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.24; import "../interfaces/IERC20.sol"; /** * @title Contract used to store layout for the USDTieredSTO storage */ contract USDTieredSTOStorage { ///////////// // Storage // ///////////// struct Tier { // NB rates mentioned below are actually price and are used like price in the logic. // How many token units a buyer gets per USD in this tier (multiplied by 10**18) uint256 rate; // How many token units a buyer gets per USD in this tier (multiplied by 10**18) when investing in POLY up to tokensDiscountPoly uint256 rateDiscountPoly; // How many tokens are available in this tier (relative to totalSupply) uint256 tokenTotal; // How many token units are available in this tier (relative to totalSupply) at the ratePerTierDiscountPoly rate uint256 tokensDiscountPoly; // How many tokens have been minted in this tier (relative to totalSupply) uint256 mintedTotal; // How many tokens have been minted in this tier (relative to totalSupply) for each fund raise type mapping (uint8 => uint256) minted; // How many tokens have been minted in this tier (relative to totalSupply) at discounted POLY rate uint256 mintedDiscountPoly; } struct Investor { // Whether investor is accredited (0 = non-accredited, 1 = accredited) uint8 accredited; // Whether we have seen the investor before (already added to investors list) uint8 seen; // Overrides for default limit in USD for non-accredited investors multiplied by 10**18 (0 = no override) uint256 nonAccreditedLimitUSDOverride; } mapping (bytes32 => mapping (bytes32 => string)) oracleKeys; // Determine whether users can invest on behalf of a beneficiary bool public allowBeneficialInvestments = false; // Whether or not the STO has been finalized bool public isFinalized; // Address of issuer reserve wallet for unsold tokens address public reserveWallet; // List of stable coin addresses address[] public usdTokens; // Current tier uint256 public currentTier; // Amount of USD funds raised uint256 public fundsRaisedUSD; // Amount of stable coins raised mapping (address => uint256) public stableCoinsRaised; // Amount in USD invested by each address mapping (address => uint256) public investorInvestedUSD; // Amount in fund raise type invested by each investor mapping (address => mapping (uint8 => uint256)) public investorInvested; // Accredited & non-accredited investor data mapping (address => Investor) public investors; // List of active stable coin addresses mapping (address => bool) public usdTokenEnabled; // List of all addresses that have been added as accredited or non-accredited without // the default limit address[] public investorsList; // Default limit in USD for non-accredited investors multiplied by 10**18 uint256 public nonAccreditedLimitUSD; // Minimum investable amount in USD uint256 public minimumInvestmentUSD; // Final amount of tokens returned to issuer uint256 public finalAmountReturned; // Array of Tiers Tier[] public tiers; }
Amount in USD invested by each address
mapping (address => uint256) public investorInvestedUSD;
15,816,827
[ 1, 6275, 316, 587, 9903, 2198, 3149, 635, 1517, 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 ]
[ 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, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 2198, 395, 280, 3605, 3149, 3378, 40, 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 ]
./full_match/5/0xe16CCDf20992d69E9E5c9be71D9cbfbA43fa4d65/sources/index.sol
change contract manager
function cCM(address manager) public virtual returns (bool) { _manager = manager; return true; }
1,896,950
[ 1, 3427, 6835, 3301, 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, 565, 445, 276, 9611, 12, 2867, 3301, 13, 1071, 5024, 1135, 261, 6430, 13, 288, 203, 3639, 389, 4181, 273, 3301, 31, 203, 3639, 327, 638, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; // contract inheritance import "./ERC721Enumerable.sol"; import "./IERC721.sol"; import "./Ownable.sol"; contract gittrees is ERC721Enumerable, Ownable { uint public mintingCost = 0.2 ether; uint public constant maxTokens = 256; uint public constant maxReservedTokens = 24; uint public constant maxGlyphTokens = 8; uint public availableTokens = 0; uint public normalTokensMinted = 0; uint public reservedTokensMinted = 0; uint public glyphTokensMinted = 0; bool public mintingEnabled = false; bool public claimingEnabled = false; string private baseTokenURI; address autoglyphsAddress = 0xd4e4078ca3495DE5B1d4dB434BEbc5a986197782; mapping(uint => uint) public glyphUsedForMint; event Mint(address indexed to, uint indexed tokenId); event MintWithGlyph(address indexed to, uint indexed tokenId, uint indexed GlyphId); constructor() payable ERC721("GitTrees", "GITTREES") {} modifier onlySender() { require(msg.sender == tx.origin, "Sender must be origin!"); _; } modifier publicMinting() { require(mintingEnabled == true, "Public Minting is not available."); _; } modifier publicClaiming() { require(claimingEnabled == true, "Public Claiming is not available."); _; } // funds withdrawals function withdrawEther() external onlyOwner { payable(msg.sender).transfer(address(this).balance); } // internal workers function addReservedTokensMinted() internal { reservedTokensMinted++; } function getReservedMintId() internal view returns (uint) { return reservedTokensMinted; } function addGlyphTokensMinted() internal { glyphTokensMinted++; } function getGlyphMintId() internal view returns (uint) { return glyphTokensMinted + maxReservedTokens; } function addNormalTokensMinted() internal { normalTokensMinted++; } function getNormalMintId() internal view returns (uint) { return normalTokensMinted + maxReservedTokens + maxGlyphTokens; } function getPublicMintableTokens() internal view returns (uint) { return availableTokens - normalTokensMinted; } function hasGlyphBeenUsedForMinting(uint glyphId_) internal view returns (bool) { return glyphUsedForMint[glyphId_] == 1; } // contract administration function setMintingQuota(uint quotaAmount_) external onlyOwner { require (quotaAmount_ <= (maxTokens - maxReservedTokens - maxGlyphTokens), "Quota over limit!" ); availableTokens = quotaAmount_; } function addMintingQuota(uint quotaAmount_) external onlyOwner { require (availableTokens + quotaAmount_ <= (maxTokens - maxReservedTokens - maxGlyphTokens), "Quota over limit!" ); availableTokens = availableTokens + quotaAmount_; } function setMintingCost(uint mintingCost_) external onlyOwner { mintingCost = mintingCost_; } function setBaseTokenURI(string memory uri_) external onlyOwner { baseTokenURI = uri_; } function setPublicMinting(bool status_) external onlyOwner { mintingEnabled = status_; } function setPublicClaiming(bool status_) external onlyOwner { claimingEnabled = status_; } function setAutoglyphsAddress(address address_) external onlyOwner { autoglyphsAddress = address_; } // view functions function tokenURI(uint tokenId_) public view override returns (string memory) { return string(abi.encodePacked(baseTokenURI, Strings.toString(tokenId_))); } function getTokensOfAddress(address address_) public view returns (uint[] memory) { uint _tokenBalance = balanceOf(address_); uint[] memory _tokenIds = new uint[](_tokenBalance); for (uint i = 0; i < _tokenBalance; i++) { _tokenIds[i] = tokenOfOwnerByIndex(address_, i); } return _tokenIds; } function getAvailableSeeds() public view returns (uint) { return availableTokens - normalTokensMinted; } function getRemainingGlyphMints() public view returns (uint) { return maxGlyphTokens - glyphTokensMinted; } // minting functions (owner only) function ownerMintReservedTokens() external onlyOwner { require(reservedTokensMinted + 1 <= maxReservedTokens, "Over Maximum Reserved Tokens!"); uint _mintId = getReservedMintId(); addReservedTokensMinted(); _mint(msg.sender, _mintId); emit Mint(msg.sender, _mintId); } function ownerMintNormalTokens() external onlyOwner { require(normalTokensMinted + 1 <= availableTokens, "No available tokens remaining!"); uint _mintId = getNormalMintId(); addNormalTokensMinted(); _mint(msg.sender, _mintId); emit Mint(msg.sender, _mintId); } function ownerMintWithGlyph() external onlyOwner { require(glyphTokensMinted + 1 <= maxGlyphTokens, "No Glyph tokens remaining!"); uint _mintId = getGlyphMintId(); addGlyphTokensMinted(); _mint(msg.sender, _mintId); emit Mint(msg.sender, _mintId); } // minting functions (normal) function normalMint() payable external onlySender publicMinting { require(msg.value == mintingCost, "Wrong Cost!"); require(normalTokensMinted + 1 <= availableTokens, "No available tokens remaining!"); uint _mintId = getNormalMintId(); addNormalTokensMinted(); _mint(msg.sender, _mintId); emit Mint(msg.sender, _mintId); } function mintWithGlyph(uint glyphId_) external onlySender publicClaiming { require(msg.sender == IERC721(autoglyphsAddress).ownerOf(glyphId_), "You do not own this Autoglyph!"); require(hasGlyphBeenUsedForMinting(glyphId_) == false, "Glyph already used for minting!"); require(glyphTokensMinted + 1 <= maxGlyphTokens, "No Glyph tokens remaining!"); uint _mintId = getGlyphMintId(); glyphUsedForMint[glyphId_]++; addGlyphTokensMinted(); _mint(msg.sender, _mintId); emit MintWithGlyph(msg.sender, _mintId, glyphId_); } }
contract inheritance
import "./ERC721Enumerable.sol";
10,417,893
[ 1, 16351, 16334, 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, 0 ]
[ 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, 0 ]
[ 1, 5666, 25165, 654, 39, 27, 5340, 3572, 25121, 18, 18281, 14432, 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 ]
./full_match/42/0x7ac9fAb3D60592EcA53641bC0E82Cfaf4DF2c92d/sources/Users/apple/Documents/yai-protocol-private/contracts/strategies/Compound/compoundNoFoldStrategyTestnet.sol
These tokens cannot be claimed by the controller
contract CompoundNoFoldStrategy is IStrategy, RewardTokenProfitNotifier, CompoundInteractor { using SafeMath for uint256; using SafeERC20 for IERC20; event ProfitNotClaimed(); event TooLowBalance(); ERC20Detailed public underlying; CompleteCToken public ctoken; ComptrollerInterface public comptroller; address public vault; address public uniswapRouterV2; uint256 public suppliedInUnderlying; bool public liquidationAllowed = true; uint256 public sellFloor = 0; bool public allowEmergencyLiquidityShortage = false; mapping(address => bool) public unsalvagableTokens; modifier restricted() { require(msg.sender == vault || msg.sender == address(controller()) || msg.sender == address(governance()), "The sender has to be the controller or vault"); _; } constructor( address _storage, address _underlying, address _ctoken, address _vault, address _comptroller, address _comp, address _uniswap ) RewardTokenProfitNotifier(_storage, _comp) CompoundInteractor(_underlying, _ctoken, _comptroller) public { require(IVault(_vault).underlying() == _underlying, "vault does not support underlying"); comptroller = ComptrollerInterface(_comptroller); comp = ERC20Detailed(_comp); underlying = ERC20Detailed(_underlying); ctoken = CompleteCToken(_ctoken); vault = _vault; uniswapRouterV2 = _uniswap; unsalvagableTokens[_underlying] = true; unsalvagableTokens[_ctoken] = true; unsalvagableTokens[_comp] = true; } modifier updateSupplyInTheEnd() { _; suppliedInUnderlying = ctoken.balanceOfUnderlying(address(this)); } function depositArbCheck() public view returns (bool) { return true; } function investAllUnderlying() public restricted updateSupplyInTheEnd { uint256 balance = underlying.balanceOf(address(this)); _supply(balance); } function withdrawAllToVault() external restricted updateSupplyInTheEnd { if (allowEmergencyLiquidityShortage) { withdrawMaximum(); withdrawAllWeInvested(); } IERC20(address(underlying)).safeTransfer(vault, underlying.balanceOf(address(this))); } function withdrawAllToVault() external restricted updateSupplyInTheEnd { if (allowEmergencyLiquidityShortage) { withdrawMaximum(); withdrawAllWeInvested(); } IERC20(address(underlying)).safeTransfer(vault, underlying.balanceOf(address(this))); } } else { function emergencyExit() external onlyGovernance updateSupplyInTheEnd { withdrawMaximum(); } function withdrawMaximum() internal updateSupplyInTheEnd { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } redeemMaximum(); } function withdrawMaximum() internal updateSupplyInTheEnd { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } redeemMaximum(); } } else { function withdrawAllWeInvested() internal updateSupplyInTheEnd { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } uint256 currentBalance = ctoken.balanceOfUnderlying(address(this)); mustRedeemPartial(currentBalance); } function withdrawAllWeInvested() internal updateSupplyInTheEnd { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } uint256 currentBalance = ctoken.balanceOfUnderlying(address(this)); mustRedeemPartial(currentBalance); } } else { function withdrawToVault(uint256 amountUnderlying) external restricted updateSupplyInTheEnd { if (amountUnderlying <= underlying.balanceOf(address(this))) { IERC20(address(underlying)).safeTransfer(vault, amountUnderlying); return; } } function withdrawToVault(uint256 amountUnderlying) external restricted updateSupplyInTheEnd { if (amountUnderlying <= underlying.balanceOf(address(this))) { IERC20(address(underlying)).safeTransfer(vault, amountUnderlying); return; } } mustRedeemPartial(amountUnderlying); IERC20(address(underlying)).safeTransfer(vault, amountUnderlying); investAllUnderlying(); function doHardWork() public restricted { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } investAllUnderlying(); } function doHardWork() public restricted { if (liquidationAllowed) { claimComp(); liquidateComp(); emit ProfitNotClaimed(); } investAllUnderlying(); } } else { function redeemMaximum() internal { redeemMaximumToken(); } function mustRedeemPartial(uint256 amountUnderlying) internal { require( ctoken.getCash() >= amountUnderlying, "market cash cannot cover liquidity" ); _redeemUnderlying(amountUnderlying); } function salvage(address recipient, address token, uint256 amount) public onlyGovernance { require(!unsalvagableTokens[token], "token is defined as not salvagable"); IERC20(token).safeTransfer(recipient, amount); } function liquidateComp() internal { uint256 balance = comp.balanceOf(address(this)); if (balance < sellFloor) { emit TooLowBalance(); return; } balance = comp.balanceOf(address(this)); IERC20(address(comp)).safeApprove(address(uniswapRouterV2), 0); IERC20(address(comp)).safeApprove(address(uniswapRouterV2), balance); address[] memory path = new address[](3); path[0] = address(comp); path[1] = IUniswapV2Router02(uniswapRouterV2).WETH(); path[2] = address(underlying); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balance, amountOutMin, path, address(this), block.timestamp ); } function liquidateComp() internal { uint256 balance = comp.balanceOf(address(this)); if (balance < sellFloor) { emit TooLowBalance(); return; } balance = comp.balanceOf(address(this)); IERC20(address(comp)).safeApprove(address(uniswapRouterV2), 0); IERC20(address(comp)).safeApprove(address(uniswapRouterV2), balance); address[] memory path = new address[](3); path[0] = address(comp); path[1] = IUniswapV2Router02(uniswapRouterV2).WETH(); path[2] = address(underlying); IUniswapV2Router02(uniswapRouterV2).swapExactTokensForTokens( balance, amountOutMin, path, address(this), block.timestamp ); } notifyProfitInRewardToken(balance); uint256 amountOutMin = 1; function investedUnderlyingBalance() public view returns (uint256) { return underlying.balanceOf(address(this)).add(suppliedInUnderlying); } function setLiquidationAllowed( bool allowed ) external restricted { liquidationAllowed = allowed; } function setAllowLiquidityShortage( bool allowed ) external restricted { allowEmergencyLiquidityShortage = allowed; } function setSellFloor(uint256 value) external restricted { sellFloor = value; } }
16,230,679
[ 1, 29690, 2430, 2780, 506, 7516, 329, 635, 326, 2596, 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, 16351, 21327, 2279, 15592, 4525, 353, 467, 4525, 16, 534, 359, 1060, 1345, 626, 7216, 14889, 16, 21327, 2465, 3362, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 203, 565, 871, 1186, 7216, 1248, 9762, 329, 5621, 203, 565, 871, 15869, 10520, 13937, 5621, 203, 203, 565, 4232, 39, 3462, 40, 6372, 1071, 6808, 31, 203, 565, 14575, 1268, 969, 1071, 276, 2316, 31, 203, 565, 1286, 337, 1539, 1358, 1071, 532, 337, 1539, 31, 203, 203, 565, 1758, 1071, 9229, 31, 203, 203, 565, 1758, 1071, 640, 291, 91, 438, 8259, 58, 22, 31, 203, 565, 2254, 5034, 1071, 4580, 382, 14655, 6291, 31, 203, 565, 1426, 1071, 4501, 26595, 367, 5042, 273, 638, 31, 203, 565, 2254, 5034, 1071, 357, 80, 42, 5807, 273, 374, 31, 203, 565, 1426, 1071, 1699, 1514, 24530, 48, 18988, 24237, 4897, 410, 273, 629, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 16804, 287, 90, 346, 429, 5157, 31, 203, 203, 203, 565, 9606, 15693, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 9229, 747, 1234, 18, 15330, 422, 1758, 12, 5723, 10756, 747, 1234, 18, 15330, 422, 1758, 12, 75, 1643, 82, 1359, 1435, 3631, 203, 5411, 315, 1986, 5793, 711, 358, 506, 326, 2596, 578, 9229, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 3885, 12, 203, 3639, 1758, 389, 5697, 16, 203, 3639, 1758, 389, 9341, 6291, 16, 2 ]
pragma solidity 0.4.24; /** @title Mock contract in order to test time logic reliably. */ /** @author Kerman Kohli - <[email protected]> */ contract MockTime { // solhint-disable-next-line uint256 public currentTime = block.timestamp; /** PUBLIC FUNCTIONS */ /** @dev Set the time in the contract * */ function setTime(uint256 _time) public { currentTime = _time; } /** @dev Turn back the time in the contract * */ function turnBackTime(uint256 _seconds) public { currentTime -= _seconds; } /** INTERNAL FUNCTIONS */ /** @dev A mock of the current timsstamp * */ function currentTimestamp() internal view returns (uint256 _timetstamp) { return currentTime; } }
* @dev Turn back the time in the contract/
function turnBackTime(uint256 _seconds) public { currentTime -= _seconds; }
12,755,207
[ 1, 15858, 1473, 326, 813, 316, 326, 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, 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, 7005, 2711, 950, 12, 11890, 5034, 389, 7572, 13, 203, 3639, 1071, 203, 565, 288, 203, 3639, 6680, 3947, 389, 7572, 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 ]
pragma solidity ^0.4.24; // File: contracts/upgradeability/ImplementationStorage.sol /** * @title ImplementationStorage * @dev This contract stores proxy implementation address. */ contract ImplementationStorage { /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "cvc.proxy.implementation", and is validated in the constructor. */ bytes32 internal constant IMPLEMENTATION_SLOT = 0xa490aab0d89837371982f93f57ffd20c47991f88066ef92475bc8233036969bb; /** * @dev Constructor */ constructor() public { assert(IMPLEMENTATION_SLOT == keccak256("cvc.proxy.implementation")); } /** * @dev Returns the current implementation. * @return Address of the current implementation */ function implementation() public view returns (address impl) { bytes32 slot = IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param addr address to check * @return whether the target address is a contract */ function isContract(address addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(addr) } return size > 0; } } // File: contracts/upgradeability/CvcProxy.sol /** * @title CvcProxy * @dev Transparent proxy with upgradeability functions and authorization control. */ contract CvcProxy is ImplementationStorage { /** * @dev Emitted when the implementation is upgraded. * @param implementation Address of the new implementation. */ event Upgraded(address implementation); /** * @dev Emitted when the administration has been transferred. * @param previousAdmin Address of the previous admin. * @param newAdmin Address of the new admin. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "cvc.proxy.admin", and is validated in the constructor. */ bytes32 private constant ADMIN_SLOT = 0x2bbac3e52eee27be250d682577104e2abe776c40160cd3167b24633933100433; /** * @dev Modifier to check whether the `msg.sender` is the admin. * It executes the function if called by admin. Otherwise, it will delegate the call to the implementation. */ modifier ifAdmin() { if (msg.sender == currentAdmin()) { _; } else { delegate(implementation()); } } /** * Contract constructor. * It sets the `msg.sender` as the proxy admin. */ constructor() public { assert(ADMIN_SLOT == keccak256("cvc.proxy.admin")); setAdmin(msg.sender); } /** * @dev Fallback function. */ function() external payable { require(msg.sender != currentAdmin(), "Message sender is not contract admin"); delegate(implementation()); } /** * @dev Changes the admin of the proxy. * Only the current admin can call this function. * @param _newAdmin Address to transfer proxy administration to. */ function changeAdmin(address _newAdmin) external ifAdmin { require(_newAdmin != address(0), "Cannot change contract admin to zero address"); emit AdminChanged(currentAdmin(), _newAdmin); setAdmin(_newAdmin); } /** * @dev Allows the proxy owner to upgrade the current version of the proxy. * @param _implementation the address of the new implementation to be set. */ function upgradeTo(address _implementation) external ifAdmin { upgradeImplementation(_implementation); } /** * @dev Allows the proxy owner to upgrade and call the new implementation * to initialize whatever is needed through a low level call. * @param _implementation the address of the new implementation to be set. * @param _data the msg.data to bet sent in the low level call. This parameter may include the function * signature of the implementation to be called with the needed payload. */ function upgradeToAndCall(address _implementation, bytes _data) external payable ifAdmin { upgradeImplementation(_implementation); //solium-disable-next-line security/no-call-value require(address(this).call.value(msg.value)(_data), "Upgrade error: initialization method call failed"); } /** * @dev Returns the Address of the proxy admin. * @return address */ function admin() external view ifAdmin returns (address) { return currentAdmin(); } /** * @dev Upgrades the implementation address. * @param _newImplementation the address of the new implementation to be set */ function upgradeImplementation(address _newImplementation) private { address currentImplementation = implementation(); require(currentImplementation != _newImplementation, "Upgrade error: proxy contract already uses specified implementation"); setImplementation(_newImplementation); emit Upgraded(_newImplementation); } /** * @dev Delegates execution to an implementation contract. * This is a low level function that doesn't return to its internal call site. * It will return to the external caller whatever the implementation returns. * @param _implementation Address to delegate. */ function delegate(address _implementation) private { assembly { // Copy msg.data. calldatacopy(0, 0, calldatasize) // Call current implementation passing proxy calldata. let result := delegatecall(gas, _implementation, 0, calldatasize, 0, 0) // Copy the returned data. returndatacopy(0, 0, returndatasize) // Propagate result (delegatecall returns 0 on error). switch result case 0 {revert(0, returndatasize)} default {return (0, returndatasize)} } } /** * @return The admin slot. */ function currentAdmin() private view returns (address proxyAdmin) { bytes32 slot = ADMIN_SLOT; assembly { proxyAdmin := sload(slot) } } /** * @dev Sets the address of the proxy admin. * @param _newAdmin Address of the new proxy admin. */ function setAdmin(address _newAdmin) private { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, _newAdmin) } } /** * @dev Sets the implementation address of the proxy. * @param _newImplementation Address of the new implementation. */ function setImplementation(address _newImplementation) private { require( AddressUtils.isContract(_newImplementation), "Cannot set new implementation: no contract code at contract address" ); bytes32 slot = IMPLEMENTATION_SLOT; assembly { sstore(slot, _newImplementation) } } }
* @dev Sets the address of the proxy admin. @param _newAdmin Address of the new proxy admin./
function setAdmin(address _newAdmin) private { bytes32 slot = ADMIN_SLOT; assembly { sstore(slot, _newAdmin) } }
113,203
[ 1, 2785, 326, 1758, 434, 326, 2889, 3981, 18, 225, 389, 2704, 4446, 5267, 434, 326, 394, 2889, 3981, 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, 444, 4446, 12, 2867, 389, 2704, 4446, 13, 3238, 288, 203, 3639, 1731, 1578, 4694, 273, 25969, 67, 55, 1502, 56, 31, 203, 3639, 19931, 288, 203, 5411, 272, 2233, 12, 14194, 16, 389, 2704, 4446, 13, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x118E662de0C4cdc2f8AD0fb1c6Ef4a85222baCF0/sources/contracts/base/Multicall.sol
@notice Multiple calls on proxy functions @param _data The destination address
function multicall(bytes[] calldata _data) public payable { unlockEth(); for (uint256 i = 0; i < _data.length;) { (bool success, bytes memory result) = address(this).delegatecall(_data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } unchecked { ++i; } } unlockEth(); }
3,587,932
[ 1, 8438, 4097, 603, 2889, 4186, 225, 389, 892, 1021, 2929, 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 ]
[ 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, 445, 1778, 335, 454, 12, 3890, 8526, 745, 892, 389, 892, 13, 1071, 8843, 429, 288, 203, 3639, 7186, 41, 451, 5621, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 389, 892, 18, 2469, 30943, 288, 203, 5411, 261, 6430, 2216, 16, 1731, 3778, 563, 13, 273, 1758, 12, 2211, 2934, 22216, 1991, 24899, 892, 63, 77, 19226, 203, 203, 5411, 309, 16051, 4768, 13, 288, 203, 7734, 309, 261, 2088, 18, 2469, 411, 23797, 13, 15226, 5621, 203, 203, 7734, 19931, 288, 203, 10792, 563, 519, 527, 12, 2088, 16, 374, 92, 3028, 13, 203, 7734, 289, 203, 203, 7734, 15226, 12, 21457, 18, 3922, 12, 2088, 16, 261, 1080, 3719, 1769, 203, 5411, 289, 203, 203, 5411, 22893, 288, 203, 7734, 965, 77, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 7186, 41, 451, 5621, 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 ]
pragma solidity >=0.6.0 <0.7.0; //SPDX-License-Identifier: MIT import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import 'base64-sol/base64.sol'; import './HexStrings.sol'; import './ToColor.sol'; //learn more: https://docs.openzeppelin.com/contracts/3.x/erc721 // GET LISTED ON OPENSEA: https://testnets.opensea.io/get-listed/step-two contract YourCollectible is ERC721, Ownable { using Strings for uint256; using HexStrings for uint160; using ToColor for bytes3; using Counters for Counters.Counter; Counters.Counter private _tokenIds; string[] private scriptures = [ "Blessed are the poor in spirt", "Blessed are those who mourn", "Blessed are the meek", "Blessed are those who hunger and thirst for righteousness", "Blessed are the merciful", "Blessed are the pure in heart", "Blessed are the peacemakers", "Blessed are those who are persecuted because of righteousness" ]; constructor() public ERC721("Cross Bearer", "ONCHAINCROSS") { // RELEASE THE LOOGIES! } mapping (uint256 => bytes3) public color; mapping (uint256 => bytes3) public bgColor; mapping (uint256 => uint256) public chubbiness; mapping (uint256 => string) public scripture; uint256 mintDeadline = block.timestamp + 24 hours; function mintItem() public returns (uint256) { _tokenIds.increment(); uint256 id = _tokenIds.current(); require(id < 144000, "Minting is complete"); //emd // require(msg.value > 1, "Need to pay some Eth"); _mint(msg.sender, id); bytes32 predictableRandom = keccak256(abi.encodePacked( blockhash(block.number-1), msg.sender, address(this) )); color[id] = bytes2(predictableRandom[0]) | ( bytes2(predictableRandom[1]) >> 8 ) | ( bytes3(predictableRandom[2]) >> 16 ); // set a contrasting background color bgColor[id] = ( bytes1(uint8(255-uint8(predictableRandom[0]))) ^ 0xFF ) | ( bytes2((bytes2(uint16(255-uint8(predictableRandom[0]))) >> 8) ^ 0xFFFF) ) | ( bytes3((bytes3(uint24(255-uint8(predictableRandom[0]))) >> 16) ) ^ 0xFFFFFF ) ; chubbiness[id] = 35+((55*uint256(uint8(predictableRandom[3])))/255); scripture[id] = getScripture(id); return id; } function random(string memory input) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(input))); } function getScripture(uint256 id) public view returns (string memory) { return pluck(id, "cross-bearer", scriptures); } function pluck(uint256 tokenId, string memory keyPrefix, string[] memory sourceArray) internal pure returns (string memory) { uint256 rand = random(string(abi.encodePacked(keyPrefix, uint2str(tokenId)))); string memory output = sourceArray[rand % sourceArray.length]; return output; } function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "not exist"); string memory name = string(abi.encodePacked('cross-bearer ',id.toString())); string memory description = string(abi.encodePacked('color #',color[id].toColor(),' bg of ',bgColor[id].toColor(), '!!' ) ); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', name, //'", "description":"', //description, //'", "external_url":"https://burnyboys.com/token/', //id.toString(), '", "attributes": [{"trait_type": "color", "value": "#', color[id].toColor(), '"}], "owner":"', (uint160(ownerOf(id))).toHexString(20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) ) ); } function generateSVGofTokenById(uint256 id) internal view returns (string memory) { string memory svg = string(abi.encodePacked( '<svg width="400" height="400" xmlns="http://www.w3.org/2000/svg">', renderCrossToken(id), '</svg>' )); return svg; } function renderCrossToken(uint256 id) public view returns (string memory) { string memory render = string(abi.encodePacked( '<rect x="0" y="0" width="400" height="400" style="fill:#', bgColor[id].toColor(), '"/>', '<rect x="196" y="90" width="14" height="176" style="fill:#', color[id].toColor(), '"/>', '<rect x="150" y="143" width="102" height="14" style="fill:#', color[id].toColor(), '"/>', '<text x="50%" y="10%" dominant-baseline="middle" text-anchor="middle">', scripture[id], '</text>' )); return render; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len; while (_i != 0) { k = k-1; uint8 temp = (48 + uint8(_i - _i / 10 * 10)); bytes1 b1 = bytes1(temp); bstr[k] = b1; _i /= 10; } return string(bstr); } }
'", "description":"',description,'", "external_url":"https:burnyboys.com/token/',id.toString(),
function tokenURI(uint256 id) public view override returns (string memory) { require(_exists(id), "not exist"); string memory name = string(abi.encodePacked('cross-bearer ',id.toString())); string memory description = string(abi.encodePacked('color #',color[id].toColor(),' bg of ',bgColor[id].toColor(), '!!' ) ); string memory image = Base64.encode(bytes(generateSVGofTokenById(id))); return string( abi.encodePacked( 'data:application/json;base64,', Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "attributes": [{"trait_type": "color", "value": "#', color[id].toColor(), '"}], "owner":"', (uint160(ownerOf(id))).toHexString(20), '", "image": "', 'data:image/svg+xml;base64,', image, '"}' ) ) ) ) ); }
12,780,620
[ 1, 11, 3113, 315, 3384, 15563, 2187, 3384, 11189, 3113, 315, 9375, 67, 718, 15563, 4528, 30, 70, 321, 93, 1075, 1900, 18, 832, 19, 2316, 19, 2187, 350, 18, 10492, 9334, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1147, 3098, 12, 11890, 5034, 612, 13, 1071, 1476, 3849, 1135, 261, 1080, 3778, 13, 288, 203, 565, 2583, 24899, 1808, 12, 350, 3631, 315, 902, 1005, 8863, 203, 565, 533, 3778, 508, 273, 533, 12, 21457, 18, 3015, 4420, 329, 2668, 14653, 17, 29400, 264, 2265, 350, 18, 10492, 1435, 10019, 203, 565, 533, 3778, 2477, 273, 533, 12, 21457, 18, 3015, 4420, 329, 2668, 3266, 468, 2187, 3266, 63, 350, 8009, 869, 2957, 9334, 11, 7611, 434, 2265, 12370, 2957, 63, 350, 8009, 869, 2957, 9334, 11817, 5124, 262, 11272, 203, 565, 533, 3778, 1316, 273, 3360, 1105, 18, 3015, 12, 3890, 12, 7163, 26531, 792, 1345, 5132, 12, 350, 3719, 1769, 203, 203, 565, 327, 203, 1377, 533, 12, 203, 1850, 24126, 18, 3015, 4420, 329, 12, 203, 5411, 296, 892, 30, 3685, 19, 1977, 31, 1969, 1105, 16, 2187, 203, 5411, 3360, 1105, 18, 3015, 12, 203, 7734, 1731, 12, 203, 8227, 24126, 18, 3015, 4420, 329, 12, 203, 12900, 2292, 6, 529, 15563, 2187, 203, 12900, 508, 16, 203, 12900, 19197, 315, 4350, 6877, 306, 16711, 22513, 67, 723, 6877, 315, 3266, 3113, 315, 1132, 6877, 6619, 2187, 203, 12900, 2036, 63, 350, 8009, 869, 2957, 9334, 203, 12900, 2119, 97, 6487, 315, 8443, 15563, 2187, 203, 12900, 261, 11890, 16874, 12, 8443, 951, 12, 350, 3719, 2934, 869, 14866, 12, 3462, 3631, 203, 12900, 19197, 315, 2730, 6877, 14912, 203, 12900, 296, 892, 30, 2730, 19, 11451, 15, 2902, 31, 1969, 1105, 16, 2187, 203, 12900, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; contract ExampleToken is ERC20, Ownable { /** * @dev assign totalSupply to account creating this contract */ constructor() public ERC20("Example", "EMP") { _mint(msg.sender, 1000000000000000000000000000); } }
* @dev assign totalSupply to account creating this contract /
constructor() public ERC20("Example", "EMP") { _mint(msg.sender, 1000000000000000000000000000); }
14,087,330
[ 1, 6145, 2078, 3088, 1283, 358, 2236, 4979, 333, 6835, 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 ]
[ 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, 3885, 1435, 1071, 4232, 39, 3462, 2932, 10908, 3113, 315, 3375, 52, 7923, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 2130, 12648, 12648, 2787, 11706, 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.5.3; import "openzeppelin-solidity/contracts/math/SafeMath.sol"; import "openzeppelin-solidity/contracts/ownership/Ownable.sol"; import "./interfaces/IReserve.sol"; import "./interfaces/ISortedOracles.sol"; import "../common/FixidityLib.sol"; import "../common/Initializable.sol"; import "../common/UsingRegistry.sol"; import "../common/libraries/ReentrancyGuard.sol"; /** * @title Ensures price stability of StableTokens with respect to their pegs */ contract Reserve is IReserve, Ownable, Initializable, UsingRegistry, ReentrancyGuard { using SafeMath for uint256; using FixidityLib for FixidityLib.Fraction; struct TobinTaxCache { uint128 numerator; uint128 timestamp; } mapping(address => bool) public isToken; address[] private _tokens; TobinTaxCache public tobinTaxCache; uint256 public tobinTaxStalenessThreshold; uint256 public constant TOBIN_TAX_NUMERATOR = 5000000000000000000000; // 0.005 mapping(address => bool) public isSpender; mapping(address => bool) public isOtherReserveAddress; address[] public otherReserveAddresses; bytes32[] public assetAllocationSymbols; mapping(bytes32 => uint256) public assetAllocationWeights; uint256 public lastSpendingDay; uint256 public spendingLimit; FixidityLib.Fraction private spendingRatio; uint256 public frozenReserveGoldStartBalance; uint256 public frozenReserveGoldStartDay; uint256 public frozenReserveGoldDays; event TobinTaxStalenessThresholdSet(uint256 value); event DailySpendingRatioSet(uint256 ratio); event TokenAdded(address indexed token); event TokenRemoved(address indexed token, uint256 index); event SpenderAdded(address indexed spender); event SpenderRemoved(address indexed spender); event OtherReserveAddressAdded(address indexed otherReserveAddress); event OtherReserveAddressRemoved(address indexed otherReserveAddress, uint256 index); event AssetAllocationSet(bytes32[] symbols, uint256[] weights); event ReserveGoldTransferred(address indexed spender, address indexed to, uint256 value); modifier isStableToken(address token) { require(isToken[token], "token addr was never registered"); _; } function() external payable {} // solhint-disable no-empty-blocks /** * @notice Used in place of the constructor to allow the contract to be upgradable via proxy. * @param registryAddress The address of the registry core smart contract. * @param _tobinTaxStalenessThreshold The initial number of seconds to cache tobin tax value for. * @param _frozenGold The balance of reserve gold that is frozen. * @param _frozenDays The number of days during which the frozen gold thaws. */ function initialize( address registryAddress, uint256 _tobinTaxStalenessThreshold, uint256 _spendingRatio, uint256 _frozenGold, uint256 _frozenDays, bytes32[] calldata _assetAllocationSymbols, uint256[] calldata _assetAllocationWeights ) external initializer { _transferOwnership(msg.sender); setRegistry(registryAddress); setTobinTaxStalenessThreshold(_tobinTaxStalenessThreshold); setDailySpendingRatio(_spendingRatio); setFrozenGold(_frozenGold, _frozenDays); setAssetAllocations(_assetAllocationSymbols, _assetAllocationWeights); } /** * @notice Sets the number of seconds to cache the tobin tax value for. * @param value The number of seconds to cache the tobin tax value for. */ function setTobinTaxStalenessThreshold(uint256 value) public onlyOwner { require(value > 0, "value was zero"); tobinTaxStalenessThreshold = value; emit TobinTaxStalenessThresholdSet(value); } /** * @notice Set the ratio of reserve that is spendable per day. * @param ratio Spending ratio as unwrapped Fraction. */ function setDailySpendingRatio(uint256 ratio) public onlyOwner { spendingRatio = FixidityLib.wrap(ratio); require(spendingRatio.lte(FixidityLib.fixed1()), "spending ratio cannot be larger than 1"); emit DailySpendingRatioSet(ratio); } /** * @notice Get daily spending ratio. * @return Spending ratio as unwrapped Fraction. */ function getDailySpendingRatio() public view returns (uint256) { return spendingRatio.unwrap(); } /** * @notice Sets the balance of reserve gold frozen from transfer. * @param frozenGold The amount of cGLD frozen. * @param frozenDays The number of days the frozen cGLD thaws over. */ function setFrozenGold(uint256 frozenGold, uint256 frozenDays) public onlyOwner { require(frozenGold <= address(this).balance, "Cannot freeze more than balance"); frozenReserveGoldStartBalance = frozenGold; frozenReserveGoldStartDay = now / 1 days; frozenReserveGoldDays = frozenDays; } /** * @notice Sets target allocations for Celo Gold and a diversified basket of non-Celo assets. * @param symbols The symbol of each asset in the Reserve portfolio. * @param weights The weight for the corresponding asset as unwrapped Fixidity.Fraction. */ function setAssetAllocations(bytes32[] memory symbols, uint256[] memory weights) public onlyOwner { require(symbols.length == weights.length, "Array length mismatch"); FixidityLib.Fraction memory sum = FixidityLib.wrap(0); for (uint256 i = 0; i < weights.length; i = i.add(1)) { sum = sum.add(FixidityLib.wrap(weights[i])); } require(sum.equals(FixidityLib.fixed1()), "Sum of asset allocation must be 1"); for (uint256 i = 0; i < assetAllocationSymbols.length; i = i.add(1)) { delete assetAllocationWeights[assetAllocationSymbols[i]]; } assetAllocationSymbols = symbols; for (uint256 i = 0; i < symbols.length; i = i.add(1)) { require(assetAllocationWeights[symbols[i]] == 0, "Cannot set weight twice"); assetAllocationWeights[symbols[i]] = weights[i]; } require(assetAllocationWeights["cGLD"] != 0, "Must set cGLD asset weight"); emit AssetAllocationSet(symbols, weights); } /** * @notice Add a token that the reserve will stabilize. * @param token The address of the token being stabilized. * @return Returns true if the transaction succeeds. */ function addToken(address token) external onlyOwner nonReentrant returns (bool) { require(!isToken[token], "token addr already registered"); // Require an exchange rate between the new token and Gold exists. address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID); ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress); uint256 tokenAmount; uint256 goldAmount; (tokenAmount, goldAmount) = sortedOracles.medianRate(token); require(goldAmount > 0, "median rate returned 0 gold"); isToken[token] = true; _tokens.push(token); emit TokenAdded(token); return true; } /** * @notice Remove a token that the reserve will no longer stabilize. * @param token The address of the token no longer being stabilized. * @param index The index of the token in _tokens. * @return Returns true if the transaction succeeds. */ function removeToken(address token, uint256 index) external onlyOwner isStableToken(token) returns (bool) { require( index < _tokens.length && _tokens[index] == token, "index into tokens list not mapped to token" ); isToken[token] = false; address lastItem = _tokens[_tokens.length.sub(1)]; _tokens[index] = lastItem; _tokens.length = _tokens.length.sub(1); emit TokenRemoved(token, index); return true; } /** * @notice Add a reserve address whose balance shall be included in the reserve ratio. * @param reserveAddress The reserve address to add. * @return Returns true if the transaction succeeds. */ function addOtherReserveAddress(address reserveAddress) external onlyOwner nonReentrant returns (bool) { require(!isOtherReserveAddress[reserveAddress], "reserve addr already added"); isOtherReserveAddress[reserveAddress] = true; otherReserveAddresses.push(reserveAddress); emit OtherReserveAddressAdded(reserveAddress); return true; } /** * @notice Remove reserve address whose balance shall no longer be included in the reserve ratio. * @param reserveAddress The reserve address to remove. * @param index The index of the reserve address in otherReserveAddresses. * @return Returns true if the transaction succeeds. */ function removeOtherReserveAddress(address reserveAddress, uint256 index) external onlyOwner returns (bool) { require(isOtherReserveAddress[reserveAddress], "reserve addr was never added"); require( index < otherReserveAddresses.length && otherReserveAddresses[index] == reserveAddress, "index into reserve list not mapped to address" ); isOtherReserveAddress[reserveAddress] = false; address lastItem = otherReserveAddresses[otherReserveAddresses.length.sub(1)]; otherReserveAddresses[index] = lastItem; otherReserveAddresses.length = otherReserveAddresses.length.sub(1); emit OtherReserveAddressRemoved(reserveAddress, index); return true; } /** * @notice Gives an address permission to spend Reserve funds. * @param spender The address that is allowed to spend Reserve funds. */ function addSpender(address spender) external onlyOwner { isSpender[spender] = true; emit SpenderAdded(spender); } /** * @notice Takes away an address's permission to spend Reserve funds. * @param spender The address that is to be no longer allowed to spend Reserve funds. */ function removeSpender(address spender) external onlyOwner { isSpender[spender] = false; emit SpenderRemoved(spender); } /** * @notice Transfer gold to a whitelisted address subject to reserve spending limits. * @param to The address that will receive the gold. * @param value The amount of gold to transfer. * @return Returns true if the transaction succeeds. */ function transferGold(address payable to, uint256 value) external returns (bool) { require(isSpender[msg.sender], "sender not allowed to transfer Reserve funds"); require(isOtherReserveAddress[to], "can only transfer to other reserve address"); uint256 currentDay = now / 1 days; if (currentDay > lastSpendingDay) { uint256 balance = getUnfrozenReserveGoldBalance(); lastSpendingDay = currentDay; spendingLimit = spendingRatio.multiply(FixidityLib.newFixed(balance)).fromFixed(); } require(spendingLimit >= value, "Exceeding spending limit"); spendingLimit = spendingLimit.sub(value); return _transferGold(to, value); } /** * @notice Transfer unfrozen gold to any address. * @param to The address that will receive the gold. * @param value The amount of gold to transfer. * @return Returns true if the transaction succeeds. */ function _transferGold(address payable to, uint256 value) internal returns (bool) { require(value <= getUnfrozenBalance(), "Exceeding unfrozen reserves"); to.transfer(value); emit ReserveGoldTransferred(msg.sender, to, value); return true; } /** * @notice Transfer unfrozen gold to any address, used for one side of CP-DOTO. * @param to The address that will receive the gold. * @param value The amount of gold to transfer. * @return Returns true if the transaction succeeds. */ function transferExchangeGold(address payable to, uint256 value) external onlyRegisteredContract(EXCHANGE_REGISTRY_ID) returns (bool) { return _transferGold(to, value); } /** * @notice Returns the tobin tax, recomputing it if it's stale. * @return The tobin tax amount as a fraction. */ function getOrComputeTobinTax() external nonReentrant returns (uint256, uint256) { // solhint-disable-next-line not-rely-on-time if (now.sub(tobinTaxCache.timestamp) > tobinTaxStalenessThreshold) { tobinTaxCache.numerator = uint128(computeTobinTax().unwrap()); tobinTaxCache.timestamp = uint128(now); // solhint-disable-line not-rely-on-time } return (uint256(tobinTaxCache.numerator), FixidityLib.fixed1().unwrap()); } /** * @notice Returns the list of stabilized token addresses. * @return An array of addresses of stabilized tokens. */ function getTokens() external view returns (address[] memory) { return _tokens; } /** * @notice Returns the list other addresses included in the reserve total. * @return An array of other addresses included in the reserve total. */ function getOtherReserveAddresses() external view returns (address[] memory) { return otherReserveAddresses; } /** * @notice Returns a list of token symbols that have been allocated. * @return An array of token symbols that have been allocated. */ function getAssetAllocationSymbols() external view returns (bytes32[] memory) { return assetAllocationSymbols; } /** * @notice Returns a list of weights used for the allocation of reserve assets. * @return An array of a list of weights used for the allocation of reserve assets. */ function getAssetAllocationWeights() external view returns (uint256[] memory) { uint256[] memory weights = new uint256[](assetAllocationSymbols.length); for (uint256 i = 0; i < assetAllocationSymbols.length; i = i.add(1)) { weights[i] = assetAllocationWeights[assetAllocationSymbols[i]]; } return weights; } /** * @notice Returns the amount of unfrozen Celo Gold in the reserve. * @return The total unfrozen Celo Gold in the reserve. */ function getUnfrozenBalance() public view returns (uint256) { uint256 balance = address(this).balance; uint256 frozenReserveGold = getFrozenReserveGoldBalance(); return balance > frozenReserveGold ? balance.sub(frozenReserveGold) : 0; } /** * @notice Returns the amount of Celo Gold included in the reserve. * @return The Celo Gold amount included in the reserve. */ function getReserveGoldBalance() public view returns (uint256) { return address(this).balance.add(getOtherReserveAddressesGoldBalance()); } /** * @notice Returns the amount of Celo Gold included in other reserve addresses. * @return The Celo Gold amount included in other reserve addresses. */ function getOtherReserveAddressesGoldBalance() public view returns (uint256) { uint256 reserveGoldBalance = 0; for (uint256 i = 0; i < otherReserveAddresses.length; i = i.add(1)) { reserveGoldBalance = reserveGoldBalance.add(otherReserveAddresses[i].balance); } return reserveGoldBalance; } /** * @notice Returns the amount of unfrozen Celo Gold included in the reserve. * @return The unfrozen Celo Gold amount included in the reserve. */ function getUnfrozenReserveGoldBalance() public view returns (uint256) { return getUnfrozenBalance().add(getOtherReserveAddressesGoldBalance()); } /** * @notice Returns the amount of frozen Celo Gold in the reserve. * @return The total frozen Celo Gold in the reserve. */ function getFrozenReserveGoldBalance() public view returns (uint256) { uint256 currentDay = now / 1 days; uint256 frozenDays = currentDay.sub(frozenReserveGoldStartDay); if (frozenDays >= frozenReserveGoldDays) return 0; return frozenReserveGoldStartBalance.sub( frozenReserveGoldStartBalance.mul(frozenDays).div(frozenReserveGoldDays) ); } /** * @notice Computes the ratio of current reserve balance to total stable token valuation. * @return Reserve ratio in a fixed point format. */ function getReserveRatio() public view returns (uint256) { address sortedOraclesAddress = registry.getAddressForOrDie(SORTED_ORACLES_REGISTRY_ID); ISortedOracles sortedOracles = ISortedOracles(sortedOraclesAddress); uint256 reserveGoldBalance = getUnfrozenReserveGoldBalance(); uint256 stableTokensValueInGold = 0; FixidityLib.Fraction memory cgldWeight = FixidityLib.wrap(assetAllocationWeights["cGLD"]); for (uint256 i = 0; i < _tokens.length; i = i.add(1)) { uint256 stableAmount; uint256 goldAmount; (stableAmount, goldAmount) = sortedOracles.medianRate(_tokens[i]); uint256 stableTokenSupply = IERC20(_tokens[i]).totalSupply(); uint256 aStableTokenValueInGold = stableTokenSupply.mul(goldAmount).div(stableAmount); stableTokensValueInGold = stableTokensValueInGold.add(aStableTokenValueInGold); } return FixidityLib .newFixed(reserveGoldBalance) .divide(cgldWeight) .divide(FixidityLib.newFixed(stableTokensValueInGold)) .unwrap(); } /* * Internal functions */ /** * @notice Computes a tobin tax based on the reserve ratio. * @return The numerator of the tobin tax amount, where the denominator is 1000. */ function computeTobinTax() private view returns (FixidityLib.Fraction memory) { // The protocol calls for a 0.5% transfer tax on Celo Gold when the reserve ratio <= 2. FixidityLib.Fraction memory ratio = FixidityLib.wrap(getReserveRatio()); if (ratio.gte(FixidityLib.newFixed(2))) { return FixidityLib.wrap(0); } else { return FixidityLib.wrap(TOBIN_TAX_NUMERATOR); } } }
* @notice Sets target allocations for Celo Gold and a diversified basket of non-Celo assets. @param symbols The symbol of each asset in the Reserve portfolio. @param weights The weight for the corresponding asset as unwrapped Fixidity.Fraction./
function setAssetAllocations(bytes32[] memory symbols, uint256[] memory weights) public onlyOwner { require(symbols.length == weights.length, "Array length mismatch"); FixidityLib.Fraction memory sum = FixidityLib.wrap(0); for (uint256 i = 0; i < weights.length; i = i.add(1)) { sum = sum.add(FixidityLib.wrap(weights[i])); } require(sum.equals(FixidityLib.fixed1()), "Sum of asset allocation must be 1"); for (uint256 i = 0; i < assetAllocationSymbols.length; i = i.add(1)) { delete assetAllocationWeights[assetAllocationSymbols[i]]; } assetAllocationSymbols = symbols; for (uint256 i = 0; i < symbols.length; i = i.add(1)) { require(assetAllocationWeights[symbols[i]] == 0, "Cannot set weight twice"); assetAllocationWeights[symbols[i]] = weights[i]; } require(assetAllocationWeights["cGLD"] != 0, "Must set cGLD asset weight"); emit AssetAllocationSet(symbols, weights); }
2,528,222
[ 1, 2785, 1018, 23804, 364, 385, 24214, 611, 1673, 471, 279, 3739, 414, 939, 12886, 434, 1661, 17, 39, 24214, 7176, 18, 225, 7963, 1021, 3273, 434, 1517, 3310, 316, 326, 1124, 6527, 19933, 18, 225, 5376, 1021, 3119, 364, 326, 4656, 3310, 487, 26917, 12139, 24237, 18, 13724, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 225, 445, 444, 6672, 8763, 1012, 12, 3890, 1578, 8526, 3778, 7963, 16, 2254, 5034, 8526, 3778, 5376, 13, 203, 565, 1071, 203, 565, 1338, 5541, 203, 225, 288, 203, 565, 2583, 12, 15536, 18, 2469, 422, 5376, 18, 2469, 16, 315, 1076, 769, 13484, 8863, 203, 565, 12139, 24237, 5664, 18, 13724, 3778, 2142, 273, 12139, 24237, 5664, 18, 4113, 12, 20, 1769, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 5376, 18, 2469, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 1377, 2142, 273, 2142, 18, 1289, 12, 8585, 24237, 5664, 18, 4113, 12, 9727, 63, 77, 5717, 1769, 203, 565, 289, 203, 565, 2583, 12, 1364, 18, 14963, 12, 8585, 24237, 5664, 18, 12429, 21, 1435, 3631, 315, 3495, 434, 3310, 13481, 1297, 506, 404, 8863, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 3310, 17353, 14821, 18, 2469, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 1377, 1430, 3310, 17353, 16595, 63, 9406, 17353, 14821, 63, 77, 13563, 31, 203, 565, 289, 203, 565, 3310, 17353, 14821, 273, 7963, 31, 203, 565, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 7963, 18, 2469, 31, 277, 273, 277, 18, 1289, 12, 21, 3719, 288, 203, 1377, 2583, 12, 9406, 17353, 16595, 63, 15536, 63, 77, 13563, 422, 374, 16, 315, 4515, 444, 3119, 13605, 8863, 203, 1377, 3310, 17353, 16595, 63, 15536, 63, 77, 13563, 273, 5376, 63, 77, 15533, 203, 565, 289, 203, 565, 2 ]
./partial_match/4/0xdbE1ED80A326E0A2A348A5f7a4764c55Bac457d4/sources/PartnerRegistry.sol
Payout both the partner and the company at the same time
function payout( address[] memory tokens ) public { for(uint256 index = 0; index<tokens.length; index++){ uint256 balance = tokens[index] == Utils.eth_address()? address(this).balance : ERC20(tokens[index]).balanceOf(address(this)); uint256 partnerAmount = SafeMath.div(SafeMath.mul(balance, partnerPercentage), getTotalFeePercentage()); uint256 companyAmount = balance - partnerAmount; if(tokens[index] == Utils.eth_address()){ partnerBeneficiary.transfer(partnerAmount); companyBeneficiary.transfer(companyAmount); ERC20SafeTransfer.safeTransfer(tokens[index], partnerBeneficiary, partnerAmount); ERC20SafeTransfer.safeTransfer(tokens[index], companyBeneficiary, companyAmount); } } }
8,679,560
[ 1, 52, 2012, 3937, 326, 19170, 471, 326, 9395, 622, 326, 1967, 813, 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, 293, 2012, 12, 203, 3639, 1758, 8526, 3778, 2430, 203, 565, 262, 1071, 288, 203, 3639, 364, 12, 11890, 5034, 770, 273, 374, 31, 770, 32, 7860, 18, 2469, 31, 770, 27245, 95, 203, 5411, 2254, 5034, 11013, 273, 2430, 63, 1615, 65, 422, 6091, 18, 546, 67, 2867, 1435, 35, 1758, 12, 2211, 2934, 12296, 294, 4232, 39, 3462, 12, 7860, 63, 1615, 65, 2934, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 5411, 2254, 5034, 19170, 6275, 273, 14060, 10477, 18, 2892, 12, 9890, 10477, 18, 16411, 12, 12296, 16, 19170, 16397, 3631, 12831, 14667, 16397, 10663, 203, 5411, 2254, 5034, 9395, 6275, 273, 11013, 300, 19170, 6275, 31, 203, 5411, 309, 12, 7860, 63, 1615, 65, 422, 6091, 18, 546, 67, 2867, 10756, 95, 203, 7734, 19170, 38, 4009, 74, 14463, 814, 18, 13866, 12, 31993, 6275, 1769, 203, 7734, 9395, 38, 4009, 74, 14463, 814, 18, 13866, 12, 16840, 6275, 1769, 203, 7734, 4232, 39, 3462, 9890, 5912, 18, 4626, 5912, 12, 7860, 63, 1615, 6487, 19170, 38, 4009, 74, 14463, 814, 16, 19170, 6275, 1769, 203, 7734, 4232, 39, 3462, 9890, 5912, 18, 4626, 5912, 12, 7860, 63, 1615, 6487, 9395, 38, 4009, 74, 14463, 814, 16, 9395, 6275, 1769, 203, 5411, 289, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-11-18 */ /** *Submitted for verification at Etherscan.io on 2020-07-21 */ pragma solidity ^0.6.0; interface DMEX { function availableBalanceOf(address token, address user) external view returns (uint256); function withdraw(address token, uint256 amount) external returns (bool success); } interface UniswapV2ExchangeInterface { function WETH() external pure returns (address); function swapExactTokensForTokens(uint amountIn, uint amountOutMin, 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 swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); } /* Interface for ERC20 Tokens */ interface DMEXTokenInterface { function burn(uint256 _value) external returns (bool success); } // The DMEX Fee Contract contract DMEX_Fee_Contract { address DMEX_CONTRACT = address(0x2101e480e22C953b37b9D0FE6551C1354Fe705E6); address DMEX_TOKEN = address(0x6263e260fF6597180c9538c69aF8284EDeaCEC80); address TOKEN_ETH = address(0x0000000000000000000000000000000000000000); address TOKEN_DAI = address(0x6B175474E89094C44Da98b954EedeAC495271d0F); address TOKEN_BTC = address(0x5228a22e72ccC52d415EcFd199F99D0665E7733b); address uniswapRouter = address(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address payable FEE_ACCOUNT; address owner; uint256 fee_account_share = 618e15; uint256 uniswap_share = 382e15; event Log(uint8 indexed errorId, uint value); function extractFees() public { uint256 fee_share; uint256 us_share; // extract eth uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); // DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance); // fee_share = eth_balance * fee_account_share / 1e18; // us_share = eth_balance - fee_share; // emit Log(2, fee_share); // emit Log(3, us_share); // require(FEE_ACCOUNT.send(fee_share), "Error: eth send failed"); // // swap eth for DMEX Token // address[] memory path = new address[](2); // path[0] = UniswapV2ExchangeInterface(uniswapRouter).WETH(); // path[1] = DMEX_TOKEN; // uint[] memory amounts = UniswapV2ExchangeInterface(uniswapRouter).swapExactETHForTokens.value(us_share)(1, path, address(this), 2**256 - 1); // uint token_bought = amounts[1]; // DMEXTokenInterface(DMEX_TOKEN).burn(token_bought); } constructor( address payable initialFeeAccount ) public { owner = msg.sender; FEE_ACCOUNT = initialFeeAccount; } /** Safe Math **/ // Safe Multiply Function - prevents integer overflow function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } // Safe Subtraction Function - prevents integer overflow function safeSub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } // Safe Addition Function - prevents integer overflow function safeAdd(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert(c>=a && c>=b); return c; } }
extract eth DMEX(DMEX_CONTRACT).withdraw(TOKEN_ETH, eth_balance); fee_share = eth_balance * fee_account_share / 1e18; us_share = eth_balance - fee_share; emit Log(2, fee_share); emit Log(3, us_share); require(FEE_ACCOUNT.send(fee_share), "Error: eth send failed"); swap eth for DMEX Token address[] memory path = new address[](2); path[0] = UniswapV2ExchangeInterface(uniswapRouter).WETH(); path[1] = DMEX_TOKEN; uint[] memory amounts = UniswapV2ExchangeInterface(uniswapRouter).swapExactETHForTokens.value(us_share)(1, path, address(this), 2**256 - 1); uint token_bought = amounts[1]; DMEXTokenInterface(DMEX_TOKEN).burn(token_bought);
function extractFees() public { uint256 fee_share; uint256 us_share; uint256 eth_balance = DMEX(DMEX_CONTRACT).availableBalanceOf(TOKEN_ETH, address(this)); emit Log(1, eth_balance); } constructor( address payable initialFeeAccount
2,293,989
[ 1, 8004, 13750, 463, 958, 60, 12, 40, 958, 60, 67, 6067, 2849, 1268, 2934, 1918, 9446, 12, 8412, 67, 1584, 44, 16, 13750, 67, 12296, 1769, 14036, 67, 14419, 273, 13750, 67, 12296, 225, 14036, 67, 4631, 67, 14419, 342, 404, 73, 2643, 31, 584, 67, 14419, 273, 13750, 67, 12296, 300, 14036, 67, 14419, 31, 3626, 1827, 12, 22, 16, 14036, 67, 14419, 1769, 3626, 1827, 12, 23, 16, 584, 67, 14419, 1769, 2583, 12, 8090, 41, 67, 21690, 18, 4661, 12, 21386, 67, 14419, 3631, 315, 668, 30, 13750, 1366, 2535, 8863, 225, 7720, 13750, 364, 463, 958, 60, 3155, 1758, 8526, 3778, 589, 273, 394, 1758, 8526, 12, 22, 1769, 589, 63, 20, 65, 273, 1351, 291, 91, 438, 58, 22, 11688, 1358, 12, 318, 291, 91, 438, 8259, 2934, 59, 1584, 44, 5621, 589, 63, 21, 65, 273, 463, 958, 60, 67, 8412, 31, 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, 2608, 2954, 281, 1435, 1071, 288, 203, 3639, 2254, 5034, 14036, 67, 14419, 31, 7010, 3639, 2254, 5034, 584, 67, 14419, 31, 203, 203, 3639, 2254, 5034, 13750, 67, 12296, 273, 463, 958, 60, 12, 40, 958, 60, 67, 6067, 2849, 1268, 2934, 5699, 13937, 951, 12, 8412, 67, 1584, 44, 16, 1758, 12, 2211, 10019, 203, 540, 203, 3639, 3626, 1827, 12, 21, 16, 13750, 67, 12296, 1769, 203, 540, 203, 203, 540, 203, 540, 203, 203, 203, 203, 377, 203, 203, 565, 289, 203, 203, 565, 3885, 12, 203, 3639, 1758, 8843, 429, 225, 2172, 14667, 3032, 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 ]
./full_match/1/0x0B41415387A7a692e5721e3461b485febf61C796/sources/contracts/Presale.sol
to check number of BTC20X for given ETH
function ethToToken(uint256 _amount) public view returns (uint256) { uint256 numberOfTokens = _amount .mul(getLatestPriceETH()) .mul(tokenPerUsd) .div(1e8); return numberOfTokens; }
16,441,134
[ 1, 869, 866, 1300, 434, 605, 15988, 3462, 60, 364, 864, 512, 2455, 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, 13750, 774, 1345, 12, 11890, 5034, 389, 8949, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 7922, 5157, 273, 389, 8949, 203, 5411, 263, 16411, 12, 588, 18650, 5147, 1584, 44, 10756, 203, 5411, 263, 16411, 12, 2316, 2173, 3477, 72, 13, 203, 5411, 263, 2892, 12, 21, 73, 28, 1769, 203, 3639, 327, 7922, 5157, 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 ]
./full_match/56/0x4d2FA1E81661ecaF1FABdB9FF08c582F1ACEf003/sources/contracts/Token.sol
all time high price
uint256 public athPrice;
3,254,961
[ 1, 454, 813, 3551, 6205, 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, 225, 2254, 5034, 1071, 225, 421, 5147, 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: Apache-2.0 /* Copyright 2020 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.6.5; pragma experimental ABIEncoderV2; import "../ZeroEx.sol"; import "../features/IOwnableFeature.sol"; import "../features/TokenSpenderFeature.sol"; import "../features/TransformERC20Feature.sol"; import "../features/MetaTransactionsFeature.sol"; import "../features/NativeOrdersFeature.sol"; import "../external/AllowanceTarget.sol"; import "./InitialMigration.sol"; /// @dev A contract for deploying and configuring the full ZeroEx contract. contract FullMigration { // solhint-disable no-empty-blocks,indent /// @dev Features to add the the proxy contract. struct Features { SimpleFunctionRegistryFeature registry; OwnableFeature ownable; TokenSpenderFeature tokenSpender; TransformERC20Feature transformERC20; MetaTransactionsFeature metaTransactions; NativeOrdersFeature nativeOrders; } /// @dev Parameters needed to initialize features. struct MigrateOpts { address transformerDeployer; } /// @dev The allowed caller of `initializeZeroEx()`. address public immutable initializeCaller; /// @dev The initial migration contract. InitialMigration private _initialMigration; /// @dev Instantiate this contract and set the allowed caller of `initializeZeroEx()` /// to `initializeCaller`. /// @param initializeCaller_ The allowed caller of `initializeZeroEx()`. constructor(address payable initializeCaller_) public { initializeCaller = initializeCaller_; // Create an initial migration contract with this contract set to the // allowed `initializeCaller`. _initialMigration = new InitialMigration(address(this)); } /// @dev Retrieve the bootstrapper address to use when constructing `ZeroEx`. /// @return bootstrapper The bootstrapper address. function getBootstrapper() external view returns (address bootstrapper) { return address(_initialMigration); } /// @dev Initialize the `ZeroEx` contract with the full feature set, /// transfer ownership to `owner`, then self-destruct. /// @param owner The owner of the contract. /// @param zeroEx The instance of the ZeroEx contract. ZeroEx should /// been constructed with this contract as the bootstrapper. /// @param features Features to add to the proxy. /// @return _zeroEx The configured ZeroEx contract. Same as the `zeroEx` parameter. /// @param migrateOpts Parameters needed to initialize features. function migrateZeroEx( address payable owner, ZeroEx zeroEx, Features memory features, MigrateOpts memory migrateOpts ) public returns (ZeroEx _zeroEx) { require(msg.sender == initializeCaller, "FullMigration/INVALID_SENDER"); // Perform the initial migration with the owner set to this contract. _initialMigration.initializeZeroEx( address(uint160(address(this))), zeroEx, InitialMigration.BootstrapFeatures({ registry: features.registry, ownable: features.ownable }) ); // Add features. _addFeatures(zeroEx, owner, features, migrateOpts); // Transfer ownership to the real owner. IOwnableFeature(address(zeroEx)).transferOwnership(owner); // Self-destruct. this.die(owner); return zeroEx; } /// @dev Destroy this contract. Only callable from ourselves (from `initializeZeroEx()`). /// @param ethRecipient Receiver of any ETH in this contract. function die(address payable ethRecipient) external virtual { require(msg.sender == address(this), "FullMigration/INVALID_SENDER"); // This contract should not hold any funds but we send // them to the ethRecipient just in case. selfdestruct(ethRecipient); } /// @dev Deploy and register features to the ZeroEx contract. /// @param zeroEx The bootstrapped ZeroEx contract. /// @param owner The ultimate owner of the ZeroEx contract. /// @param features Features to add to the proxy. /// @param migrateOpts Parameters needed to initialize features. function _addFeatures( ZeroEx zeroEx, address owner, Features memory features, MigrateOpts memory migrateOpts ) private { IOwnableFeature ownable = IOwnableFeature(address(zeroEx)); // TokenSpenderFeature { // Create the allowance target. AllowanceTarget allowanceTarget = new AllowanceTarget(); // Let the ZeroEx contract use the allowance target. allowanceTarget.addAuthorizedAddress(address(zeroEx)); // Transfer ownership of the allowance target to the (real) owner. allowanceTarget.transferOwnership(owner); // Register the feature. ownable.migrate( address(features.tokenSpender), abi.encodeWithSelector( TokenSpenderFeature.migrate.selector, allowanceTarget ), address(this) ); } // TransformERC20Feature { // Register the feature. ownable.migrate( address(features.transformERC20), abi.encodeWithSelector( TransformERC20Feature.migrate.selector, migrateOpts.transformerDeployer ), address(this) ); } // MetaTransactionsFeature { // Register the feature. ownable.migrate( address(features.metaTransactions), abi.encodeWithSelector( MetaTransactionsFeature.migrate.selector ), address(this) ); } // NativeOrdersFeature { // Register the feature. ownable.migrate( address(features.nativeOrders), abi.encodeWithSelector( NativeOrdersFeature.migrate.selector ), address(this) ); } } }
Create an initial migration contract with this contract set to the allowed `initializeCaller`.
{ initializeCaller = initializeCaller_; _initialMigration = new InitialMigration(address(this)); }
12,571,771
[ 1, 1684, 392, 2172, 6333, 6835, 598, 333, 6835, 444, 358, 326, 2935, 1375, 11160, 11095, 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, 288, 203, 3639, 4046, 11095, 273, 4046, 11095, 67, 31, 203, 3639, 389, 6769, 10224, 273, 394, 10188, 10224, 12, 2867, 12, 2211, 10019, 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 ]
./full_match/1/0x2bE9D0c8bBFd14019fd8ebe48120193fD90304b5/sources/contracts/TerribleTurtles.sol
IPFS URL WILL BE ADDED WHEN TURTLES ARE ALL SOLD OUT
string public TURTLE_PROVENANCE = "";
2,900,866
[ 1, 2579, 4931, 1976, 678, 15125, 9722, 11738, 7660, 29707, 399, 1099, 56, 11386, 432, 862, 8061, 348, 11846, 8210, 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, 533, 1071, 399, 1099, 56, 900, 67, 3373, 58, 1157, 4722, 273, 1408, 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 ]
pragma solidity ^0.4.23; // Copyright 2018 OpenST Ltd. // // 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. // // ---------------------------------------------------------------------------- // Auxiliary Chain: CoGateway Contract // // http://www.simpletoken.org/ // // ---------------------------------------------------------------------------- /* Origin chain | Auxiliary chain ------------------------------------------------------------------------------- EIP20Gateway - - - - - - - - - - - EIP20CoGateway ------------------------------------------------------------------------------- 1. GatewayLinking: initiateGatewayLink ---> confirmGatewayLinkIntent | progressGatewayLink ---> progressGatewayLink ------------------------------------------------------------------------------- */ import "./MessageBus.sol"; import "./EIP20Interface.sol"; import "../lib/SafeMath.sol"; import "./GatewayBase.sol"; import "./CoreInterface.sol"; import "./UtilityTokenInterface.sol"; import "../lib/GatewayLib.sol"; /** * @title CoGateway contract. * * @notice CoGateway contains functions for initial setup of EIP20CoGateway. */ contract CoGateway is GatewayBase { using SafeMath for uint256; /** Emitted whenever a gateway and coGateway linking is confirmed. */ event GatewayLinkConfirmed( bytes32 indexed _messageHash, address _gateway, address _cogateway, address _valueToken, address _utilityToken ); /** Emitted whenever a gateway and coGateway linking is complete. */ event GatewayLinkProgressed( bytes32 indexed _messageHash, address _gateway, address _cogateway, address _valueToken, address _utilityToken, bytes32 _unlockSecret ); /* public variables */ /** address of utility token. */ address public utilityToken; /** address of value token. */ address public valueToken; /* Constructor */ /** * @notice Initialise the contract by providing the Gateway contract * address for which the CoGateway will enable facilitation of * minting and redeeming. * * @param _valueToken The value token contract address. * @param _utilityToken The utility token address that will be used for * minting the utility token. * @param _core Core contract address. * @param _bounty The amount that facilitator will stakes to initiate the * staking process. * @param _organisation Organisation address. * @param _gateway Gateway contract address. * @param _messageBus Message bus address. */ constructor( address _valueToken, address _utilityToken, CoreInterface _core, uint256 _bounty, address _organisation, address _gateway, address _messageBus ) GatewayBase( _core, _messageBus, _bounty, _organisation ) public { require( _valueToken != address(0), "Value token address must not be zero" ); require( _utilityToken != address(0), "Utility token address must not be zero" ); require( _gateway != address(0), "Gateway address must not be zero" ); valueToken = _valueToken; utilityToken = _utilityToken; core = _core; remoteGateway = _gateway; // update the encodedGatewayPath encodedGatewayPath = GatewayLib.bytes32ToBytes( keccak256(abi.encodePacked(remoteGateway)) ); } /* External functions */ /** * @notice Confirm the Gateway and CoGateway contracts initiation. * * @param _intentHash Gateway and CoGateway linking intent hash. * This is a sha3 of gateway address, cogateway address, * bounty, token name, token symbol, token decimals, * _nonce, token. * @param _nonce Nonce of the sender. Here in this case its organisation * address of Gateway * @param _sender The address that signs the message hash. In this case it * has to be organisation address of Gateway * @param _hashLock Hash lock, set by the facilitator. * @param _blockHeight Block number for which the proof is valid * @param _rlpParentNodes RLP encoded parent node data to prove in * messageBox outbox of Gateway * * @return messageHash_ Message hash */ function confirmGatewayLinkIntent( bytes32 _intentHash, uint256 _nonce, address _sender, bytes32 _hashLock, uint256 _blockHeight, bytes memory _rlpParentNodes ) public // TODO: check to change it to external, getting stack to deep. returns (bytes32 messageHash_) { require( linked == false, "CoGateway contract must not be already linked" ); require( deactivated == false, "Gateway contract must not be deactivated" ); require( gatewayLinkHash == bytes32(0), "Linking is already initiated" ); require( _sender != address(0), "Sender must be not be zero" ); require( _rlpParentNodes.length > 0, "RLP parent nodes must not be zero" ); bytes32 storageRoot = storageRoots[_blockHeight]; require( storageRoot != bytes32(0), "Storage root for given block height must not be zero" ); bytes32 intentHash = hashLinkGateway(_nonce); // Ensure that the _intentHash matches the calculated intentHash require( intentHash == _intentHash, "Incorrect intent hash" ); // Get the message hash messageHash_ = MessageBus.messageDigest( GATEWAY_LINK_TYPEHASH, intentHash, _nonce, 0, 0 ); // create Message object messages[messageHash_] = getMessage( _sender, _nonce, 0, 0, _intentHash, _hashLock ); // initiate new inbox process registerInboxProcess( _sender, _nonce, messageHash_ ); // Declare message in inbox MessageBus.confirmMessage( messageBox, GATEWAY_LINK_TYPEHASH, messages[messageHash_], _rlpParentNodes, MESSAGE_BOX_OFFSET, storageRoot ); gatewayLinkHash = messageHash_; // Emit GatewayLinkConfirmed event emit GatewayLinkConfirmed( messageHash_, remoteGateway, address(this), valueToken, utilityToken ); } /** * @notice Complete the Gateway and CoGateway contracts linking. This will * set the variable linked to true, and thus it will activate the * CoGateway contract for mint and redeem. * * @param _messageHash Message hash * @param _unlockSecret Unlock secret for the hashLock provide by the * facilitator while initiating the Gateway/CoGateway * linking * * @return `true` if gateway linking was successfully progressed */ function progressGatewayLink( bytes32 _messageHash, bytes32 _unlockSecret ) external returns (bool) { require( _messageHash != bytes32(0), "Message hash must not be zero" ); require( gatewayLinkHash == _messageHash, "Invalid message hash" ); // Progress inbox MessageBus.progressInbox( messageBox, GATEWAY_LINK_TYPEHASH, messages[_messageHash], _unlockSecret ); // Update to specify the Gateway/CoGateway is linked linked = true; // Emit GatewayLinkProgressed event emit GatewayLinkProgressed( _messageHash, remoteGateway, address(this), valueToken, utilityToken, _unlockSecret ); return true; } /** * @notice private function to calculate gateway link intent hash. * * @dev This function is to avoid stack too deep error in * confirmGatewayLinkIntent function * * @param _nonce nonce of message * * @return bytes32 link intent hash */ function hashLinkGateway( uint256 _nonce ) private view returns (bytes32) { return GatewayLib.hashLinkGateway( remoteGateway, address(this), messageBus, EIP20Interface(utilityToken).name(), EIP20Interface(utilityToken).symbol(), EIP20Interface(utilityToken).decimals(), _nonce, valueToken); } }
* @notice private function to calculate gateway link intent hash. @dev This function is to avoid stack too deep error in confirmGatewayLinkIntent function @param _nonce nonce of message @return bytes32 link intent hash/
function hashLinkGateway( uint256 _nonce ) private view returns (bytes32) { return GatewayLib.hashLinkGateway( remoteGateway, address(this), messageBus, EIP20Interface(utilityToken).name(), EIP20Interface(utilityToken).symbol(), EIP20Interface(utilityToken).decimals(), _nonce, valueToken); }
13,018,837
[ 1, 1152, 445, 358, 4604, 6878, 1692, 10376, 1651, 18, 225, 1220, 445, 353, 358, 4543, 2110, 4885, 4608, 555, 316, 1377, 6932, 5197, 2098, 12105, 445, 225, 389, 12824, 7448, 434, 883, 327, 1731, 1578, 1692, 10376, 1651, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1651, 2098, 5197, 12, 203, 3639, 2254, 5034, 389, 12824, 203, 565, 262, 203, 3639, 3238, 203, 3639, 1476, 203, 3639, 1135, 261, 3890, 1578, 13, 203, 565, 288, 203, 3639, 327, 11381, 5664, 18, 2816, 2098, 5197, 12, 203, 5411, 2632, 5197, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 883, 7086, 16, 203, 5411, 512, 2579, 3462, 1358, 12, 1367, 560, 1345, 2934, 529, 9334, 203, 5411, 512, 2579, 3462, 1358, 12, 1367, 560, 1345, 2934, 7175, 9334, 203, 5411, 512, 2579, 3462, 1358, 12, 1367, 560, 1345, 2934, 31734, 9334, 203, 5411, 389, 12824, 16, 203, 5411, 460, 1345, 1769, 203, 203, 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 ]
pragma solidity >=0.5.0 <0.6.0; library BigMod { // Original Source from https://github.com/HarryR/solcrypto/blob/master/contracts/altbn128.sol // Commit 396fe4642cf39e2577217651a64bc3d19362ce42 License: MIT // From: https://gist.githubusercontent.com/chriseth/f9be9d9391efc5beb9704255a8e2989d/raw/4d0fb90847df1d4e04d507019031888df8372239/snarktest.solidity // Basically just calls the precompiled EVM contract/function 0x05 which calculates (_base ** _expoonent) % _modulus efficiently // Modified for Solitity ^0.5.0, original function name expMod() function bigMod(uint256 _base, uint256 _exponent, uint256 _modulus) internal view returns (uint256 retval) { bool success; uint256[1] memory output; uint[6] memory input; input[0] = 0x20; // baseLen = new(big.Int).SetBytes(getData(input, 0, 32)) input[1] = 0x20; // expLen = new(big.Int).SetBytes(getData(input, 32, 32)) input[2] = 0x20; // modLen = new(big.Int).SetBytes(getData(input, 64, 32)) input[3] = _base; input[4] = _exponent; input[5] = _modulus; assembly { success := staticcall(sub(gas, 2000), 5, input, 0xc0, output, 0x20) // Use "revert" to make gas estimation work switch success case 0 { revert(0, 0) } } require(success); return output[0]; } }
expLen = new(big.Int).SetBytes(getData(input, 32, 32))
input[1] = 0x20;
5,400,292
[ 1, 2749, 2891, 225, 273, 394, 12, 14002, 18, 1702, 2934, 694, 2160, 12, 588, 751, 12, 2630, 16, 3847, 16, 3847, 3719, 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, 202, 202, 2630, 63, 21, 65, 273, 374, 92, 3462, 31, 540, 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 ]
./full_match/432204/0x010224949cCa211Fb5dDfEDD28Dc8Bf9D2990368/sources/contracts/PortfolioSub.sol
* @notice Function for TradePairs to transfer tokens between addresses as a result of an execution @dev WHEN Increasing in addExecution the amount is applied to both total and available (so SafeIncrease can be used) as opposed to WHEN Decreasing in addExecution the amount is only applied to total. (SafeDecrease can NOT be used, so we have safeDecreaseTotal instead) i.e. (USDT 100 Total, 50 Available after we send a BUY order of 10 avax at 5$. Partial Exec 5 at $5. Total goes down to 75. Available stays at 50) @param _makerSide Side of the maker @param _makerAddr Address of the maker @param _takerAddr Address of the taker @param _baseSymbol Symbol of the base token @param _quoteSymbol Symbol of the quote token @param _baseAmount Amount of the base token @param _quoteAmount Amount of the quote token @param _makerfeeCharged Fee charged to the maker @param _takerfeeCharged Fee charged to the taker/ Only TradePairs can call PORTFOLIO addExecution if _maker.side = BUY then _taker.side = SELL decrease maker quote and incrase taker quote increase maker base and decrase taker base increase maker quote and decrease taker quote decrease maker base and incrase taker base
function addExecution( ITradePairs.Side _makerSide, address _makerAddr, address _takerAddr, bytes32 _baseSymbol, bytes32 _quoteSymbol, uint256 _baseAmount, uint256 _quoteAmount, uint256 _makerfeeCharged, uint256 _takerfeeCharged ) external override { require(hasRole(EXECUTOR_ROLE, msg.sender), "P-OACC-03"); if (_makerSide == ITradePairs.Side.BUY) { transferToken(_makerAddr, _takerAddr, _quoteSymbol, _quoteAmount, _takerfeeCharged, Tx.EXECUTION, true); transferToken(_takerAddr, _makerAddr, _baseSymbol, _baseAmount, _makerfeeCharged, Tx.EXECUTION, false); transferToken(_takerAddr, _makerAddr, _quoteSymbol, _quoteAmount, _makerfeeCharged, Tx.EXECUTION, false); transferToken(_makerAddr, _takerAddr, _baseSymbol, _baseAmount, _takerfeeCharged, Tx.EXECUTION, true); } }
16,380,929
[ 1, 2083, 364, 2197, 323, 10409, 358, 7412, 2430, 3086, 6138, 487, 279, 563, 434, 392, 4588, 1377, 29707, 657, 1793, 11730, 316, 527, 3210, 326, 3844, 353, 6754, 358, 3937, 2078, 471, 2319, 261, 2048, 14060, 382, 11908, 848, 506, 1399, 13, 487, 1061, 7423, 358, 29707, 31073, 11730, 316, 527, 3210, 326, 3844, 353, 1338, 6754, 358, 2078, 18, 261, 9890, 23326, 448, 848, 4269, 506, 1399, 16, 1427, 732, 1240, 4183, 23326, 448, 5269, 3560, 13, 277, 18, 73, 18, 261, 3378, 9081, 2130, 10710, 16, 6437, 15633, 1839, 732, 1366, 279, 10937, 61, 1353, 434, 1728, 1712, 651, 622, 1381, 8, 18, 19060, 3889, 1381, 622, 271, 25, 18, 10710, 13998, 2588, 358, 18821, 18, 15633, 384, 8271, 622, 6437, 13, 565, 389, 29261, 8895, 225, 26248, 434, 326, 312, 6388, 565, 389, 29261, 3178, 225, 5267, 434, 326, 312, 6388, 565, 389, 88, 6388, 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, 527, 3210, 12, 203, 3639, 467, 22583, 10409, 18, 8895, 389, 29261, 8895, 16, 203, 3639, 1758, 389, 29261, 3178, 16, 203, 3639, 1758, 389, 88, 6388, 3178, 16, 203, 3639, 1731, 1578, 389, 1969, 5335, 16, 203, 3639, 1731, 1578, 389, 6889, 5335, 16, 203, 3639, 2254, 5034, 389, 1969, 6275, 16, 203, 3639, 2254, 5034, 389, 6889, 6275, 16, 203, 3639, 2254, 5034, 389, 29261, 21386, 2156, 2423, 16, 203, 3639, 2254, 5034, 389, 88, 6388, 21386, 2156, 2423, 203, 565, 262, 3903, 3849, 288, 203, 3639, 2583, 12, 5332, 2996, 12, 15271, 1693, 916, 67, 16256, 16, 1234, 18, 15330, 3631, 315, 52, 17, 51, 31414, 17, 4630, 8863, 203, 3639, 309, 261, 67, 29261, 8895, 422, 467, 22583, 10409, 18, 8895, 18, 3000, 61, 13, 288, 203, 5411, 7412, 1345, 24899, 29261, 3178, 16, 389, 88, 6388, 3178, 16, 389, 6889, 5335, 16, 389, 6889, 6275, 16, 389, 88, 6388, 21386, 2156, 2423, 16, 6424, 18, 15271, 13269, 16, 638, 1769, 203, 5411, 7412, 1345, 24899, 88, 6388, 3178, 16, 389, 29261, 3178, 16, 389, 1969, 5335, 16, 389, 1969, 6275, 16, 389, 29261, 21386, 2156, 2423, 16, 6424, 18, 15271, 13269, 16, 629, 1769, 203, 5411, 7412, 1345, 24899, 88, 6388, 3178, 16, 389, 29261, 3178, 16, 389, 6889, 5335, 16, 389, 6889, 6275, 16, 389, 29261, 21386, 2156, 2423, 16, 6424, 18, 15271, 13269, 16, 629, 1769, 203, 5411, 7412, 1345, 24899, 29261, 3178, 16, 389, 88, 6388, 3178, 16, 389, 1969, 5335, 16, 389, 1969, 2 ]
pragma solidity 0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } pragma solidity 0.4.24; contract Transfer { address constant public ETH = 0x0; /** * @dev Transfer tokens from this contract to an account. * @param token Address of token to transfer. 0x0 for ETH * @param to Address to send tokens to. * @param amount Amount of token to send. */ function transfer(address token, address to, uint256 amount) internal returns (bool) { if (token == ETH) { to.transfer(amount); } else { require(ERC20(token).transfer(to, amount)); } return true; } /** * @dev Transfer tokens from an account to this contract. * @param token Address of token to transfer. 0x0 for ETH * @param from Address to send tokens from. * @param to Address to send tokens to. * @param amount Amount of token to send. */ function transferFrom( address token, address from, address to, uint256 amount ) internal returns (bool) { require(token == ETH && msg.value == amount || msg.value == 0); if (token != ETH) { // Remember to approve first require(ERC20(token).transferFrom(from, to, amount)); } return true; } } /** * @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; } } interface IERC20 { function balanceOf(address _owner) public view returns (uint balance); function transfer(address _to, uint _value) public returns (bool success); } contract Withdrawable is Ownable { function () public payable {} // Allow the owner to withdraw Ether function withdraw() public onlyOwner { owner.transfer(address(this).balance); } // Allow the owner to withdraw tokens function withdrawToken(address token) public onlyOwner returns (bool) { IERC20 foreignToken = IERC20(token); uint256 amount = foreignToken.balanceOf(address(this)); return foreignToken.transfer(owner, amount); } } pragma solidity 0.4.24; contract ExternalCall { // Source: https://github.com/gnosis/MultiSigWallet/blob/master/contracts/MultiSigWallet.sol // call has been separated into its own function in order to take advantage // of the Solidity&#39;s code generator to produce a loop that copies tx.data into memory. function external_call(address destination, uint value, uint dataLength, bytes data) internal returns (bool) { bool result; assembly { let x := mload(0x40) // "Allocate" memory for output (0x40 is where "free memory" pointer is stored by convention) let d := add(data, 32) // First 32 bytes are the padded length of data, so exclude that result := call( sub(gas, 34710), // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) + callValueTransferGas (9000) + // callNewAccountGas (25000, in case the destination address does not exist and needs creating) destination, value, d, dataLength, // Size of the input (in bytes) - this is what fixes the padding problem x, 0 // Output is ignored, therefore the output size is zero ) } return result; } } /* Copyright 2018 Contra Labs Inc. 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; // @title TradeExecutor: Atomically execute two trades using decentralized exchange wrapper contracts. // @author Rich McAteer <[email protected]>, Max Wolff <[email protected]> contract TradeExecutor is Transfer, Withdrawable, ExternalCall { // Allow exchange wrappers to send Ether function () public payable {} /** * @dev Execute multiple trades in a single transaction. * @param wrappers Addresses of exchange wrappers. * @param token Address of ERC20 token to receive in first trade. * @param trade1 Calldata of Ether => ERC20 trade. * @param trade2 Calldata of ERC20 => Ether trade. */ function trade( address[2] wrappers, address token, bytes trade1, bytes trade2 ) external payable { // Execute the first trade to get tokens require(execute(wrappers[0], msg.value, trade1)); uint256 tokenBalance = IERC20(token).balanceOf(this); // Transfer tokens to the next exchange wrapper transfer(token, wrappers[1], tokenBalance); // Execute the second trade to get Ether require(execute(wrappers[1], 0, trade2)); // Send the arbitrageur Ether msg.sender.transfer(address(this).balance); } function tradeForTokens( address[2] wrappers, address token, bytes trade1, bytes trade2 ) external { // Transfer tokens to the first exchange wrapper uint256 tokenBalance = IERC20(token).balanceOf(this); transfer(token, wrappers[0], tokenBalance); // Execute the first trade to get Ether require(execute(wrappers[0], 0, trade1)); uint256 balance = address(this).balance; // Execute the second trade to get tokens require(execute(wrappers[1], balance, trade2)); tokenBalance = IERC20(token).balanceOf(this); require(IERC20(token).transfer(msg.sender, tokenBalance)); } function execute(address wrapper, uint256 value, bytes data) private returns (bool) { return external_call(wrapper, value, data.length, data); } }
Transfer tokens to the first exchange wrapper Execute the first trade to get Ether Execute the second trade to get tokens
function tradeForTokens( address[2] wrappers, address token, bytes trade1, bytes trade2 ) external { uint256 tokenBalance = IERC20(token).balanceOf(this); transfer(token, wrappers[0], tokenBalance); require(execute(wrappers[0], 0, trade1)); uint256 balance = address(this).balance; require(execute(wrappers[1], balance, trade2)); tokenBalance = IERC20(token).balanceOf(this); require(IERC20(token).transfer(msg.sender, tokenBalance)); }
2,325,907
[ 1, 5912, 2430, 358, 326, 1122, 7829, 4053, 7903, 326, 1122, 18542, 358, 336, 512, 1136, 7903, 326, 2205, 18542, 358, 336, 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 ]
[ 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, 18542, 1290, 5157, 12, 203, 3639, 1758, 63, 22, 65, 21589, 16, 203, 3639, 1758, 1147, 16, 203, 3639, 1731, 18542, 21, 16, 203, 3639, 1731, 18542, 22, 203, 565, 262, 203, 3639, 3903, 203, 565, 288, 203, 3639, 2254, 5034, 1147, 13937, 273, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2211, 1769, 203, 3639, 7412, 12, 2316, 16, 21589, 63, 20, 6487, 1147, 13937, 1769, 203, 203, 3639, 2583, 12, 8837, 12, 4113, 10422, 63, 20, 6487, 374, 16, 18542, 21, 10019, 203, 203, 3639, 2254, 5034, 11013, 273, 1758, 12, 2211, 2934, 12296, 31, 203, 203, 3639, 2583, 12, 8837, 12, 4113, 10422, 63, 21, 6487, 11013, 16, 18542, 22, 10019, 203, 203, 3639, 1147, 13937, 273, 467, 654, 39, 3462, 12, 2316, 2934, 12296, 951, 12, 2211, 1769, 203, 3639, 2583, 12, 45, 654, 39, 3462, 12, 2316, 2934, 13866, 12, 3576, 18, 15330, 16, 1147, 13937, 10019, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.9; /* f_1 - 274287 - 99825 - 48525 f_2 - 148063 - 103637 - 52337 f_3 - 274959 - 99835 - 48535 */ // uint8 storage and setter contract Library_1 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { distributeFunds(msg.value); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } function distributeFunds(uint256 amount) private { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } } contract Library_2 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { FeeSplitter.distributeFunds(msg.value, owners, ownerBalances); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } } contract Library_3 { address[] owners; mapping(address=>uint256) ownerBalances; function SplitFunds() public payable { distributeFunds(msg.value, owners, ownerBalances); } function addOwner() public { // this should have checks, using this to just illustrate a point owners.push(msg.sender); } function distributeFunds(uint256 amount, address[] storage owners, mapping(address => uint256) storage ownerBalances) private { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } } library FeeSplitter{ function distributeFunds(uint256 amount, address[] storage owners, mapping(address => uint256) storage ownerBalances) public { uint256 split = amount / owners.length; uint256 remainder = amount % owners.length; ownerBalances[owners[0]] += remainder; for(uint i=0; i < owners.length;i++) { ownerBalances[owners[i]] += split; } } }
this should have checks, using this to just illustrate a point
function addOwner() public { owners.push(msg.sender); }
15,844,579
[ 1, 2211, 1410, 1240, 4271, 16, 1450, 333, 358, 2537, 277, 2906, 27008, 340, 279, 1634, 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, 377, 445, 527, 5541, 1435, 1071, 288, 203, 540, 25937, 18, 6206, 12, 3576, 18, 15330, 1769, 203, 377, 289, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// File: openzeppelin-solidity/contracts/token/ERC20/ERC20Basic.sol pragma solidity ^0.4.24; /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * See https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address _who) public view returns (uint256); function transfer(address _to, uint256 _value) public returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } // File: openzeppelin-solidity/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address _owner, address _spender) public view returns (uint256); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); function approve(address _spender, uint256 _value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: openzeppelin-solidity/contracts/token/ERC20/DetailedERC20.sol pragma solidity ^0.4.24; /** * @title DetailedERC20 token * @dev The decimals are only for visualization purposes. * All the operations are done using the smallest and indivisible token unit, * just as on Ethereum all the operations are done in wei. */ contract DetailedERC20 is ERC20 { string public name; string public symbol; uint8 public decimals; constructor(string _name, string _symbol, uint8 _decimals) public { name = _name; symbol = _symbol; decimals = _decimals; } } // File: contracts/interfaces/IAMB.sol pragma solidity 0.4.24; interface IAMB { function messageSender() external view returns (address); function maxGasPerTx() external view returns (uint256); function transactionHash() external view returns (bytes32); function messageId() external view returns (bytes32); function messageSourceChainId() external view returns (bytes32); function messageCallStatus(bytes32 _messageId) external view returns (bool); function failedMessageDataHash(bytes32 _messageId) external view returns (bytes32); function failedMessageReceiver(bytes32 _messageId) external view returns (address); function failedMessageSender(bytes32 _messageId) external view returns (address); function requireToPassMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function requireToConfirmMessage(address _contract, bytes _data, uint256 _gas) external returns (bytes32); function sourceChainId() external view returns (uint256); function destinationChainId() external view returns (uint256); } // File: contracts/interfaces/ERC677.sol pragma solidity 0.4.24; contract ERC677 is ERC20 { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferAndCall(address, uint256, bytes) external returns (bool); function increaseAllowance(address spender, uint256 addedValue) public returns (bool); function decreaseAllowance(address spender, uint256 subtractedValue) public returns (bool); } contract LegacyERC20 { function transfer(address _spender, uint256 _value) public; // returns (bool); function transferFrom(address _owner, address _spender, uint256 _value) public; // returns (bool); } // File: openzeppelin-solidity/contracts/math/SafeMath.sol pragma solidity ^0.4.24; /** * @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; } } // File: contracts/upgradeability/EternalStorage.sol pragma solidity 0.4.24; /** * @title EternalStorage * @dev This contract holds all the necessary state variables to carry out the storage of any contract. */ contract EternalStorage { mapping(bytes32 => uint256) internal uintStorage; mapping(bytes32 => string) internal stringStorage; mapping(bytes32 => address) internal addressStorage; mapping(bytes32 => bytes) internal bytesStorage; mapping(bytes32 => bool) internal boolStorage; mapping(bytes32 => int256) internal intStorage; } // File: contracts/interfaces/IUpgradeabilityOwnerStorage.sol pragma solidity 0.4.24; interface IUpgradeabilityOwnerStorage { function upgradeabilityOwner() external view returns (address); } // File: contracts/upgradeable_contracts/Ownable.sol pragma solidity 0.4.24; /** * @title Ownable * @dev This contract has an owner address providing basic authorization control */ contract Ownable is EternalStorage { bytes4 internal constant UPGRADEABILITY_OWNER = 0x6fde8202; // upgradeabilityOwner() /** * @dev Event to show ownership has been transferred * @param previousOwner representing the address of the previous owner * @param newOwner representing the address of the new owner */ event OwnershipTransferred(address previousOwner, address newOwner); /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner()); /* solcov ignore next */ _; } /** * @dev Throws if called by any account other than contract itself or owner. */ modifier onlyRelevantSender() { // proxy owner if used through proxy, address(0) otherwise require( !address(this).call(abi.encodeWithSelector(UPGRADEABILITY_OWNER)) || // covers usage without calling through storage proxy msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner() || // covers usage through regular proxy calls msg.sender == address(this) // covers calls through upgradeAndCall proxy method ); /* solcov ignore next */ _; } bytes32 internal constant OWNER = 0x02016836a56b71f0d02689e69e326f4f4c1b9057164ef592671cf0d37c8040c0; // keccak256(abi.encodePacked("owner")) /** * @dev Tells the address of the owner * @return the address of the owner */ function owner() public view returns (address) { return addressStorage[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) external onlyOwner { _setOwner(newOwner); } /** * @dev Sets a new owner address */ function _setOwner(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(owner(), newOwner); addressStorage[OWNER] = newOwner; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiTokenBridge.sol pragma solidity 0.4.24; contract BasicMultiTokenBridge is EternalStorage, Ownable { using SafeMath for uint256; // token == 0x00..00 represents default limits (assuming decimals == 18) for all newly created tokens event DailyLimitChanged(address indexed token, uint256 newLimit); event ExecutionDailyLimitChanged(address indexed token, uint256 newLimit); /** * @dev Checks if specified token was already bridged at least once. * @param _token address of the token contract. * @return true, if token address is address(0) or token was already bridged. */ function isTokenRegistered(address _token) public view returns (bool) { return minPerTx(_token) > 0; } /** * @dev Retrieves the total spent amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens sent through the bridge to the other side. */ function totalSpentPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("tSpD", _token, _day))]; } /** * @dev Retrieves the total executed amount for particular token during specific day. * @param _token address of the token contract. * @param _day day number for which spent amount if requested. * @return amount of tokens received from the bridge from the other side. */ function totalExecutedPerDay(address _token, uint256 _day) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))]; } /** * @dev Retrieves current daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be sent through the bridge per day. */ function dailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))]; } /** * @dev Retrieves current execution daily limit for a particular token contract. * @param _token address of the token contract. * @return daily limit on tokens that can be received from the bridge on the other side per day. */ function executionDailyLimit(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))]; } /** * @dev Retrieves current maximum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can be sent through the bridge in one transfer. */ function maxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))]; } /** * @dev Retrieves current maximum execution amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return maximum amount on tokens that can received from the bridge on the other side in one transaction. */ function executionMaxPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))]; } /** * @dev Retrieves current minimum amount of tokens per one transfer for a particular token contract. * @param _token address of the token contract. * @return minimum amount on tokens that can be sent through the bridge in one transfer. */ function minPerTx(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("minPerTx", _token))]; } /** * @dev Checks that bridged amount of tokens conforms to the configured limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be bridged. */ function withinLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalSpentPerDay(_token, getCurrentDay()).add(_amount); return dailyLimit(address(0)) > 0 && dailyLimit(_token) >= nextLimit && _amount <= maxPerTx(_token) && _amount >= minPerTx(_token); } /** * @dev Checks that bridged amount of tokens conforms to the configured execution limits. * @param _token address of the token contract. * @param _amount amount of bridge tokens. * @return true, if specified amount can be processed and executed. */ function withinExecutionLimit(address _token, uint256 _amount) public view returns (bool) { uint256 nextLimit = totalExecutedPerDay(_token, getCurrentDay()).add(_amount); return executionDailyLimit(address(0)) > 0 && executionDailyLimit(_token) >= nextLimit && _amount <= executionMaxPerTx(_token); } /** * @dev Returns current day number. * @return day number. */ function getCurrentDay() public view returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp / 1 days; } /** * @dev Updates daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the efault limit. * @param _dailyLimit daily allowed amount of bridged tokens, should be greater than maxPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > maxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _dailyLimit; emit DailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution daily limit for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _dailyLimit daily allowed amount of executed tokens, should be greater than executionMaxPerTx. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionDailyLimit(address _token, uint256 _dailyLimit) external onlyOwner { require(isTokenRegistered(_token)); require(_dailyLimit > executionMaxPerTx(_token) || _dailyLimit == 0); uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _dailyLimit; emit ExecutionDailyLimitChanged(_token, _dailyLimit); } /** * @dev Updates execution maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of executed tokens per one transaction, should be less than executionDailyLimit. * 0 value is also allowed, will stop the bridge operations in incoming direction. */ function setExecutionMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > 0 && _maxPerTx < executionDailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _maxPerTx; } /** * @dev Updates maximum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _maxPerTx maximum amount of tokens per one transaction, should be less than dailyLimit, greater than minPerTx. * 0 value is also allowed, will stop the bridge operations in outgoing direction. */ function setMaxPerTx(address _token, uint256 _maxPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_maxPerTx == 0 || (_maxPerTx > minPerTx(_token) && _maxPerTx < dailyLimit(_token))); uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _maxPerTx; } /** * @dev Updates minumum per transaction for the particular token. Only owner can call this method. * @param _token address of the token contract, or address(0) for configuring the default limit. * @param _minPerTx minumum amount of tokens per one transaction, should be less than maxPerTx and dailyLimit. */ function setMinPerTx(address _token, uint256 _minPerTx) external onlyOwner { require(isTokenRegistered(_token)); require(_minPerTx > 0 && _minPerTx < dailyLimit(_token) && _minPerTx < maxPerTx(_token)); uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _minPerTx; } /** * @dev Retrieves maximum available bridge amount per one transaction taking into account maxPerTx() and dailyLimit() parameters. * @param _token address of the token contract, or address(0) for the default limit. * @return minimum of maxPerTx parameter and remaining daily quota. */ function maxAvailablePerTx(address _token) public view returns (uint256) { uint256 _maxPerTx = maxPerTx(_token); uint256 _dailyLimit = dailyLimit(_token); uint256 _spent = totalSpentPerDay(_token, getCurrentDay()); uint256 _remainingOutOfDaily = _dailyLimit > _spent ? _dailyLimit - _spent : 0; return _maxPerTx < _remainingOutOfDaily ? _maxPerTx : _remainingOutOfDaily; } /** * @dev Internal function for adding spent amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalSpentPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("tSpD", _token, _day))] = totalSpentPerDay(_token, _day).add(_value); } /** * @dev Internal function for adding execcuted amount for some token. * @param _token address of the token contract. * @param _day day number, when tokens are processed. * @param _value amount of bridge tokens. */ function addTotalExecutedPerDay(address _token, uint256 _day, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("totalExecutedPerDay", _token, _day))] = totalExecutedPerDay( _token, _day ) .add(_value); } /** * @dev Internal function for initializing limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ]. */ function _setLimits(address _token, uint256[3] _limits) internal { require( _limits[2] > 0 && // minPerTx > 0 _limits[1] > _limits[2] && // maxPerTx > minPerTx _limits[0] > _limits[1] // dailyLimit > maxPerTx ); uintStorage[keccak256(abi.encodePacked("dailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("maxPerTx", _token))] = _limits[1]; uintStorage[keccak256(abi.encodePacked("minPerTx", _token))] = _limits[2]; emit DailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing execution limits for some token. * @param _token address of the token contract. * @param _limits [ 0 = executionDailyLimit, 1 = executionMaxPerTx ]. */ function _setExecutionLimits(address _token, uint256[2] _limits) internal { require(_limits[1] < _limits[0]); // foreignMaxPerTx < foreignDailyLimit uintStorage[keccak256(abi.encodePacked("executionDailyLimit", _token))] = _limits[0]; uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", _token))] = _limits[1]; emit ExecutionDailyLimitChanged(_token, _limits[0]); } /** * @dev Internal function for initializing limits for some token relative to its decimals parameter. * @param _token address of the token contract. * @param _decimals token decimals parameter. */ function _initializeTokenBridgeLimits(address _token, uint256 _decimals) internal { uint256 factor; if (_decimals < 18) { factor = 10**(18 - _decimals); uint256 _minPerTx = minPerTx(address(0)).div(factor); uint256 _maxPerTx = maxPerTx(address(0)).div(factor); uint256 _dailyLimit = dailyLimit(address(0)).div(factor); uint256 _executionMaxPerTx = executionMaxPerTx(address(0)).div(factor); uint256 _executionDailyLimit = executionDailyLimit(address(0)).div(factor); // such situation can happen when calculated limits relative to the token decimals are too low // e.g. minPerTx(address(0)) == 10 ** 14, _decimals == 3. _minPerTx happens to be 0, which is not allowed. // in this case, limits are raised to the default values if (_minPerTx == 0) { // Numbers 1, 100, 10000 are chosen in a semi-random way, // so that any token with small decimals can still be bridged in some amounts. // It is possible to override limits for the particular token later if needed. _minPerTx = 1; if (_maxPerTx <= _minPerTx) { _maxPerTx = 100; _executionMaxPerTx = 100; if (_dailyLimit <= _maxPerTx || _executionDailyLimit <= _executionMaxPerTx) { _dailyLimit = 10000; _executionDailyLimit = 10000; } } } _setLimits(_token, [_dailyLimit, _maxPerTx, _minPerTx]); _setExecutionLimits(_token, [_executionDailyLimit, _executionMaxPerTx]); } else { factor = 10**(_decimals - 18); _setLimits( _token, [dailyLimit(address(0)).mul(factor), maxPerTx(address(0)).mul(factor), minPerTx(address(0)).mul(factor)] ); _setExecutionLimits( _token, [executionDailyLimit(address(0)).mul(factor), executionMaxPerTx(address(0)).mul(factor)] ); } } } // File: contracts/libraries/Bytes.sol pragma solidity 0.4.24; /** * @title Bytes * @dev Helper methods to transform bytes to other solidity types. */ library Bytes { /** * @dev Converts bytes array to bytes32. * Truncates bytes array if its size is more than 32 bytes. * NOTE: This function does not perform any checks on the received parameter. * Make sure that the _bytes argument has a correct length, not less than 32 bytes. * A case when _bytes has length less than 32 will lead to the undefined behaviour, * since assembly will read data from memory that is not related to the _bytes argument. * @param _bytes to be converted to bytes32 type * @return bytes32 type of the firsts 32 bytes array in parameter. */ function bytesToBytes32(bytes _bytes) internal pure returns (bytes32 result) { assembly { result := mload(add(_bytes, 32)) } } /** * @dev Truncate bytes array if its size is more than 20 bytes. * NOTE: Similar to the bytesToBytes32 function, make sure that _bytes is not shorter than 20 bytes. * @param _bytes to be converted to address type * @return address included in the firsts 20 bytes of the bytes array in parameter. */ function bytesToAddress(bytes _bytes) internal pure returns (address addr) { assembly { addr := mload(add(_bytes, 20)) } } } // File: openzeppelin-solidity/contracts/AddressUtils.sol pragma solidity ^0.4.24; /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/upgradeable_contracts/BasicAMBMediator.sol pragma solidity 0.4.24; /** * @title BasicAMBMediator * @dev Basic storage and methods needed by mediators to interact with AMB bridge. */ contract BasicAMBMediator is Ownable { bytes32 internal constant BRIDGE_CONTRACT = 0x811bbb11e8899da471f0e69a3ed55090fc90215227fc5fb1cb0d6e962ea7b74f; // keccak256(abi.encodePacked("bridgeContract")) bytes32 internal constant MEDIATOR_CONTRACT = 0x98aa806e31e94a687a31c65769cb99670064dd7f5a87526da075c5fb4eab9880; // keccak256(abi.encodePacked("mediatorContract")) bytes32 internal constant REQUEST_GAS_LIMIT = 0x2dfd6c9f781bb6bbb5369c114e949b69ebb440ef3d4dd6b2836225eb1dc3a2be; // keccak256(abi.encodePacked("requestGasLimit")) /** * @dev Throws if caller on the other side is not an associated mediator. */ modifier onlyMediator { require(msg.sender == address(bridgeContract())); require(messageSender() == mediatorContractOnOtherSide()); _; } /** * @dev Sets the AMB bridge contract address. Only the owner can call this method. * @param _bridgeContract the address of the bridge contract. */ function setBridgeContract(address _bridgeContract) external onlyOwner { _setBridgeContract(_bridgeContract); } /** * @dev Sets the mediator contract address from the other network. Only the owner can call this method. * @param _mediatorContract the address of the mediator contract. */ function setMediatorContractOnOtherSide(address _mediatorContract) external onlyOwner { _setMediatorContractOnOtherSide(_mediatorContract); } /** * @dev Sets the gas limit to be used in the message execution by the AMB bridge on the other network. * This value can't exceed the parameter maxGasPerTx defined on the AMB bridge. * Only the owner can call this method. * @param _requestGasLimit the gas limit for the message execution. */ function setRequestGasLimit(uint256 _requestGasLimit) external onlyOwner { _setRequestGasLimit(_requestGasLimit); } /** * @dev Get the AMB interface for the bridge contract address * @return AMB interface for the bridge contract address */ function bridgeContract() public view returns (IAMB) { return IAMB(addressStorage[BRIDGE_CONTRACT]); } /** * @dev Tells the mediator contract address from the other network. * @return the address of the mediator contract. */ function mediatorContractOnOtherSide() public view returns (address) { return addressStorage[MEDIATOR_CONTRACT]; } /** * @dev Tells the gas limit to be used in the message execution by the AMB bridge on the other network. * @return the gas limit for the message execution. */ function requestGasLimit() public view returns (uint256) { return uintStorage[REQUEST_GAS_LIMIT]; } /** * @dev Stores a valid AMB bridge contract address. * @param _bridgeContract the address of the bridge contract. */ function _setBridgeContract(address _bridgeContract) internal { require(AddressUtils.isContract(_bridgeContract)); addressStorage[BRIDGE_CONTRACT] = _bridgeContract; } /** * @dev Stores the mediator contract address from the other network. * @param _mediatorContract the address of the mediator contract. */ function _setMediatorContractOnOtherSide(address _mediatorContract) internal { addressStorage[MEDIATOR_CONTRACT] = _mediatorContract; } /** * @dev Stores the gas limit to be used in the message execution by the AMB bridge on the other network. * @param _requestGasLimit the gas limit for the message execution. */ function _setRequestGasLimit(uint256 _requestGasLimit) internal { require(_requestGasLimit <= maxGasPerTx()); uintStorage[REQUEST_GAS_LIMIT] = _requestGasLimit; } /** * @dev Tells the address that generated the message on the other network that is currently being executed by * the AMB bridge. * @return the address of the message sender. */ function messageSender() internal view returns (address) { return bridgeContract().messageSender(); } /** * @dev Tells the id of the message originated on the other network. * @return the id of the message originated on the other network. */ function messageId() internal view returns (bytes32) { return bridgeContract().messageId(); } /** * @dev Tells the maximum gas limit that a message can use on its execution by the AMB bridge on the other network. * @return the maximum gas limit value. */ function maxGasPerTx() internal view returns (uint256) { return bridgeContract().maxGasPerTx(); } } // File: contracts/upgradeable_contracts/ChooseReceiverHelper.sol pragma solidity 0.4.24; contract ChooseReceiverHelper { /** * @dev Helper function for alternative receiver feature. Chooses the actual receiver out of sender and passed data. * @param _from address of tokens sender. * @param _data passed data in the transfer message. * @return address of the receiver on the other side. */ function chooseReceiver(address _from, bytes _data) internal view returns (address recipient) { recipient = _from; if (_data.length > 0) { require(_data.length == 20); recipient = Bytes.bytesToAddress(_data); require(recipient != address(0)); require(recipient != bridgeContractOnOtherSide()); } } /* solcov ignore next */ function bridgeContractOnOtherSide() internal view returns (address); } // File: contracts/upgradeable_contracts/TransferInfoStorage.sol pragma solidity 0.4.24; contract TransferInfoStorage is EternalStorage { /** * @dev Stores the value of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _value amount of tokens bridged. */ function setMessageValue(bytes32 _messageId, uint256 _value) internal { uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))] = _value; } /** * @dev Tells the amount of tokens of a message sent to the AMB bridge. * @return value representing amount of tokens. */ function messageValue(bytes32 _messageId) internal view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("messageValue", _messageId))]; } /** * @dev Stores the receiver of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _recipient receiver of the tokens bridged. */ function setMessageRecipient(bytes32 _messageId, address _recipient) internal { addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))] = _recipient; } /** * @dev Tells the receiver of a message sent to the AMB bridge. * @return address of the receiver. */ function messageRecipient(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageRecipient", _messageId))]; } /** * @dev Sets that the message sent to the AMB bridge has been fixed. * @param _messageId of the message sent to the bridge. */ function setMessageFixed(bytes32 _messageId) internal { boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))] = true; } /** * @dev Tells if a message sent to the AMB bridge has been fixed. * @return bool indicating the status of the message. */ function messageFixed(bytes32 _messageId) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("messageFixed", _messageId))]; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenBridgeMediator.sol pragma solidity 0.4.24; /** * @title MultiTokenBridgeMediator * @dev Common mediator functionality to handle operations related to multi-token bridge messages sent to AMB bridge. */ contract MultiTokenBridgeMediator is BasicAMBMediator, BasicMultiTokenBridge, TransferInfoStorage, ChooseReceiverHelper { event FailedMessageFixed(bytes32 indexed messageId, address token, address recipient, uint256 value); event TokensBridgingInitiated( address indexed token, address indexed sender, uint256 value, bytes32 indexed messageId ); event TokensBridged(address indexed token, address indexed recipient, uint256 value, bytes32 indexed messageId); /** * @dev Stores the bridged token of a message sent to the AMB bridge. * @param _messageId of the message sent to the bridge. * @param _token bridged token address. */ function setMessageToken(bytes32 _messageId, address _token) internal { addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))] = _token; } /** * @dev Tells the bridged token address of a message sent to the AMB bridge. * @return address of a token contract. */ function messageToken(bytes32 _messageId) internal view returns (address) { return addressStorage[keccak256(abi.encodePacked("messageToken", _messageId))]; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20/ERC677 token * @param _recipient address that will receive the tokens * @param _value amount of tokens to be received */ function _handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) internal { if (withinExecutionLimit(_token, _value)) { addTotalExecutedPerDay(_token, getCurrentDay(), _value); executeActionOnBridgedTokens(_token, _recipient, _value); } else { executeActionOnBridgedTokensOutOfLimit(_token, _recipient, _value); } } /** * @dev Method to be called when a bridged message execution failed. It will generate a new message requesting to * fix/roll back the transferred assets on the other network. * @param _messageId id of the message which execution failed. */ function requestFailedMessageFix(bytes32 _messageId) external { require(!bridgeContract().messageCallStatus(_messageId)); require(bridgeContract().failedMessageReceiver(_messageId) == address(this)); require(bridgeContract().failedMessageSender(_messageId) == mediatorContractOnOtherSide()); bytes4 methodSelector = this.fixFailedMessage.selector; bytes memory data = abi.encodeWithSelector(methodSelector, _messageId); bridgeContract().requireToPassMessage(mediatorContractOnOtherSide(), data, requestGasLimit()); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public onlyMediator { require(!messageFixed(_messageId)); address token = messageToken(_messageId); address recipient = messageRecipient(_messageId); uint256 value = messageValue(_messageId); setMessageFixed(_messageId); executeActionOnFixedTokens(token, recipient, value); emit FailedMessageFixed(_messageId, token, recipient, value); } /** * @dev Execute the action to be performed when the bridge tokens are out of execution limits. */ function executeActionOnBridgedTokensOutOfLimit(address, address, uint256) internal { revert(); } /* solcov ignore next */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal; /* solcov ignore next */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal; } // File: contracts/upgradeable_contracts/Initializable.sol pragma solidity 0.4.24; contract Initializable is EternalStorage { bytes32 internal constant INITIALIZED = 0x0a6f646cd611241d8073675e00d1a1ff700fbf1b53fcf473de56d1e6e4b714ba; // keccak256(abi.encodePacked("isInitialized")) function setInitialize() internal { boolStorage[INITIALIZED] = true; } function isInitialized() public view returns (bool) { return boolStorage[INITIALIZED]; } } // File: contracts/upgradeable_contracts/ReentrancyGuard.sol pragma solidity 0.4.24; contract ReentrancyGuard is EternalStorage { bytes32 internal constant LOCK = 0x6168652c307c1e813ca11cfb3a601f1cf3b22452021a5052d8b05f1f1f8a3e92; // keccak256(abi.encodePacked("lock")) function lock() internal returns (bool) { return boolStorage[LOCK]; } function setLock(bool _lock) internal { boolStorage[LOCK] = _lock; } } // File: contracts/upgradeable_contracts/Upgradeable.sol pragma solidity 0.4.24; contract Upgradeable { // Avoid using onlyUpgradeabilityOwner name to prevent issues with implementation from proxy contract modifier onlyIfUpgradeabilityOwner() { require(msg.sender == IUpgradeabilityOwnerStorage(this).upgradeabilityOwner()); /* solcov ignore next */ _; } } // File: contracts/upgradeable_contracts/Sacrifice.sol pragma solidity 0.4.24; contract Sacrifice { constructor(address _recipient) public payable { selfdestruct(_recipient); } } // File: contracts/libraries/Address.sol pragma solidity 0.4.24; /** * @title Address * @dev Helper methods for Address type. */ library Address { /** * @dev Try to send native tokens to the address. If it fails, it will force the transfer by creating a selfdestruct contract * @param _receiver address that will receive the native tokens * @param _value the amount of native tokens to send */ function safeSendValue(address _receiver, uint256 _value) internal { if (!_receiver.send(_value)) { (new Sacrifice).value(_value)(_receiver); } } } // File: contracts/libraries/SafeERC20.sol pragma solidity 0.4.24; /** * @title SafeERC20 * @dev Helper methods for safe token transfers. * Functions perform additional checks to be sure that token transfer really happened. */ library SafeERC20 { using SafeMath for uint256; /** * @dev Same as ERC20.transfer(address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _to address of the receiver * @param _value amount of tokens to send */ function safeTransfer(address _token, address _to, uint256 _value) internal { LegacyERC20(_token).transfer(_to, _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } /** * @dev Same as ERC20.transferFrom(address,address,uint256) but with extra consistency checks. * @param _token address of the token contract * @param _from address of the sender * @param _value amount of tokens to send */ function safeTransferFrom(address _token, address _from, uint256 _value) internal { LegacyERC20(_token).transferFrom(_from, address(this), _value); assembly { if returndatasize { returndatacopy(0, 0, 32) if iszero(mload(0)) { revert(0, 0) } } } } } // File: contracts/upgradeable_contracts/Claimable.sol pragma solidity 0.4.24; /** * @title Claimable * @dev Implementation of the claiming utils that can be useful for withdrawing accidentally sent tokens that are not used in bridge operations. */ contract Claimable { using SafeERC20 for address; /** * Throws if a given address is equal to address(0) */ modifier validAddress(address _to) { require(_to != address(0)); /* solcov ignore next */ _; } /** * @dev Withdraws the erc20 tokens or native coins from this contract. * Caller should additionally check that the claimed token is not a part of bridge operations (i.e. that token != erc20token()). * @param _token address of the claimed token or address(0) for native coins. * @param _to address of the tokens/coins receiver. */ function claimValues(address _token, address _to) internal validAddress(_to) { if (_token == address(0)) { claimNativeCoins(_to); } else { claimErc20Tokens(_token, _to); } } /** * @dev Internal function for withdrawing all native coins from the contract. * @param _to address of the coins receiver. */ function claimNativeCoins(address _to) internal { uint256 value = address(this).balance; Address.safeSendValue(_to, value); } /** * @dev Internal function for withdrawing all tokens of ssome particular ERC20 contract from this contract. * @param _token address of the claimed ERC20 token. * @param _to address of the tokens receiver. */ function claimErc20Tokens(address _token, address _to) internal { ERC20Basic token = ERC20Basic(_token); uint256 balance = token.balanceOf(this); _token.safeTransfer(_to, balance); } } // File: contracts/upgradeable_contracts/VersionableBridge.sol pragma solidity 0.4.24; contract VersionableBridge { function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (5, 2, 0); } /* solcov ignore next */ function getBridgeMode() external pure returns (bytes4); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/BasicMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title BasicMultiAMBErc20ToErc677 * @dev Common functionality for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. */ contract BasicMultiAMBErc20ToErc677 is Initializable, ReentrancyGuard, Upgradeable, Claimable, VersionableBridge, MultiTokenBridgeMediator { /** * @dev Tells the address of the mediator contract on the other side, used by chooseReceiver method * to avoid sending the native tokens to that address. * @return address of the mediator contract con the other side */ function bridgeContractOnOtherSide() internal view returns (address) { return mediatorContractOnOtherSide(); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, address _receiver, uint256 _value) external { _relayTokens(token, _receiver, _value); } /** * @dev Initiate the bridge operation for some amount of tokens from msg.sender to msg.sender on the other side. * The user should first call Approve method of the ERC677 token. * @param token bridged token contract address. * @param _value amount of tokens to be transferred to the other network. */ function relayTokens(ERC677 token, uint256 _value) external { _relayTokens(token, msg.sender, _value); } /** * @dev Tells the bridge interface version that this contract supports. * @return major value of the version * @return minor value of the version * @return patch value of the version */ function getBridgeInterfacesVersion() external pure returns (uint64 major, uint64 minor, uint64 patch) { return (1, 2, 0); } /** * @dev Tells the bridge mode that this contract supports. * @return _data 4 bytes representing the bridge mode */ function getBridgeMode() external pure returns (bytes4 _data) { return 0xb1516c26; // bytes4(keccak256(abi.encodePacked("multi-erc-to-erc-amb"))) } /** * @dev Claims stucked tokens. Only unsupported tokens can be claimed. * When dealing with already supported tokens, fixMediatorBalance can be used instead. * @param _token address of claimed token, address(0) for native * @param _to address of tokens receiver */ function claimTokens(address _token, address _to) external onlyIfUpgradeabilityOwner { // Only unregistered tokens and native coins are allowed to be claimed with the use of this function require(_token == address(0) || !isTokenRegistered(_token)); claimValues(_token, _to); } /* solcov ignore next */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool); /* solcov ignore next */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal; /* solcov ignore next */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal; } // File: contracts/upgradeability/Proxy.sol pragma solidity 0.4.24; /** * @title Proxy * @dev Gives the possibility to delegate any call to a foreign implementation. */ contract Proxy { /** * @dev Tells the address of the implementation where every call will be delegated. * @return address of the implementation to which it will be delegated */ /* solcov ignore next */ function implementation() public view returns (address); /** * @dev Fallback function allowing to perform a delegatecall to the given implementation. * This function will return whatever the implementation call returns */ function() public payable { // solhint-disable-previous-line no-complex-fallback address _impl = implementation(); require(_impl != address(0)); assembly { /* 0x40 is the "free memory slot", meaning a pointer to next slot of empty memory. mload(0x40) loads the data in the free memory slot, so `ptr` is a pointer to the next slot of empty memory. It's needed because we're going to write the return data of delegatecall to the free memory slot. */ let ptr := mload(0x40) /* `calldatacopy` is copy calldatasize bytes from calldata First argument is the destination to which data is copied(ptr) Second argument specifies the start position of the copied data. Since calldata is sort of its own unique location in memory, 0 doesn't refer to 0 in memory or 0 in storage - it just refers to the zeroth byte of calldata. That's always going to be the zeroth byte of the function selector. Third argument, calldatasize, specifies how much data will be copied. calldata is naturally calldatasize bytes long (same thing as msg.data.length) */ calldatacopy(ptr, 0, calldatasize) /* delegatecall params explained: gas: the amount of gas to provide for the call. `gas` is an Opcode that gives us the amount of gas still available to execution _impl: address of the contract to delegate to ptr: to pass copied data calldatasize: loads the size of `bytes memory data`, same as msg.data.length 0, 0: These are for the `out` and `outsize` params. Because the output could be dynamic, these are set to 0, 0 so the output data will not be written to memory. The output data will be read using `returndatasize` and `returdatacopy` instead. result: This will be 0 if the call fails and 1 if it succeeds */ let result := delegatecall(gas, _impl, ptr, calldatasize, 0, 0) /* */ /* ptr current points to the value stored at 0x40, because we assigned it like ptr := mload(0x40). Because we use 0x40 as a free memory pointer, we want to make sure that the next time we want to allocate memory, we aren't overwriting anything important. So, by adding ptr and returndatasize, we get a memory location beyond the end of the data we will be copying to ptr. We place this in at 0x40, and any reads from 0x40 will now read from free memory */ mstore(0x40, add(ptr, returndatasize)) /* `returndatacopy` is an Opcode that copies the last return data to a slot. `ptr` is the slot it will copy to, 0 means copy from the beginning of the return data, and size is the amount of data to copy. `returndatasize` is an Opcode that gives us the size of the last return data. In this case, that is the size of the data returned from delegatecall */ returndatacopy(ptr, 0, returndatasize) /* if `result` is 0, revert. if `result` is 1, return `size` amount of data from `ptr`. This is the data that was copied to `ptr` from the delegatecall return data */ switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } } // File: contracts/interfaces/IBridgeMediator.sol interface IBridgeMediator { function tokenImage() public view returns (address); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/TokenProxy.sol pragma solidity 0.4.24; interface IPermittableTokenVersion { function version() external pure returns (string); } /** * @title TokenProxy * @dev Helps to reduces the size of the deployed bytecode for automatically created tokens, by using a proxy contract. */ contract TokenProxy is Proxy { // storage layout is copied from PermittableToken.sol string internal name; string internal symbol; uint8 internal decimals; mapping(address => uint256) internal balances; uint256 internal totalSupply; mapping(address => mapping(address => uint256)) internal allowed; address internal owner; bool internal mintingFinished; address internal bridgeContractAddr; // string public constant version = "1"; bytes32 internal DOMAIN_SEPARATOR; // bytes32 public constant PERMIT_TYPEHASH = 0xea2aa0a1be11a07ed86d755c93467f4f82362b452371d1ba94d1715123511acb; mapping(address => uint256) internal nonces; mapping(address => mapping(address => uint256)) internal expirations; /** * @dev Creates a non-upgradeable token proxy for PermitableToken.sol, initializes its eternalStorage. * @param _tokenImage address of the token image used for mirroring all functions. * @param _name token name. * @param _symbol token symbol. * @param _decimals token decimals. * @param _chainId chain id for current network. */ constructor(address _tokenImage, string memory _name, string memory _symbol, uint8 _decimals, uint256 _chainId) public { string memory version = IPermittableTokenVersion(_tokenImage).version(); name = _name; symbol = _symbol; decimals = _decimals; owner = msg.sender; // msg.sender == HomeMultiAMBErc20ToErc677 mediator bridgeContractAddr = msg.sender; DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(_name)), keccak256(bytes(version)), _chainId, address(this) ) ); } /** * @dev Retrieves the implementation contract address, mirrored token image. * @return token image address. */ function implementation() public view returns (address impl) { return IBridgeMediator(bridgeContractAddr).tokenImage(); } } // File: contracts/upgradeable_contracts/BaseRewardAddressList.sol pragma solidity 0.4.24; /** * @title BaseRewardAddressList * @dev Implements the logic to store, add and remove reward account addresses. Works as a linked list. */ contract BaseRewardAddressList is EternalStorage { using SafeMath for uint256; address public constant F_ADDR = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; uint256 internal constant MAX_REWARD_ADDRESSES = 50; bytes32 internal constant REWARD_ADDRESS_COUNT = 0xabc77c82721ced73eef2645facebe8c30249e6ac372cce6eb9d1fed31bd6648f; // keccak256(abi.encodePacked("rewardAddressCount")) event RewardAddressAdded(address indexed addr); event RewardAddressRemoved(address indexed addr); /** * @dev Retrieves all registered reward accounts. * @return address list of the registered reward receivers. */ function rewardAddressList() external view returns (address[]) { address[] memory list = new address[](rewardAddressCount()); uint256 counter = 0; address nextAddr = getNextRewardAddress(F_ADDR); while (nextAddr != F_ADDR) { require(nextAddr != address(0)); list[counter] = nextAddr; nextAddr = getNextRewardAddress(nextAddr); counter++; } return list; } /** * @dev Retrieves amount of registered reward accounts. * @return length of reward addresses list. */ function rewardAddressCount() public view returns (uint256) { return uintStorage[REWARD_ADDRESS_COUNT]; } /** * @dev Checks if specified address is included into the registered rewards receivers list. * @param _addr address to verify. * @return true, if specified address is associated with one of the registered reward accounts. */ function isRewardAddress(address _addr) public view returns (bool) { return _addr != F_ADDR && getNextRewardAddress(_addr) != address(0); } /** * @dev Retrieves next reward address in the linked list, or F_ADDR if given address is the last one. * @param _address address of some reward account. * @return address of the next reward receiver. */ function getNextRewardAddress(address _address) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("rewardAddressList", _address))]; } /** * @dev Internal function for adding a new reward address to the linked list. * @param _addr new reward account. */ function _addRewardAddress(address _addr) internal { require(_addr != address(0) && _addr != F_ADDR); require(!isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != address(0)); _setNextRewardAddress(_addr, nextAddr); _setNextRewardAddress(F_ADDR, _addr); _setRewardAddressCount(rewardAddressCount().add(1)); } /** * @dev Internal function for removing existing reward address from the linked list. * @param _addr old reward account which should be removed. */ function _removeRewardAddress(address _addr) internal { require(isRewardAddress(_addr)); address nextAddr = getNextRewardAddress(_addr); address index = F_ADDR; address next = getNextRewardAddress(index); while (next != _addr) { require(next != address(0)); index = next; next = getNextRewardAddress(index); require(next != F_ADDR); } _setNextRewardAddress(index, nextAddr); delete addressStorage[keccak256(abi.encodePacked("rewardAddressList", _addr))]; _setRewardAddressCount(rewardAddressCount().sub(1)); } /** * @dev Internal function for initializing linked list with the array of the initial reward addresses. * @param _rewardAddresses initial reward addresses list, should be non-empty. */ function _setRewardAddressList(address[] _rewardAddresses) internal { require(_rewardAddresses.length > 0); _setNextRewardAddress(F_ADDR, _rewardAddresses[0]); for (uint256 i = 0; i < _rewardAddresses.length; i++) { require(_rewardAddresses[i] != address(0) && _rewardAddresses[i] != F_ADDR); require(!isRewardAddress(_rewardAddresses[i])); if (i == _rewardAddresses.length - 1) { _setNextRewardAddress(_rewardAddresses[i], F_ADDR); } else { _setNextRewardAddress(_rewardAddresses[i], _rewardAddresses[i + 1]); } emit RewardAddressAdded(_rewardAddresses[i]); } _setRewardAddressCount(_rewardAddresses.length); } /** * @dev Internal function for updating the length of the reward accounts list. * @param _rewardAddressCount new linked list length. */ function _setRewardAddressCount(uint256 _rewardAddressCount) internal { require(_rewardAddressCount <= MAX_REWARD_ADDRESSES); uintStorage[REWARD_ADDRESS_COUNT] = _rewardAddressCount; } /** * @dev Internal function for updating the pointer to the next reward receiver. * @param _prevAddr address of some reward receiver. * @param _addr address of the next receiver to which _prevAddr should point to. */ function _setNextRewardAddress(address _prevAddr, address _addr) internal { addressStorage[keccak256(abi.encodePacked("rewardAddressList", _prevAddr))] = _addr; } } // File: contracts/interfaces/IBurnableMintableERC677Token.sol pragma solidity 0.4.24; contract IBurnableMintableERC677Token is ERC677 { function mint(address _to, uint256 _amount) public returns (bool); function burn(uint256 _value) public; function claimTokens(address _token, address _to) external; } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeFeeManagerMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeFeeManagerMultiAMBErc20ToErc677 * @dev Implements the logic to distribute fees from the multi erc20 to erc677 mediator contract operations. * The fees are distributed in the form of native tokens to the list of reward accounts. */ contract HomeFeeManagerMultiAMBErc20ToErc677 is BaseRewardAddressList, Ownable, BasicMultiTokenBridge { using SafeMath for uint256; event FeeUpdated(bytes32 feeType, address indexed token, uint256 fee); event FeeDistributed(uint256 fee, address indexed token, bytes32 indexed messageId); // This is not a real fee value but a relative value used to calculate the fee percentage uint256 internal constant MAX_FEE = 1 ether; bytes32 public constant HOME_TO_FOREIGN_FEE = 0x741ede137d0537e88e0ea0ff25b1f22d837903dbbee8980b4a06e8523247ee26; // keccak256(abi.encodePacked("homeToForeignFee")) bytes32 public constant FOREIGN_TO_HOME_FEE = 0x03be2b2875cb41e0e77355e802a16769bb8dfcf825061cde185c73bf94f12625; // keccak256(abi.encodePacked("foreignToHomeFee")) /** * @dev Throws if given fee percentage is >= 100%. */ modifier validFee(uint256 _fee) { require(_fee < MAX_FEE); /* solcov ignore next */ _; } /** * @dev Throws if given fee type is unknown. */ modifier validFeeType(bytes32 _feeType) { require(_feeType == HOME_TO_FOREIGN_FEE || _feeType == FOREIGN_TO_HOME_FEE); /* solcov ignore next */ _; } /** * @dev Adds a new reward address to the list, which will receive fees collected from the bridge operations. * Only the owner can call this method. * @param _addr new reward account. */ function addRewardAddress(address _addr) external onlyOwner { _addRewardAddress(_addr); } /** * @dev Removes a reward address from the rewards list. * Only the owner can call this method. * @param _addr old reward account, that should be removed. */ function removeRewardAddress(address _addr) external onlyOwner { _removeRewardAddress(_addr); } /** * @dev Updates the value for the particular fee type. * Only the owner can call this method. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function setFee(bytes32 _feeType, address _token, uint256 _fee) external onlyOwner { _setFee(_feeType, _token, _fee); } /** * @dev Retrieves the value for the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @return fee value associated with the requested fee type. */ function getFee(bytes32 _feeType, address _token) public view validFeeType(_feeType) returns (uint256) { return uintStorage[keccak256(abi.encodePacked(_feeType, _token))]; } /** * @dev Calculates the amount of fee to pay for the value of the particular fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return amount of fee to be subtracted from the transferred value. */ function calculateFee(bytes32 _feeType, address _token, uint256 _value) public view returns (uint256) { uint256 _fee = getFee(_feeType, _token); return _value.mul(_fee).div(MAX_FEE); } /** * @dev Internal function for updating the fee value for the given fee type. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _fee new fee value, in percentage (1 ether == 10**18 == 100%). */ function _setFee(bytes32 _feeType, address _token, uint256 _fee) internal validFeeType(_feeType) validFee(_fee) { require(isTokenRegistered(_token)); uintStorage[keccak256(abi.encodePacked(_feeType, _token))] = _fee; emit FeeUpdated(_feeType, _token, _fee); } /** * @dev Calculates a random number based on the block number. * @param _count the max value for the random number. * @return a number between 0 and _count. */ function random(uint256 _count) internal view returns (uint256) { return uint256(blockhash(block.number.sub(1))) % _count; } /** * @dev Calculates and distributes the amount of fee proportionally between registered reward addresses. * @param _feeType type of the updated fee, can be one of [HOME_TO_FOREIGN_FEE, FOREIGN_TO_HOME_FEE]. * @param _token address of the token contract for which fee should apply, 0x00..00 describes the initial fee for newly created tokens. * @param _value bridged value, for which fee should be evaluated. * @return total amount of fee subtracted from the transferred value and distributed between the reward accounts. */ function _distributeFee(bytes32 _feeType, address _token, uint256 _value) internal returns (uint256) { uint256 numOfAccounts = rewardAddressCount(); uint256 _fee = calculateFee(_feeType, _token, _value); if (numOfAccounts == 0 || _fee == 0) { return 0; } uint256 feePerAccount = _fee.div(numOfAccounts); uint256 randomAccountIndex; uint256 diff = _fee.sub(feePerAccount.mul(numOfAccounts)); if (diff > 0) { randomAccountIndex = random(numOfAccounts); } address nextAddr = getNextRewardAddress(F_ADDR); require(nextAddr != F_ADDR && nextAddr != address(0)); uint256 i = 0; while (nextAddr != F_ADDR) { uint256 feeToDistribute = feePerAccount; if (diff > 0 && randomAccountIndex == i) { feeToDistribute = feeToDistribute.add(diff); } if (_feeType == HOME_TO_FOREIGN_FEE) { ERC677(_token).transfer(nextAddr, feeToDistribute); } else { IBurnableMintableERC677Token(_token).mint(nextAddr, feeToDistribute); } nextAddr = getNextRewardAddress(nextAddr); require(nextAddr != address(0)); i = i + 1; } return _fee; } } // File: contracts/interfaces/IBridgeUtils.sol pragma solidity 0.4.24; interface IBridgeUtils { function addToken(address _tokenAddr) external returns (bool); function registerSupplier(address ownerAddr) external returns (address); function isRegistered(address supplierAddr) public view returns (bool); function safeForSupplier(address supplierAddr) public view returns (address); } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/MultiTokenForwardingRules.sol pragma solidity 0.4.24; /** * @title MultiTokenForwardingRules * @dev Multi token mediator functionality for managing destination AMB lanes permissions. */ contract MultiTokenForwardingRules is Ownable { address internal constant ANY_ADDRESS = 0xFFfFfFffFFfffFFfFFfFFFFFffFFFffffFfFFFfF; event ForwardingRuleUpdated(address token, address sender, address receiver, int256 lane); /** * @dev Tells the destination lane for a particular bridge operation by checking several wildcard forwarding rules. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return destination lane identifier, where the message should be forwarded to. * 1 - oracle-driven-lane should be used. * 0 - default behaviour should be applied. * -1 - manual lane should be used. */ function destinationLane(address _token, address _sender, address _receiver) public view returns (int256) { int256 defaultLane = forwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS); // specific token for all senders and receivers int256 lane; if (defaultLane < 0) { lane = forwardingRule(_token, _sender, ANY_ADDRESS); // specific token for specific sender if (lane != 0) return lane; lane = forwardingRule(_token, ANY_ADDRESS, _receiver); // specific token for specific receiver if (lane != 0) return lane; return defaultLane; } lane = forwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS); // all tokens for specific sender if (lane != 0) return lane; return forwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver); // all tokens for specific receiver } /** * Updates the forwarding rule for bridging specific token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _enable true, if bridge operations for a given token should be forwarded to the manual lane. */ function setTokenForwardingRule(address _token, bool _enable) external { require(_token != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Allows a particular address to send bridge requests to the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _sender address of the tokens sender on the home side of the bridge. * @param _enable true, if bridge operations for a given token and sender should be forwarded to the oracle-driven lane. */ function setSenderExceptionForTokenForwardingRule(address _token, address _sender, bool _enable) external { require(_token != ANY_ADDRESS); require(_sender != ANY_ADDRESS); _setForwardingRule(_token, _sender, ANY_ADDRESS, _enable ? int256(1) : int256(0)); } /** * Allows a particular address to receive bridged tokens from the oracle-driven lane for a particular token. * Only owner can call this method. * @param _token address of the token contract on the foreign side. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _enable true, if bridge operations for a given token and receiver should be forwarded to the oracle-driven lane. */ function setReceiverExceptionForTokenForwardingRule(address _token, address _receiver, bool _enable) external { require(_token != ANY_ADDRESS); require(_receiver != ANY_ADDRESS); _setForwardingRule(_token, ANY_ADDRESS, _receiver, _enable ? int256(1) : int256(0)); } /** * Updates the forwarding rule for the specific sender. * Only owner can call this method. * @param _sender address of the tokens sender on the home side. * @param _enable true, if all bridge operations from a given sender should be forwarded to the manual lane. */ function setSenderForwardingRule(address _sender, bool _enable) external { require(_sender != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, _sender, ANY_ADDRESS, _enable ? int256(-1) : int256(0)); } /** * Updates the forwarding rule for the specific receiver. * Only owner can call this method. * @param _receiver address of the tokens receiver on the foreign side. * @param _enable true, if all bridge operations to a given receiver should be forwarded to the manual lane. */ function setReceiverForwardingRule(address _receiver, bool _enable) external { require(_receiver != ANY_ADDRESS); _setForwardingRule(ANY_ADDRESS, ANY_ADDRESS, _receiver, _enable ? int256(-1) : int256(0)); } /** * @dev Tells forwarding rule set up for a particular bridge operation. * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @return preferred destination lane for the particular bridge operation. */ function forwardingRule(address _token, address _sender, address _receiver) public view returns (int256) { return intStorage[keccak256(abi.encodePacked("f2", _token, _sender, _receiver))]; } /** * @dev Internal function for updating the preferred destination lane for the specific wildcard pattern. * Only owner can call this method. * Examples: * _setForwardingRule(tokenA, ANY_ADDRESS, ANY_ADDRESS, -1) - forward all operations on tokenA to the manual lane * _setForwardingRule(tokenA, Alice, ANY_ADDRESS, 1) - allow Alice to use the oracle-driven lane for bridging tokenA * _setForwardingRule(tokenA, ANY_ADDRESS, Bob, 1) - forward all tokenA bridge operations, where Bob is the receiver, to the oracle-driven lane * _setForwardingRule(ANY_ADDRESS, Mallory, ANY_ADDRESS, -1) - forward all bridge operations from Mallory to the manual lane * @param _token address of the token contract on the foreign side of the bridge. * @param _sender address of the tokens sender on the home side of the bridge. * @param _receiver address of the tokens receiver on the foreign side of the bridge. * @param _lane preferred destination lane for the particular sender. * 1 - forward to the oracle-driven lane. * 0 - behaviour is unset, proceed by checking other less-specific rules. * -1 - manual lane should be used. */ function _setForwardingRule(address _token, address _sender, address _receiver, int256 _lane) internal onlyOwner { intStorage[keccak256(abi.encodePacked("f2", _token, _sender, _receiver))] = _lane; emit ForwardingRuleUpdated(_token, _sender, _receiver, _lane); } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/HomeMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title HomeMultiAMBErc20ToErc677 * @dev Home side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract HomeMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677, HomeFeeManagerMultiAMBErc20ToErc677, MultiTokenForwardingRules { bytes32 internal constant TOKEN_IMAGE_CONTRACT = 0x20b8ca26cc94f39fab299954184cf3a9bd04f69543e4f454fab299f015b8130f; // keccak256(abi.encodePacked("tokenImageContract")) bytes32 internal constant BRIDGE_UTILS_CONTRACT = 0x174a58966ad4181674ba19a3131ba82f8683cbe56350f1172634244845855e9b; // keccak256(abi.encodePacked("bridgeUtilsContract")) event NewTokenRegistered(address indexed foreignToken, address indexed homeToken); event TokensBridgedToSafe( address indexed token, address indexed recipient, address safe, uint256 value, bytes32 indexed messageId ); /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. * @param _tokenImage address of the PermittableToken contract that will be used for deploying of new tokens. * @param _rewardAddresses list of reward addresses, between whom fees will be distributed. * @param _fees array with initial fees for both bridge directions. * [ 0 = homeToForeignFee, 1 = foreignToHomeFee ] */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner, address _tokenImage, address[] _rewardAddresses, uint256[2] _fees, // [ 0 = homeToForeignFee, 1 = foreignToHomeFee ], address _bridgeUtilsContract ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setBridgeUtilsContract(_bridgeUtilsContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); _setTokenImage(_tokenImage); if (_rewardAddresses.length > 0) { _setRewardAddressList(_rewardAddresses); } _setFee(HOME_TO_FOREIGN_FEE, address(0), _fees[0]); _setFee(FOREIGN_TO_HOME_FEE, address(0), _fees[1]); setInitialize(); return isInitialized(); } /** * @dev Updates an address of the token image contract used for proxifying newly created tokens. * @param _tokenImage address of PermittableToken contract. */ function setTokenImage(address _tokenImage) external onlyOwner { _setTokenImage(_tokenImage); } function setBridgeUtilsContract(address _bridgeUtilsContract) external onlyOwner { _setBridgeUtilsContract(_bridgeUtilsContract); } function _setBridgeUtilsContract(address _bridgeUtilsContract) internal { require(AddressUtils.isContract(_bridgeUtilsContract)); addressStorage[BRIDGE_UTILS_CONTRACT] = _bridgeUtilsContract; } /** * @dev Retrieves address of the token image contract. * @return address of block reward contract. */ function tokenImage() public view returns (address) { return addressStorage[TOKEN_IMAGE_CONTRACT]; } function bridgeUtils() public view returns (address) { return addressStorage[BRIDGE_UTILS_CONTRACT]; } /** * @dev Handles the bridged tokens for the first time, includes deployment of new TokenProxy contract. * Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token address of the bridged ERC20/ERC677 token on the foreign side. * @param _name name of the bridged token, "x" will be appended, if empty, symbol will be used instead. * @param _symbol symbol of the bridged token, "x" will be appended, if empty, name will be used instead. * @param _decimals decimals of the bridge foreign token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function deployAndHandleBridgedTokens( address _token, string _name, string _symbol, uint8 _decimals, address _recipient, uint256 _value ) external onlyMediator { string memory name = _name; string memory symbol = _symbol; require(bytes(name).length > 0 || bytes(symbol).length > 0); if (bytes(name).length == 0) { name = symbol; } else if (bytes(symbol).length == 0) { symbol = name; } name = string(abi.encodePacked(name, ".CPXD")); address homeToken = new TokenProxy(tokenImage(), name, symbol, _decimals, bridgeContract().sourceChainId()); _setTokenAddressPair(_token, homeToken); _initializeTokenBridgeLimits(homeToken, _decimals); _setFee(HOME_TO_FOREIGN_FEE, homeToken, getFee(HOME_TO_FOREIGN_FEE, address(0))); _setFee(FOREIGN_TO_HOME_FEE, homeToken, getFee(FOREIGN_TO_HOME_FEE, address(0))); IBridgeUtils bridgeUtilsInstance = IBridgeUtils(bridgeUtils()); bridgeUtilsInstance.addToken(homeToken); _handleBridgedTokens(ERC677(homeToken), _recipient, _value); emit NewTokenRegistered(_token, homeToken); } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { ERC677 homeToken = ERC677(homeTokenAddress(_token)); require(isTokenRegistered(homeToken)); _handleBridgedTokens(homeToken, _recipient, _value); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { // if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing if (!lock()) { ERC677 token = ERC677(msg.sender); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); } return true; } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); address to = address(this); // if msg.sender if not a valid token contract, this check will fail, since limits are zeros // so the following check is not needed // require(isTokenRegistered(token)); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); setLock(true); token.transferFrom(msg.sender, to, _value); setLock(false); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, _value, abi.encodePacked(_receiver)); } /** * @dev Executes action on the request to deposit tokens relayed from the other network * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); uint256 valueToMint = _value; uint256 fee = _distributeFee(FOREIGN_TO_HOME_FEE, _token, valueToMint); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); valueToMint = valueToMint.sub(fee); } address safeAddress; IBridgeUtils bridgeUtilsInstance = IBridgeUtils(bridgeUtils()); if (bridgeUtilsInstance.isRegistered(_recipient)) { safeAddress = bridgeUtilsInstance.safeForSupplier(_recipient); require(safeAddress != address(0)); } else { safeAddress = bridgeUtilsInstance.registerSupplier(_recipient); } IBurnableMintableERC677Token(_token).mint(safeAddress, valueToMint); emit TokensBridgedToSafe(_token, _recipient, safeAddress, valueToMint, _messageId); } /** * @dev Mints back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { IBurnableMintableERC677Token(_token).mint(_recipient, _value); } /** * @dev Retrieves address of the home bridged token contract associated with a specific foreign token contract. * @param _foreignToken address of the created home token contract. * @return address of the home token contract. */ function homeTokenAddress(address _foreignToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("hta", _foreignToken))]; } /** * @dev Retrieves address of the foreign bridged token contract associated with a specific home token contract. * @param _homeToken address of the created home token contract. * @return address of the foreign token contract. */ function foreignTokenAddress(address _homeToken) public view returns (address) { return addressStorage[keccak256(abi.encodePacked("fta", _homeToken))]; } /** * @dev Internal function for updating an address of the token image contract. * @param _foreignToken address of bridged foreign token contract. * @param _foreignToken address of created home token contract. */ function _setTokenAddressPair(address _foreignToken, address _homeToken) internal { addressStorage[keccak256(abi.encodePacked("hta", _foreignToken))] = _homeToken; addressStorage[keccak256(abi.encodePacked("fta", _homeToken))] = _foreignToken; } /** * @dev Internal function for updating an address of the token image contract. * @param _tokenImage address of deployed PermittableToken contract. */ function _setTokenImage(address _tokenImage) internal { require(AddressUtils.isContract(_tokenImage)); addressStorage[TOKEN_IMAGE_CONTRACT] = _tokenImage; } /** * @dev Executes action on withdrawal of bridged tokens * @param _token address of token contract * @param _from address of tokens sender * @param _value requested amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (!lock()) { uint256 valueToBridge = _value; uint256 fee = 0; // Next line disables fee collection in case sender is one of the reward addresses. // It is needed to allow a 100% withdrawal of tokens from the home side. // If fees are not disabled for reward receivers, small fraction of tokens will always // be redistributed between the same set of reward addresses, which is not the desired behaviour. if (!isRewardAddress(_from)) { fee = _distributeFee(HOME_TO_FOREIGN_FEE, _token, valueToBridge); valueToBridge = valueToBridge.sub(fee); } IBurnableMintableERC677Token(_token).burn(valueToBridge); bytes32 _messageId = passMessage(_token, _from, chooseReceiver(_from, _data), valueToBridge); if (fee > 0) { emit FeeDistributed(fee, _token, _messageId); } } } /** * @dev Call AMB bridge to require the invocation of handleBridgedTokens method of the mediator on the other network. * Store information related to the bridged tokens in case the message execution fails on the other network * and the action needs to be fixed/rolled back. * @param _token bridged ERC20 token * @param _from address of sender, if bridge operation fails, tokens will be returned to this address * @param _receiver address of receiver on the other side, will eventually receive bridged tokens * @param _value bridged amount of tokens * @return id of the created and passed message */ function passMessage(ERC677 _token, address _from, address _receiver, uint256 _value) internal returns (bytes32) { bytes4 methodSelector = this.handleBridgedTokens.selector; address foreignToken = foreignTokenAddress(_token); bytes memory data = abi.encodeWithSelector(methodSelector, foreignToken, _receiver, _value); address executor = mediatorContractOnOtherSide(); uint256 gasLimit = requestGasLimit(); IAMB bridge = bridgeContract(); // Address of the foreign token is used here for determining lane permissions. // Such decision makes it possible to set rules for tokens that are not bridged yet. bytes32 _messageId = destinationLane(foreignToken, _from, _receiver) >= 0 ? bridge.requireToPassMessage(executor, data, gasLimit) : bridge.requireToConfirmMessage(executor, data, gasLimit); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); emit TokensBridgingInitiated(_token, _from, _value, _messageId); return _messageId; } } // File: contracts/libraries/TokenReader.sol pragma solidity 0.4.24; /** * @title TokenReader * @dev Helper methods for reading name/symbol/decimals parameters from ERC20 token contracts. */ library TokenReader { bytes4 private constant _NAME = 0x06fdde03; // web3.eth.abi.encodeFunctionSignature("name()") bytes4 private constant _NAME_CAPS = 0xa3f4df7e; // web3.eth.abi.encodeFunctionSignature("NAME()") bytes4 private constant _SYMBOL = 0x95d89b41; // web3.eth.abi.encodeFunctionSignature("symbol") bytes4 private constant _SYMBOL_CAPS = 0xf76f8d78; // web3.eth.abi.encodeFunctionSignature("SYMBOL()") bytes4 private constant _DECIMALS = 0x313ce567; // web3.eth.abi.encodeFunctionSignature("decimals()") bytes4 private constant _DECIMALS_CAPS = 0x2e0f2625; // web3.eth.abi.encodeFunctionSignature("DECIMALS()") bytes4 private constant _TOTAL_SUPPLY = 0x18160ddd; // web3.eth.abi.encodeFunctionSignature("totalSupply()") bytes4 private constant _TOKEN_URI = 0xc87b56dd; // web3.eth.abi.encodeFunctionSignature("tokenURI(uint256)") /** * @dev Reads the name property of the provided token. * Either name() or NAME() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token name as a string or an empty string if none of the methods succeeded. */ function readName(address _token) internal view returns (string) { return _readStringWithFallback(_token, _NAME, _NAME_CAPS); } /** * @dev Reads the symbol property of the provided token. * Either symbol() or SYMBOL() method is used. * Both, string and bytes32 types are supported. * @param _token address of the token contract. * @return token symbol as a string or an empty string if none of the methods succeeded. */ function readSymbol(address _token) internal view returns (string) { return _readStringWithFallback(_token, _SYMBOL, _SYMBOL_CAPS); } /** * @dev Reads the decimals property of the provided token. * Either decimals() or DECIMALS() method is used. * @param _token address of the token contract. * @return token decimals or 0 if none of the methods succeeded. */ function readDecimals(address _token) internal view returns (uint256) { return _readIntWithFallback(_token, _DECIMALS, _DECIMALS_CAPS); } function readTotalSupply(address _token) internal view returns (uint256) { return _readIntFunctionThatMightNotExist(_token, _TOTAL_SUPPLY); } function readTokenURI(address _token, uint256 _tokenId) internal view returns (string) { bytes memory encodedParams = abi.encodeWithSelector(_TOKEN_URI, _tokenId); return _dynamicStringMethodCall(_token, encodedParams); } function _readStringWithFallback(address _contract, bytes4 _selector1, bytes4 _selector2) internal view returns (string) { string memory firstResult = _readStringFunctionThatMightNotExist(_contract, _selector1); if (bytes(firstResult).length > 0) { return firstResult; } return _readStringFunctionThatMightNotExist(_contract, _selector2); } function _readIntWithFallback(address _contract, bytes4 _selector1, bytes4 _selector2) internal view returns (uint256) { uint256 firstResult = _readIntFunctionThatMightNotExist(_contract, _selector1); if (firstResult > 0) { return firstResult; } return _readIntFunctionThatMightNotExist(_contract, _selector2); } function _readStringFunctionThatMightNotExist(address _contract, bytes4 _selector) internal view returns (string) { bytes memory encodedParams = abi.encodeWithSelector(_selector); return _dynamicStringMethodCall(_contract, encodedParams); } function _dynamicStringMethodCall(address _contract, bytes encodedParams) internal view returns (string) { uint256 ptr; uint256 size; assembly { let encodedParams_data := add(0x20, encodedParams) let encodedParams_size := mload(encodedParams) ptr := mload(0x40) staticcall(gas, _contract, encodedParams_data, encodedParams_size, ptr, 32) pop mstore(0x40, add(ptr, returndatasize)) switch gt(returndatasize, 32) case 1 { returndatacopy(mload(0x40), 32, 32) // string length size := mload(mload(0x40)) } default { size := returndatasize // 32 or 0 } } string memory res = new string(size); assembly { if gt(returndatasize, 32) { // load as string returndatacopy(add(res, 32), 64, size) jump(exit) } // solhint-disable if gt(returndatasize, 0) { let i := 0 ptr := mload(ptr) // load bytes32 value mstore(add(res, 32), ptr) // save value in result string for { } gt(ptr, 0) { i := add(i, 1) } { // until string is empty ptr := shl(8, ptr) // shift left by one symbol } mstore(res, i) // save result string length } exit: // solhint-enable } return res; } function _readIntFunctionThatMightNotExist(address _contract, bytes4 selector) internal view returns (uint256) { uint256 decimals; // bytes32 nameBytes = _encodeMethodSignature(); assembly { let ptr := mload(0x40) mstore(0x40, add(ptr, 32)) mstore(ptr, selector) if iszero(staticcall(gas, _contract, ptr, 4, ptr, 32)) { mstore(ptr, 0) } decimals := mload(ptr) } return decimals; } } // File: contracts/upgradeable_contracts/multi_amb_erc20_to_erc677/ForeignMultiAMBErc20ToErc677.sol pragma solidity 0.4.24; /** * @title ForeignMultiAMBErc20ToErc677 * @dev Foreign side implementation for multi-erc20-to-erc677 mediator intended to work on top of AMB bridge. * It is designed to be used as an implementation contract of EternalStorageProxy contract. */ contract ForeignMultiAMBErc20ToErc677 is BasicMultiAMBErc20ToErc677 { using SafeERC20 for address; using SafeERC20 for ERC677; /** * @dev Stores the initial parameters of the mediator. * @param _bridgeContract the address of the AMB bridge contract. * @param _mediatorContract the address of the mediator contract on the other network. * @param _dailyLimitMaxPerTxMinPerTxArray array with limit values for the assets to be bridged to the other network. * [ 0 = dailyLimit, 1 = maxPerTx, 2 = minPerTx ] * @param _executionDailyLimitExecutionMaxPerTxArray array with limit values for the assets bridged from the other network. * [ 0 = executionDailyLimit, 1 = executionMaxPerTx ] * @param _requestGasLimit the gas limit for the message execution. * @param _owner address of the owner of the mediator contract. */ function initialize( address _bridgeContract, address _mediatorContract, uint256[3] _dailyLimitMaxPerTxMinPerTxArray, // [ 0 = _dailyLimit, 1 = _maxPerTx, 2 = _minPerTx ] uint256[2] _executionDailyLimitExecutionMaxPerTxArray, // [ 0 = _executionDailyLimit, 1 = _executionMaxPerTx ] uint256 _requestGasLimit, address _owner ) external onlyRelevantSender returns (bool) { require(!isInitialized()); _setBridgeContract(_bridgeContract); _setMediatorContractOnOtherSide(_mediatorContract); _setLimits(address(0), _dailyLimitMaxPerTxMinPerTxArray); _setExecutionLimits(address(0), _executionDailyLimitExecutionMaxPerTxArray); _setRequestGasLimit(_requestGasLimit); _setOwner(_owner); setInitialize(); return isInitialized(); } /** * @dev Executes action on the request to withdraw tokens relayed from the other network * @param _token address of the token contract * @param _recipient address of tokens receiver * @param _value amount of bridged tokens */ function executeActionOnBridgedTokens(address _token, address _recipient, uint256 _value) internal { bytes32 _messageId = messageId(); _token.safeTransfer(_recipient, _value); _setMediatorBalance(_token, mediatorBalance(_token).sub(_value)); emit TokensBridged(_token, _recipient, _value, _messageId); } /** * @dev ERC677 transfer callback function. * @param _from address of tokens sender. * @param _value amount of transferred tokens. * @param _data additional transfer data, can be used for passing alternative receiver address. */ function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { if (!lock()) { ERC677 token = ERC677(msg.sender); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); } return true; } /** * @dev Handles the bridged tokens. Checks that the value is inside the execution limits and invokes the method * to execute the Mint or Unlock accordingly. * @param _token bridged ERC20 token. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function handleBridgedTokens(ERC677 _token, address _recipient, uint256 _value) external onlyMediator { require(isTokenRegistered(_token)); _handleBridgedTokens(_token, _recipient, _value); } /** * @dev Validates that the token amount is inside the limits, calls transferFrom to transfer the tokens to the contract * and invokes the method to burn/lock the tokens and unlock/mint the tokens on the other network. * The user should first call Approve method of the ERC677 token. * @param token bridge token contract address. * @param _receiver address that will receive the native tokens on the other network. * @param _value amount of tokens to be transferred to the other network. */ function _relayTokens(ERC677 token, address _receiver, uint256 _value) internal { // This lock is to prevent calling passMessage twice if a ERC677 token is used. // When transferFrom is called, after the transfer, the ERC677 token will call onTokenTransfer from this contract // which will call passMessage. require(!lock()); uint256 balanceBefore = token.balanceOf(address(this)); setLock(true); token.transferFrom(msg.sender, address(this), _value); setLock(false); uint256 balanceDiff = token.balanceOf(address(this)).sub(balanceBefore); require(balanceDiff <= _value); bridgeSpecificActionsOnTokenTransfer(token, msg.sender, balanceDiff, abi.encodePacked(_receiver)); } /** * @dev Executes action on deposit of bridged tokens * @param _token address of the token contract * @param _from address of tokens sender * @param _value requsted amount of bridged tokens * @param _data alternative receiver, if specified */ function bridgeSpecificActionsOnTokenTransfer(ERC677 _token, address _from, uint256 _value, bytes _data) internal { if (lock()) return; require(isTokenAllowed(_token)); bool isKnownToken = isTokenRegistered(_token); if (!isKnownToken) { string memory name = TokenReader.readName(_token); string memory symbol = TokenReader.readSymbol(_token); uint8 decimals = uint8(TokenReader.readDecimals(_token)); require(bytes(name).length > 0 || bytes(symbol).length > 0); _initializeTokenBridgeLimits(_token, decimals); } require(withinLimit(_token, _value)); addTotalSpentPerDay(_token, getCurrentDay(), _value); bytes memory data; address receiver = chooseReceiver(_from, _data); if (isKnownToken) { data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, receiver, _value); } else { data = abi.encodeWithSelector( HomeMultiAMBErc20ToErc677(this).deployAndHandleBridgedTokens.selector, _token, name, symbol, decimals, receiver, _value ); } _setMediatorBalance(_token, mediatorBalance(_token).add(_value)); bytes32 _messageId = bridgeContract().requireToPassMessage( mediatorContractOnOtherSide(), data, requestGasLimit() ); setMessageToken(_messageId, _token); setMessageValue(_messageId, _value); setMessageRecipient(_messageId, _from); if (!isKnownToken) { _setTokenRegistrationMessageId(_token, _messageId); } emit TokensBridgingInitiated(_token, _from, _value, _messageId); } /** * @dev Handles the request to fix transferred assets which bridged message execution failed on the other network. * It uses the information stored by passMessage method when the assets were initially transferred * @param _messageId id of the message which execution failed on the other network. */ function fixFailedMessage(bytes32 _messageId) public { super.fixFailedMessage(_messageId); address token = messageToken(_messageId); if (_messageId == tokenRegistrationMessageId(token)) { delete uintStorage[keccak256(abi.encodePacked("dailyLimit", token))]; delete uintStorage[keccak256(abi.encodePacked("maxPerTx", token))]; delete uintStorage[keccak256(abi.encodePacked("minPerTx", token))]; delete uintStorage[keccak256(abi.encodePacked("executionDailyLimit", token))]; delete uintStorage[keccak256(abi.encodePacked("executionMaxPerTx", token))]; _setTokenRegistrationMessageId(token, bytes32(0)); } } /** * @dev Unlock back the amount of tokens that were bridged to the other network but failed. * @param _token address that bridged token contract. * @param _recipient address that will receive the tokens. * @param _value amount of tokens to be received. */ function executeActionOnFixedTokens(address _token, address _recipient, uint256 _value) internal { _setMediatorBalance(_token, mediatorBalance(_token).sub(_value)); _token.safeTransfer(_recipient, _value); } /** * @dev Allows to send to the other network the amount of locked tokens that can be forced into the contract * without the invocation of the required methods. (e. g. regular transfer without a call to onTokenTransfer) * @param _token address of the token contract. * @param _receiver the address that will receive the tokens on the other network. */ function fixMediatorBalance(address _token, address _receiver) external onlyIfUpgradeabilityOwner validAddress(_receiver) { require(isTokenRegistered(_token)); uint256 balance = ERC677(_token).balanceOf(address(this)); uint256 expectedBalance = mediatorBalance(_token); require(balance > expectedBalance); uint256 diff = balance - expectedBalance; uint256 available = maxAvailablePerTx(_token); require(available > 0); if (diff > available) { diff = available; } addTotalSpentPerDay(_token, getCurrentDay(), diff); _setMediatorBalance(_token, expectedBalance.add(diff)); bytes memory data = abi.encodeWithSelector(this.handleBridgedTokens.selector, _token, _receiver, diff); bytes32 _messageId = bridgeContract().requireToPassMessage( mediatorContractOnOtherSide(), data, requestGasLimit() ); setMessageToken(_messageId, _token); setMessageValue(_messageId, diff); setMessageRecipient(_messageId, _receiver); } /** * @dev Tells the expected token balance of the contract. * @param _token address of token contract. * @return the current tracked token balance of the contract. */ function mediatorBalance(address _token) public view returns (uint256) { return uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))]; } /** * @dev Returns message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @return message id of the send message. */ function tokenRegistrationMessageId(address _token) public view returns (bytes32) { return bytes32(uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))]); } /** * @dev Updates expected token balance of the contract. * @param _token address of token contract. * @param _balance the new token balance of the contract. */ function _setMediatorBalance(address _token, uint256 _balance) internal { uintStorage[keccak256(abi.encodePacked("mediatorBalance", _token))] = _balance; } /** * @dev Updates message id where specified token was first seen and deploy on the other side was requested. * @param _token address of token contract. * @param _messageId message id of the send message. */ function _setTokenRegistrationMessageId(address _token, bytes32 _messageId) internal { uintStorage[keccak256(abi.encodePacked("tokenRegistrationMessageId", _token))] = uint256(_messageId); } function isTokenAllowed(address _token) public view returns (bool) { return boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))]; } function allowToken(address _token) external onlyOwner { _allowToken(_token); } event TokenAllowed(address indexed token); function _allowToken(address _token) internal { require(!isTokenAllowed(_token)); require(AddressUtils.isContract(_token)); boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))] = true; emit TokenAllowed(_token); } function disallowToken(address _token) external onlyOwner { _disallowToken(_token); } event TokenDisallowed(address indexed token); function _disallowToken(address _token) internal { require(isTokenAllowed(_token)); require(AddressUtils.isContract(_token)); boolStorage[keccak256(abi.encodePacked("tokenAllowed", _token))] = false; emit TokenDisallowed(_token); } }
* @dev ERC677 transfer callback function. @param _from address of tokens sender. @param _value amount of transferred tokens. @param _data additional transfer data, can be used for passing alternative receiver address./ if onTokenTransfer is called as a part of call to _relayTokens, this callback does nothing if msg.sender if not a valid token contract, this check will fail, since limits are zeros so the following check is not needed require(isTokenRegistered(token));
function onTokenTransfer(address _from, uint256 _value, bytes _data) public returns (bool) { if (!lock()) { ERC677 token = ERC677(msg.sender); require(withinLimit(token, _value)); addTotalSpentPerDay(token, getCurrentDay(), _value); bridgeSpecificActionsOnTokenTransfer(token, _from, _value, _data); } return true; }
1,401,987
[ 1, 654, 39, 26, 4700, 7412, 1348, 445, 18, 225, 389, 2080, 1758, 434, 2430, 5793, 18, 225, 389, 1132, 3844, 434, 906, 4193, 2430, 18, 225, 389, 892, 3312, 7412, 501, 16, 848, 506, 1399, 364, 9588, 10355, 5971, 1758, 18, 19, 309, 603, 1345, 5912, 353, 2566, 487, 279, 1087, 434, 745, 358, 389, 2878, 528, 5157, 16, 333, 1348, 1552, 5083, 309, 1234, 18, 15330, 309, 486, 279, 923, 1147, 6835, 16, 333, 866, 903, 2321, 16, 3241, 8181, 854, 4922, 1427, 326, 3751, 866, 353, 486, 3577, 2583, 12, 291, 1345, 10868, 12, 2316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 603, 1345, 5912, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 16, 1731, 389, 892, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 739, 10756, 288, 203, 5411, 4232, 39, 26, 4700, 1147, 273, 4232, 39, 26, 4700, 12, 3576, 18, 15330, 1769, 203, 5411, 2583, 12, 25850, 3039, 12, 2316, 16, 389, 1132, 10019, 203, 5411, 527, 5269, 3389, 319, 2173, 4245, 12, 2316, 16, 5175, 4245, 9334, 389, 1132, 1769, 203, 5411, 10105, 9969, 6100, 1398, 1345, 5912, 12, 2316, 16, 389, 2080, 16, 389, 1132, 16, 389, 892, 1769, 203, 3639, 289, 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, -100 ]
pragma solidity ^0.4.24; import "./BimodalProxy.sol"; import "./ERC20.sol"; import "./BimodalLib.sol"; import "./MerkleVerifier.sol"; import "./ChallengeLib.sol"; import "./SafeMath/SafeMathLib256.sol"; contract ChallengeProxy is BimodalProxy { using SafeMathLib256 for uint256; modifier onlyWithFairReimbursement() { uint256 gas = gasleft(); _; gas = gas.sub(gasleft()); require( msg.value >= gas.mul(ledger.MIN_CHALLENGE_GAS_COST) && msg.value >= gas.mul(tx.gasprice), 'r'); ledger.operator.transfer(msg.value); } modifier onlyWithSkewedReimbursement(uint256 extra) { uint256 gas = gasleft(); _; gas = gas.sub(gasleft()); require( msg.value >= gas.add(extra).mul(ledger.MIN_CHALLENGE_GAS_COST) && msg.value >= gas.add(extra).mul(tx.gasprice), 'r'); ledger.operator.transfer(msg.value); } // ========================================================================= function verifyProofOfExclusiveAccountBalanceAllotment( ERC20 token, address holder, bytes32[2] activeStateChecksum_passiveTransfersRoot, // solhint-disable func-param-name-mixedcase uint64 trail, uint256[3] eonPassiveMark, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, uint256[2] LR // solhint-disable-line func-param-name-mixedcase ) public view returns (bool) { return ChallengeLib.verifyProofOfExclusiveAccountBalanceAllotment( ledger, token, holder, activeStateChecksum_passiveTransfersRoot, trail, eonPassiveMark, allotmentChain, membershipChain, values, LR ); } function verifyProofOfActiveStateUpdateAgreement( ERC20 token, address holder, uint64 trail, uint256 eon, bytes32 txSetRoot, uint256[2] deltas, address attester, bytes32 r, bytes32 s, uint8 v ) public view returns (bytes32 checksum) { return ChallengeLib.verifyProofOfActiveStateUpdateAgreement( token, holder, trail, eon, txSetRoot, deltas, attester, r, s, v ); } function verifyWithdrawalAuthorization( ERC20 token, address holder, uint256 expiry, uint256 amount, address attester, bytes32 r, bytes32 s, uint8 v ) public view returns (bool) { return ChallengeLib.verifyWithdrawalAuthorization( token, holder, expiry, amount, attester, r, s, v ); } function verifyProofOfExclusiveBalanceAllotment( uint64 allotmentTrail, uint64 membershipTrail, bytes32 node, bytes32 root, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] value, uint256[2] LR // solhint-disable-line func-param-name-mixedcase ) public pure returns (uint256) { return MerkleVerifier.verifyProofOfExclusiveBalanceAllotment( allotmentTrail, membershipTrail, node, root, allotmentChain, membershipChain, value, LR ); } function verifyProofOfMembership( uint256 trail, bytes32[] chain, bytes32 node, bytes32 merkleRoot ) public pure returns (bool) { return MerkleVerifier.verifyProofOfMembership( trail, chain, node, merkleRoot ); } function verifyProofOfPassiveDelivery( uint64 allotmentTrail, bytes32 node, bytes32 root, bytes32[] chainValues, uint256[2] LR // solhint-disable-line func-param-name-mixedcase ) public pure returns (uint256) { return MerkleVerifier.verifyProofOfPassiveDelivery( allotmentTrail, node, root, chainValues, LR ); } // ========================================================================= function challengeStateUpdateWithProofOfExclusiveBalanceAllotment( ERC20 token, bytes32[2] checksums, uint64 trail, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] value, uint256[2][3] lrDeltasPassiveMark, bytes32[3] rsTxSetRoot, uint8 v ) public payable onlyWithFairReimbursement() { ChallengeLib.challengeStateUpdateWithProofOfExclusiveBalanceAllotment( ledger, token, checksums, trail, allotmentChain, membershipChain, value, lrDeltasPassiveMark, rsTxSetRoot, v ); } function challengeStateUpdateWithProofOfActiveStateUpdateAgreement( ERC20 token, bytes32 txSetRoot, uint64 trail, uint256[2] deltas, bytes32 r, bytes32 s, uint8 v ) public payable onlyWithSkewedReimbursement(25) /* TODO calculate exact addition */ { ChallengeLib.challengeStateUpdateWithProofOfActiveStateUpdateAgreement( ledger, token, txSetRoot, trail, deltas, r, s, v ); } function answerStateUpdateChallenge( ERC20 token, address issuer, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, uint256[2][3] lrDeltasPassiveMark, // [ [L, R], Deltas ] bytes32[6] rSrStxSetRootChecksum, uint8[2] v ) public { ChallengeLib.answerStateUpdateChallenge( ledger, token, issuer, allotmentChain, membershipChain, values, lrDeltasPassiveMark, rSrStxSetRootChecksum, v ); } // ========================================================================= function challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement( ERC20 token, address[2] SR, // solhint-disable-line func-param-name-mixedcase uint256[2] nonceAmount, uint64[3] trails, bytes32[] chain, uint256[2] deltas, bytes32[3] rsTxSetRoot, uint8 v ) public payable onlyWithFairReimbursement() { ChallengeLib.challengeTransferDeliveryWithProofOfActiveStateUpdateAgreement( ledger, token, SR, nonceAmount, trails, chain, deltas, rsTxSetRoot, v ); } function answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement( ERC20 token, address[2] SR, // solhint-disable-line func-param-name-mixedcase uint64 transferMembershipTrail, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, uint256[2][3] lrDeltasPassiveMark, bytes32[2] txSetRootChecksum, bytes32[] txChain ) public { ChallengeLib.answerTransferDeliveryChallengeWithProofOfActiveStateUpdateAgreement( ledger, token, SR, transferMembershipTrail, allotmentChain, membershipChain, values, lrDeltasPassiveMark, txSetRootChecksum, txChain ); } // ========================================================================= function challengeTransferDeliveryWithProofOfPassiveStateUpdate( ERC20 token, address[2] SR, // solhint-disable-line func-param-name-mixedcase bytes32[2] txSetRootChecksum, uint64[3] senderTransferRecipientTrails, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, uint256[2][4] lrDeltasPassiveMarkDummyAmount, bytes32[] transferMembershipChain ) public payable onlyWithFairReimbursement() { ChallengeLib.challengeTransferDeliveryWithProofOfPassiveStateUpdate( ledger, token, SR, txSetRootChecksum, senderTransferRecipientTrails, allotmentChain, membershipChain, values, lrDeltasPassiveMarkDummyAmount, transferMembershipChain ); } function answerTransferDeliveryChallengeWithProofOfPassiveStateUpdate( ERC20 token, address[2] SR, // solhint-disable-line func-param-name-mixedcase uint64 transferMembershipTrail, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, uint256[2][3] lrPassiveMarkPositionNonce, bytes32[2] checksums, bytes32[] txChainValues ) public { ChallengeLib.answerTransferDeliveryChallengeWithProofOfPassiveStateUpdate( ledger, token, SR, transferMembershipTrail, allotmentChain, membershipChain, values, lrPassiveMarkPositionNonce, checksums, txChainValues ); } // ========================================================================= function challengeSwapEnactmentWithProofOfActiveStateUpdateAgreement( ERC20[2] tokens, uint64[3] senderTransferRecipientTrails, bytes32[] allotmentChain, bytes32[] membershipChain, bytes32[] txChain, uint256[] values, uint256[2][3] lrDeltasPassiveMark, uint256[4] sellBuyBalanceNonce, bytes32[3] txSetRootChecksumDummy ) public payable onlyWithFairReimbursement() { ChallengeLib.challengeSwapEnactmentWithProofOfActiveStateUpdateAgreement( ledger, tokens, senderTransferRecipientTrails, allotmentChain, membershipChain, txChain, values, lrDeltasPassiveMark, sellBuyBalanceNonce, txSetRootChecksumDummy ); } function answerSwapChallengeWithProofOfExclusiveBalanceAllotment( ERC20[2] tokens, address issuer, uint64 transferMembershipTrail, bytes32[] allotmentChain, bytes32[] membershipChain, bytes32[] txChain, uint256[] values, uint256[2][3] lrDeltasPassiveMark, uint256 balance, bytes32[3] txSetRootChecksumDummy ) public { ChallengeLib.answerSwapChallengeWithProofOfExclusiveBalanceAllotment( ledger, tokens, issuer, transferMembershipTrail, allotmentChain, membershipChain, txChain, values, lrDeltasPassiveMark, balance, txSetRootChecksumDummy ); } // ========================================================================= function slashWithdrawalWithProofOfMinimumAvailableBalance( ERC20 token, address withdrawer, uint256[2] markerEonAvailable, bytes32[2] rs, uint8 v ) public returns (uint256[2]) { return ChallengeLib.slashWithdrawalWithProofOfMinimumAvailableBalance( ledger, token, withdrawer, markerEonAvailable, rs, v ); } }
=========================================================================
function verifyProofOfExclusiveAccountBalanceAllotment( ERC20 token, address holder, uint64 trail, uint256[3] eonPassiveMark, bytes32[] allotmentChain, bytes32[] membershipChain, uint256[] values, ) public view returns (bool) { return ChallengeLib.verifyProofOfExclusiveAccountBalanceAllotment( ledger, token, holder, activeStateChecksum_passiveTransfersRoot, trail, eonPassiveMark, allotmentChain, membershipChain, values, LR ); }
13,031,313
[ 1, 22121, 33, 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, 0 ]
[ 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, 0 ]
[ 1, 225, 445, 3929, 20439, 951, 17075, 3032, 13937, 1595, 352, 475, 12, 203, 565, 4232, 39, 3462, 1147, 16, 203, 565, 1758, 10438, 16, 203, 565, 2254, 1105, 15569, 16, 203, 565, 2254, 5034, 63, 23, 65, 425, 265, 6433, 688, 3882, 16, 203, 565, 1731, 1578, 8526, 777, 352, 475, 3893, 16, 203, 565, 1731, 1578, 8526, 12459, 3893, 16, 203, 565, 2254, 5034, 8526, 924, 16, 203, 225, 262, 203, 565, 1071, 203, 565, 1476, 203, 565, 1135, 261, 6430, 13, 203, 225, 288, 203, 565, 327, 1680, 8525, 5664, 18, 8705, 20439, 951, 17075, 3032, 13937, 1595, 352, 475, 12, 203, 1377, 16160, 16, 203, 1377, 1147, 16, 203, 1377, 10438, 16, 203, 1377, 2695, 1119, 10723, 67, 5466, 688, 1429, 18881, 2375, 16, 203, 1377, 15569, 16, 203, 1377, 425, 265, 6433, 688, 3882, 16, 203, 1377, 777, 352, 475, 3893, 16, 203, 1377, 12459, 3893, 16, 203, 1377, 924, 16, 203, 1377, 511, 54, 203, 565, 11272, 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 ]
./full_match/80001/0x3459342748b01cC5b5C9Cf57166F8dd4ABD8f6bD/sources/project_/contracts/Product020802V01.sol
Coverage[] memory selectedCoverages else if (keccak256(abi.encodePacked((endorsmentParams[index].key))) == "selectedCoverages") { allPolicies[onChainPolicyId].selectedCoverages = selectedCoverages; }
function endorsePolicyArray( string memory onChainPolicyId, EndorsementParamsStruct[] memory endorsmentParams, uint256 endorsementType ) external onlyPartnerOrWakam(allPolicies[onChainPolicyId].partnershipCodeHash) { for (uint256 index = 0; index < endorsmentParams.length; index++) { if (keccak256(abi.encodePacked((endorsmentParams[index].key))) == "coverageStartDate") { uint256 coverageStartDate = computeCoverageStartDate( endorsmentParams[index].uintValue, allPolicies[onChainPolicyId].subscriptionDate ); allPolicies[onChainPolicyId].coverageStartDate = coverageStartDate; allPolicies[onChainPolicyId].expirationDate = coverageStartDate.addYears(1, TIME_ZONE_OFFSET); allPolicies[onChainPolicyId].riskType = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].termination = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].renewalType = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].package = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].selectedOptions = endorsmentParams[index].stringValueArray; } else if (keccak256(abi.encodePacked((endorsmentParams[index].key))) == "split") { allPolicies[onChainPolicyId].split = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].isOfLegalAge = endorsmentParams[index].uintValue == 1 ? true : false; allPolicies[onChainPolicyId].commonSensitiveData = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].claimsAdminSensitiveData = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].policiesAdminSensitiveData = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].distributorSensitiveData = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].insurerSensitiveData = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].exposure.vehicleType = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].exposure.brand = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].exposure.model = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].exposure.purchaseDate = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].exposure.purchasePrice = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].exposure.purchaseCurrency = endorsmentParams[index].stringValue; allPolicies[onChainPolicyId].exposure.usage = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].exposure.householdSize = endorsmentParams[index].uintValue; allPolicies[onChainPolicyId].exposure.maxSpeed = endorsmentParams[index].uintValue; } } allPolicies[onChainPolicyId].operationType = endorsementType; allPolicies[onChainPolicyId].operationEffectiveDate = block.timestamp; }
5,676,542
[ 1, 9739, 8526, 3778, 3170, 8084, 1023, 469, 309, 261, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 409, 1383, 475, 1370, 63, 1615, 8009, 856, 20349, 422, 315, 8109, 8084, 1023, 7923, 288, 377, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 8109, 8084, 1023, 273, 3170, 8084, 1023, 31, 289, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 679, 23035, 2582, 1076, 12, 203, 3639, 533, 3778, 603, 3893, 2582, 548, 16, 203, 3639, 4403, 23035, 475, 1370, 3823, 8526, 3778, 679, 1383, 475, 1370, 16, 203, 3639, 2254, 5034, 679, 23035, 475, 559, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 1988, 1224, 1162, 59, 581, 301, 12, 454, 8825, 63, 265, 3893, 2582, 548, 8009, 2680, 9646, 5310, 1085, 2310, 13, 203, 565, 288, 203, 3639, 364, 261, 11890, 5034, 770, 273, 374, 31, 770, 411, 679, 1383, 475, 1370, 18, 2469, 31, 770, 27245, 288, 203, 5411, 309, 261, 79, 24410, 581, 5034, 12, 21457, 18, 3015, 4420, 329, 12443, 409, 1383, 475, 1370, 63, 1615, 8009, 856, 20349, 422, 315, 16356, 22635, 7923, 288, 203, 7734, 2254, 5034, 11196, 22635, 273, 3671, 9739, 22635, 12, 203, 10792, 679, 1383, 475, 1370, 63, 1615, 8009, 11890, 620, 16, 203, 10792, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 11185, 1626, 203, 7734, 11272, 203, 7734, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 16356, 22635, 273, 11196, 22635, 31, 203, 7734, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 19519, 1626, 273, 11196, 22635, 18, 1289, 21945, 12, 21, 16, 8721, 67, 20725, 67, 11271, 1769, 203, 7734, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 86, 10175, 559, 273, 679, 1383, 475, 1370, 63, 1615, 8009, 11890, 620, 31, 203, 7734, 777, 8825, 63, 265, 3893, 2582, 548, 8009, 9505, 367, 273, 679, 1383, 475, 1370, 63, 1615, 8009, 11890, 620, 31, 203, 7734, 777, 2 ]
// File: contracts\lib\TransferHelper.sol // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.6; // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferETH(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: ETH_TRANSFER_FAILED'); } } // File: contracts\interface\INestMining.sol /// @dev This interface defines the mining methods for nest interface INestMining { /// @dev Post event /// @param tokenAddress The address of TOKEN contract /// @param miner Address of miner /// @param index Index of the price sheet /// @param ethNum The numbers of ethers to post sheets event Post(address tokenAddress, address miner, uint index, uint ethNum, uint price); /* ========== Structures ========== */ /// @dev Nest mining configuration structure struct Config { // Eth number of each post. 30 // We can stop post and taking orders by set postEthUnit to 0 (closing and withdraw are not affected) uint32 postEthUnit; // Post fee(0.0001eth,DIMI_ETHER). 1000 uint16 postFeeUnit; // Proportion of miners digging(10000 based). 8000 uint16 minerNestReward; // The proportion of token dug by miners is only valid for the token created in version 3.0 // (10000 based). 9500 uint16 minerNTokenReward; // When the circulation of ntoken exceeds this threshold, post() is prohibited(Unit: 10000 ether). 500 uint32 doublePostThreshold; // The limit of ntoken mined blocks. 100 uint16 ntokenMinedBlockLimit; // -- Public configuration // The number of times the sheet assets have doubled. 4 uint8 maxBiteNestedLevel; // Price effective block interval. 20 uint16 priceEffectSpan; // The amount of nest to pledge for each post(Unit: 1000). 100 uint16 pledgeNest; } /// @dev PriceSheetView structure struct PriceSheetView { // Index of the price sheeet uint32 index; // Address of miner address miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // The token price. (1eth equivalent to (price) token) uint152 price; } /* ========== Configuration ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) external; /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== Mining ========== */ /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) external payable; /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2(address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth) external payable; /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth(address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth) external payable; /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) external; /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) external; /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2(address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices) external; /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) external; /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) external; /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list(address tokenAddress, uint offset, uint count, uint order) external view returns (PriceSheetView[] memory); /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) external view returns (uint); /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks(address tokenAddress, uint index) external view returns (uint minedBlocks, uint totalShares); /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) external; /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) external view returns (uint); /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) external view returns (address); /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) external view returns (uint); /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() external view returns (uint); } // File: contracts\interface\INestQuery.sol /// @dev This interface defines the methods for price query interface INestQuery { /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ); /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) external view returns (uint blockNumber, uint price); /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) external view returns (uint blockNumber, uint price); /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) external view returns (uint[] memory); /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ); /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ); /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ); } // File: contracts\interface\INTokenController.sol ///@dev This interface defines the methods for ntoken management interface INTokenController { /// @notice when the auction of a token gets started /// @param tokenAddress The address of the (ERC20) token /// @param ntokenAddress The address of the ntoken w.r.t. token for incentives /// @param owner The address of miner who opened the oracle event NTokenOpened(address tokenAddress, address ntokenAddress, address owner); /// @notice ntoken disable event /// @param tokenAddress token address event NTokenDisabled(address tokenAddress); /// @notice ntoken enable event /// @param tokenAddress token address event NTokenEnabled(address tokenAddress); /// @dev ntoken configuration structure struct Config { // The number of nest needed to pay for opening ntoken. 10000 ether uint96 openFeeNestAmount; // ntoken management is enabled. 0: not enabled, 1: enabled uint8 state; } /// @dev A struct for an ntoken struct NTokenTag { // ntoken address address ntokenAddress; // How much nest has paid for open this ntoken uint96 nestFee; // token address address tokenAddress; // Index for this ntoken uint40 index; // Create time uint48 startTime; // State of this ntoken. 0: disabled; 1 normal uint8 state; } /* ========== Governance ========== */ /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set the token mapping /// @param tokenAddress Destination token address /// @param ntokenAddress Destination ntoken address /// @param state status for this map function setNTokenMapping(address tokenAddress, address ntokenAddress, uint state) external; /// @dev Get token address from ntoken address /// @param ntokenAddress Destination ntoken address /// @return token address function getTokenAddress(address ntokenAddress) external view returns (address); /// @dev Get ntoken address from token address /// @param tokenAddress Destination token address /// @return ntoken address function getNTokenAddress(address tokenAddress) external view returns (address); /* ========== ntoken management ========== */ /// @dev Bad tokens should be banned function disable(address tokenAddress) external; /// @dev enable ntoken function enable(address tokenAddress) external; /// @notice Open a NToken for a token by anyone (contracts aren't allowed) /// @dev Create and map the (Token, NToken) pair in NestPool /// @param tokenAddress The address of token contract function open(address tokenAddress) external; /* ========== VIEWS ========== */ /// @dev Get ntoken information /// @param tokenAddress Destination token address /// @return ntoken information function getNTokenTag(address tokenAddress) external view returns (NTokenTag memory); /// @dev Get opened ntoken count /// @return ntoken count function getNTokenCount() external view returns (uint); /// @dev List ntoken information by page /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return ntoken information by page function list(uint offset, uint count, uint order) external view returns (NTokenTag[] memory); } // File: contracts\interface\INestLedger.sol /// @dev This interface defines the nest ledger methods interface INestLedger { /// @dev Application Flag Changed event /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization event ApplicationChanged(address addr, uint flag); /// @dev Configuration structure of nest ledger contract struct Config { // nest reward scale(10000 based). 2000 uint16 nestRewardScale; // // ntoken reward scale(10000 based). 8000 // uint16 ntokenRewardScale; } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) external; /// @dev Get configuration /// @return Configuration object function getConfig() external view returns (Config memory); /// @dev Set DAO application /// @param addr DAO application contract address /// @param flag Authorization flag, 1 means authorization, 0 means cancel authorization function setApplication(address addr, uint flag) external; /// @dev Check DAO application flag /// @param addr DAO application contract address /// @return Authorization flag, 1 means authorization, 0 means cancel authorization function checkApplication(address addr) external view returns (uint); /// @dev Carve reward /// @param ntokenAddress Destination ntoken address function carveETHReward(address ntokenAddress) external payable; /// @dev Add reward /// @param ntokenAddress Destination ntoken address function addETHReward(address ntokenAddress) external payable; /// @dev The function returns eth rewards of specified ntoken /// @param ntokenAddress The ntoken address function totalETHRewards(address ntokenAddress) external view returns (uint); /// @dev Pay /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to pay with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function pay(address ntokenAddress, address tokenAddress, address to, uint value) external; /// @dev Settlement /// @param ntokenAddress Destination ntoken address. Indicates which ntoken to settle with /// @param tokenAddress Token address of receiving funds (0 means ETH) /// @param to Address to receive /// @param value Amount to receive function settle(address ntokenAddress, address tokenAddress, address to, uint value) external payable; } // File: contracts\interface\INToken.sol /// @dev ntoken interface interface INToken { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); /// @dev Mint /// @param value The amount of NToken to add function increaseTotal(uint256 value) external; /// @notice The view of variables about minting /// @dev The naming follows Nestv3.0 /// @return createBlock The block number where the contract was created /// @return recentlyUsedBlock The block number where the last minting went function checkBlockInfo() external view returns(uint256 createBlock, uint256 recentlyUsedBlock); /// @dev The ABI keeps unchanged with old NTokens, so as to support token-and-ntoken-mining /// @return The address of bidder function checkBidder() external view returns(address); /// @notice The view of totalSupply /// @return The total supply of ntoken function totalSupply() external view returns (uint256); /// @dev The view of balances /// @param owner The address of an account /// @return The balance of the account function balanceOf(address owner) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); } // File: contracts\interface\INestMapping.sol /// @dev The interface defines methods for nest builtin contract address mapping interface INestMapping { /// @dev Set the built-in contract address of the system /// @param nestTokenAddress Address of nest token contract /// @param nestNodeAddress Address of nest node contract /// @param nestLedgerAddress INestLedger implementation contract address /// @param nestMiningAddress INestMining implementation contract address for nest /// @param ntokenMiningAddress INestMining implementation contract address for ntoken /// @param nestPriceFacadeAddress INestPriceFacade implementation contract address /// @param nestVoteAddress INestVote implementation contract address /// @param nestQueryAddress INestQuery implementation contract address /// @param nnIncomeAddress NNIncome contract address /// @param nTokenControllerAddress INTokenController implementation contract address function setBuiltinAddress( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ) external; /// @dev Get the built-in contract address of the system /// @return nestTokenAddress Address of nest token contract /// @return nestNodeAddress Address of nest node contract /// @return nestLedgerAddress INestLedger implementation contract address /// @return nestMiningAddress INestMining implementation contract address for nest /// @return ntokenMiningAddress INestMining implementation contract address for ntoken /// @return nestPriceFacadeAddress INestPriceFacade implementation contract address /// @return nestVoteAddress INestVote implementation contract address /// @return nestQueryAddress INestQuery implementation contract address /// @return nnIncomeAddress NNIncome contract address /// @return nTokenControllerAddress INTokenController implementation contract address function getBuiltinAddress() external view returns ( address nestTokenAddress, address nestNodeAddress, address nestLedgerAddress, address nestMiningAddress, address ntokenMiningAddress, address nestPriceFacadeAddress, address nestVoteAddress, address nestQueryAddress, address nnIncomeAddress, address nTokenControllerAddress ); /// @dev Get address of nest token contract /// @return Address of nest token contract function getNestTokenAddress() external view returns (address); /// @dev Get address of nest node contract /// @return Address of nest node contract function getNestNodeAddress() external view returns (address); /// @dev Get INestLedger implementation contract address /// @return INestLedger implementation contract address function getNestLedgerAddress() external view returns (address); /// @dev Get INestMining implementation contract address for nest /// @return INestMining implementation contract address for nest function getNestMiningAddress() external view returns (address); /// @dev Get INestMining implementation contract address for ntoken /// @return INestMining implementation contract address for ntoken function getNTokenMiningAddress() external view returns (address); /// @dev Get INestPriceFacade implementation contract address /// @return INestPriceFacade implementation contract address function getNestPriceFacadeAddress() external view returns (address); /// @dev Get INestVote implementation contract address /// @return INestVote implementation contract address function getNestVoteAddress() external view returns (address); /// @dev Get INestQuery implementation contract address /// @return INestQuery implementation contract address function getNestQueryAddress() external view returns (address); /// @dev Get NNIncome contract address /// @return NNIncome contract address function getNnIncomeAddress() external view returns (address); /// @dev Get INTokenController implementation contract address /// @return INTokenController implementation contract address function getNTokenControllerAddress() external view returns (address); /// @dev Registered address. The address registered here is the address accepted by nest system /// @param key The key /// @param addr Destination address. 0 means to delete the registration information function registerAddress(string memory key, address addr) external; /// @dev Get registered address /// @param key The key /// @return Destination address. 0 means empty function checkAddress(string memory key) external view returns (address); } // File: contracts\interface\INestGovernance.sol /// @dev This interface defines the governance methods interface INestGovernance is INestMapping { /// @dev Set governance authority /// @param addr Destination address /// @param flag Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function setGovernance(address addr, uint flag) external; /// @dev Get governance rights /// @param addr Destination address /// @return Weight. 0 means to delete the governance permission of the target address. Weight is not /// implemented in the current system, only the difference between authorized and unauthorized. /// Here, a uint96 is used to represent the weight, which is only reserved for expansion function getGovernance(address addr) external view returns (uint); /// @dev Check whether the target address has governance rights for the given target /// @param addr Destination address /// @param flag Permission weight. The permission of the target address must be greater than this weight to pass the check /// @return True indicates permission function checkGovernance(address addr, uint flag) external view returns (bool); } // File: contracts\NestBase.sol /// @dev Base contract of nest contract NestBase { // Address of nest token contract address constant NEST_TOKEN_ADDRESS = 0x04abEdA201850aC0124161F037Efd70c74ddC74C; // Genesis block number of nest // NEST token contract is created at block height 6913517. However, because the mining algorithm of nest1.0 // is different from that at present, a new mining algorithm is adopted from nest2.0. The new algorithm // includes the attenuation logic according to the block. Therefore, it is necessary to trace the block // where the nest begins to decay. According to the circulation when nest2.0 is online, the new mining // algorithm is used to deduce and convert the nest, and the new algorithm is used to mine the nest2.0 // on-line flow, the actual block is 5120000 uint constant NEST_GENESIS_BLOCK = 5120000; /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) virtual public { require(_governance == address(0), 'NEST:!initialize'); _governance = nestGovernanceAddress; } /// @dev INestGovernance implementation contract address address public _governance; /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) virtual public { address governance = _governance; require(governance == msg.sender || INestGovernance(governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _governance = nestGovernanceAddress; } /// @dev Migrate funds from current contract to NestLedger /// @param tokenAddress Destination token address.(0 means eth) /// @param value Migrate amount function migrate(address tokenAddress, uint value) external onlyGovernance { address to = INestGovernance(_governance).getNestLedgerAddress(); if (tokenAddress == address(0)) { INestLedger(to).addETHReward { value: value } (address(0)); } else { TransferHelper.safeTransfer(tokenAddress, to, value); } } //---------modifier------------ modifier onlyGovernance() { require(INestGovernance(_governance).checkGovernance(msg.sender, 0), "NEST:!gov"); _; } modifier noContract() { require(msg.sender == tx.origin, "NEST:!contract"); _; } } // File: contracts\NestMining.sol /// @dev This contract implemented the mining logic of nest contract NestMining is NestBase, INestMining, INestQuery { // /// @param nestTokenAddress Address of nest token contract // /// @param nestGenesisBlock Genesis block number of nest // constructor(address nestTokenAddress, uint nestGenesisBlock) { // NEST_TOKEN_ADDRESS = nestTokenAddress; // NEST_GENESIS_BLOCK = nestGenesisBlock; // // Placeholder in _accounts, the index of a real account must greater than 0 // _accounts.push(); // } /// @dev To support open-zeppelin/upgrades /// @param nestGovernanceAddress INestGovernance implementation contract address function initialize(address nestGovernanceAddress) override public { super.initialize(nestGovernanceAddress); // Placeholder in _accounts, the index of a real account must greater than 0 _accounts.push(); } ///@dev Definitions for the price sheet, include the full information. (use 256-bits, a storage unit in ethereum evm) struct PriceSheet { // Index of miner account in _accounts. for this way, mapping an address(which need 160-bits) to a 32-bits // integer, support 4 billion accounts uint32 miner; // The block number of this price sheet packaged uint32 height; // The remain number of this price sheet uint32 remainNum; // The eth number which miner will got uint32 ethNumBal; // The eth number which equivalent to token's value which miner will got uint32 tokenNumBal; // The pledged number of nest in this sheet. (Unit: 1000nest) uint24 nestNum1k; // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet uint8 level; // Post fee shares, if there are many sheets in one block, this value is used to divide up mining value uint8 shares; // Represent price as this way, may lose precision, the error less than 1/10^14 // price = priceFraction * 16 ^ priceExponent uint56 priceFloat; } /// @dev Definitions for the price information struct PriceInfo { // Record the index of price sheet, for update price information from price sheet next time. uint32 index; // The block number of this price uint32 height; // The remain number of this price sheet uint32 remainNum; // Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 priceFloat; // Avg Price, represent as float // Represent price as this way, may lose precision, the error less than 1/10^14 uint56 avgFloat; // Square of price volatility, need divide by 2^48 uint48 sigmaSQ; } /// @dev Price channel struct PriceChannel { // Array of price sheets PriceSheet[] sheets; // Price information PriceInfo price; // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) // The information of mining fee // Low 128-bits represent fee per post // High 128-bits represent the current counter of no fee sheets (including settled) uint feeInfo; } /// @dev Structure is used to represent a storage location. Storage variable can be used to avoid indexing from mapping many times struct UINT { uint value; } /// @dev Account information struct Account { // Address of account address addr; // Balances of mining account // tokenAddress=>balance mapping(address=>UINT) balances; } // Configuration Config _config; // Registered account information Account[] _accounts; // Mapping from address to index of account. address=>accountIndex mapping(address=>uint) _accountMapping; // Mapping from token address to price channel. tokenAddress=>PriceChannel mapping(address=>PriceChannel) _channels; // Mapping from token address to ntoken address. tokenAddress=>ntokenAddress mapping(address=>address) _addressCache; // Cache for genesis block number of ntoken. ntokenAddress=>genesisBlockNumber mapping(address=>uint) _genesisBlockNumberCache; // INestPriceFacade implementation contract address address _nestPriceFacadeAddress; // INTokenController implementation contract address address _nTokenControllerAddress; // INestLegder implementation contract address address _nestLedgerAddress; // Unit of post fee. 0.0001 ether uint constant DIMI_ETHER = 0.0001 ether; // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint constant COLLECT_REWARD_MASK = 0xFF; // Ethereum average block time interval, 14 seconds uint constant ETHEREUM_BLOCK_TIMESPAN = 14; /* ========== Governance ========== */ /// @dev Rewritten in the implementation contract, for load other contract addresses. Call /// super.update(nestGovernanceAddress) when overriding, and override method without onlyGovernance /// @param nestGovernanceAddress INestGovernance implementation contract address function update(address nestGovernanceAddress) override public { super.update(nestGovernanceAddress); ( //address nestTokenAddress , //address nestNodeAddress , //address nestLedgerAddress _nestLedgerAddress, //address nestMiningAddress , //address ntokenMiningAddress , //address nestPriceFacadeAddress _nestPriceFacadeAddress, //address nestVoteAddress , //address nestQueryAddress , //address nnIncomeAddress , //address nTokenControllerAddress _nTokenControllerAddress ) = INestGovernance(nestGovernanceAddress).getBuiltinAddress(); } /// @dev Modify configuration /// @param config Configuration object function setConfig(Config calldata config) override external onlyGovernance { _config = config; } /// @dev Get configuration /// @return Configuration object function getConfig() override external view returns (Config memory) { return _config; } /// @dev Clear chache of token. while ntoken recreated, this method is need to call /// @param tokenAddress Token address function resetNTokenCache(address tokenAddress) external onlyGovernance { // Clear cache address ntokenAddress = _getNTokenAddress(tokenAddress); _genesisBlockNumberCache[ntokenAddress] = 0; _addressCache[tokenAddress] = _addressCache[ntokenAddress] = address(0); } /// @dev Set the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @param ntokenAddress The ntoken address function setNTokenAddress(address tokenAddress, address ntokenAddress) override external onlyGovernance { _addressCache[tokenAddress] = ntokenAddress; } /// @dev Get the ntokenAddress from tokenAddress, if ntokenAddress is equals to tokenAddress, means the token is disabled /// @param tokenAddress Destination token address /// @return The ntoken address function getNTokenAddress(address tokenAddress) override external view returns (address) { return _addressCache[tokenAddress]; } /* ========== Mining ========== */ // Get ntoken address of from token address function _getNTokenAddress(address tokenAddress) private returns (address) { address ntokenAddress = _addressCache[tokenAddress]; if (ntokenAddress == address(0)) { ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (ntokenAddress != address(0)) { _addressCache[tokenAddress] = ntokenAddress; } } return ntokenAddress; } // Get genesis block number of ntoken function _getNTokenGenesisBlock(address ntokenAddress) private returns (uint) { uint genesisBlockNumber = _genesisBlockNumberCache[ntokenAddress]; if (genesisBlockNumber == 0) { (genesisBlockNumber,) = INToken(ntokenAddress).checkBlockInfo(); _genesisBlockNumberCache[ntokenAddress] = genesisBlockNumber; } return genesisBlockNumber; } /// @notice Post a price sheet for TOKEN /// @dev It is for TOKEN (except USDT and NTOKENs) whose NTOKEN has a total supply below a threshold (e.g. 5,000,000 * 1e18) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN function post(address tokenAddress, uint ethNum, uint tokenAmountPerEth) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel // Check if the token allow post() address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // Unit of nest is different, but the total supply already exceeded the number of this issue. No additional judgment will be made // ntoken is mint when the price sheet is closed (or withdrawn), this may be the problem that the user // intentionally does not close or withdraw, which leads to the inaccurate judgment of the total amount. ignore require(INToken(ntokenAddress).totalSupply() < uint(config.doublePostThreshold) * 10000 ether, "NM:!post2"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint accountIndex = _addressIndex(msg.sender); // Freeze token and nest // Because of the use of floating-point representation(fraction * 16 ^ exponent), it may bring some precision loss // After assets are frozen according to tokenAmountPerEth * ethNum, the part with poor accuracy may be lost when // the assets are returned, It should be frozen according to decodeFloat(fraction, exponent) * ethNum // However, considering that the loss is less than 1 / 10 ^ 14, the loss here is ignored, and the part of // precision loss can be transferred out as system income in the future _freeze2( _accounts[accountIndex].balances, tokenAddress, tokenAmountPerEth * ethNum, uint(config.pledgeNest) * 1000 ether ); // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 1 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), uint(config.pledgeNest), shares, tokenAmountPerEth); } /// @notice Post two price sheets for a token and its ntoken simultaneously /// @dev Support dual-posts for TOKEN/NTOKEN, (ETH, TOKEN) + (ETH, NTOKEN) /// @param tokenAddress The address of TOKEN contract /// @param ethNum The numbers of ethers to post sheets /// @param tokenAmountPerEth The price of TOKEN /// @param ntokenAmountPerEth The price of NTOKEN function post2( address tokenAddress, uint ethNum, uint tokenAmountPerEth, uint ntokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(ethNum > 0 && ethNum == uint(config.postEthUnit), "NM:!ethNum"); require(tokenAmountPerEth > 0 && ntokenAmountPerEth > 0, "NM:!price"); // 2. Check price channel address ntokenAddress = _getNTokenAddress(tokenAddress); require(ntokenAddress != address(0) && ntokenAddress != tokenAddress, "NM:!tokenAddress"); // 3. Load token channel and sheets PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // 4. Freeze assets uint pledgeNest = uint(config.pledgeNest); uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; _freeze(balances, tokenAddress, ethNum * tokenAmountPerEth); _freeze2(balances, ntokenAddress, ethNum * ntokenAmountPerEth, pledgeNest * 2000 ether); } // 5. Deposit fee // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part uint length = sheets.length; uint shares = _collect(config, channel, ntokenAddress, length, msg.value - ethNum * 2 ether); require(shares > 0 && shares < 256, "NM:!fee"); // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 6. Create token price sheet emit Post(tokenAddress, msg.sender, length, ethNum, tokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, shares, tokenAmountPerEth); // 7. Load ntoken channel and sheets channel = _channels[ntokenAddress]; sheets = channel.sheets; // Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create token price sheet emit Post(ntokenAddress, msg.sender, sheets.length, ethNum, ntokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(ethNum), pledgeNest, 0, ntokenAmountPerEth); } /// @notice Call the function to buy TOKEN/NTOKEN from a posted price sheet /// @dev bite TOKEN(NTOKEN) by ETH, (+ethNumBal, -tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum * newTokenAmountPerEth /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeToken( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum + takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); { mapping(address=>UINT) storage balances = _accounts[accountIndex].balances; uint backTokenValue = decodeFloat(sheet.priceFloat) * takeNum; if (needEthNum * newTokenAmountPerEth > backTokenValue) { _freeze2( balances, tokenAddress, needEthNum * newTokenAmountPerEth - backTokenValue, needNest1k * 1000 ether ); } else { _freeze(balances, NEST_TOKEN_ADDRESS, needNest1k * 1000 ether); _unfreeze(balances, tokenAddress, backTokenValue - needEthNum * newTokenAmountPerEth); } } // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) + takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) - takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } /// @notice Call the function to buy ETH from a posted price sheet /// @dev bite ETH by TOKEN(NTOKEN), (-ethNumBal, +tokenNumBal) /// @param tokenAddress The address of token(ntoken) /// @param index The position of the sheet in priceSheetList[token] /// @param takeNum The amount of biting (in the unit of ETH), realAmount = takeNum /// @param newTokenAmountPerEth The new price of token (1 ETH : some TOKEN), here some means newTokenAmountPerEth function takeEth( address tokenAddress, uint index, uint takeNum, uint newTokenAmountPerEth ) override external payable { Config memory config = _config; // 1. Check arguments require(takeNum > 0 && takeNum % uint(config.postEthUnit) == 0, "NM:!takeNum"); require(newTokenAmountPerEth > 0, "NM:!price"); // 2. Load price sheet PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; PriceSheet memory sheet = sheets[index]; // 3. Check state require(uint(sheet.remainNum) >= takeNum, "NM:!remainNum"); require(uint(sheet.height) + uint(config.priceEffectSpan) >= block.number, "NM:!state"); // 4. Deposit fee { // The revenue is deposited every 256 sheets, deducting the times of taking orders and the settled part address ntokenAddress = _getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { _collect(config, channel, ntokenAddress, sheets.length, 0); } } // 5. Calculate the number of eth, token and nest needed, and freeze them uint needEthNum; uint level = uint(sheet.level); // When the level of the sheet is less than 4, both the nest and the scale of the offer are doubled if (level < uint(config.maxBiteNestedLevel)) { // Double scale sheet needEthNum = takeNum << 1; ++level; } // When the level of the sheet reaches 4 or more, nest doubles, but the scale does not else { // Single scale sheet needEthNum = takeNum; // It is possible that the length of a single chain exceeds 255. When the length of a chain reaches 4 // or more, there is no logical dependence on the specific value of the contract, and the count will // not increase after it is accumulated to 255 if (level < 255) ++level; } require(msg.value == (needEthNum - takeNum) * 1 ether, "NM:!value"); // Number of nest to be pledged //uint needNest1k = ((takeNum << 1) / uint(config.postEthUnit)) * uint(config.pledgeNest); // sheet.ethNumBal + sheet.tokenNumBal is always two times to sheet.ethNum uint needNest1k = (takeNum << 2) * uint(sheet.nestNum1k) / (uint(sheet.ethNumBal) + uint(sheet.tokenNumBal)); // Freeze nest and token uint accountIndex = _addressIndex(msg.sender); _freeze2( _accounts[accountIndex].balances, tokenAddress, needEthNum * newTokenAmountPerEth + decodeFloat(sheet.priceFloat) * takeNum, needNest1k * 1000 ether ); // 6. Update the biten sheet sheet.remainNum = uint32(uint(sheet.remainNum) - takeNum); sheet.ethNumBal = uint32(uint(sheet.ethNumBal) - takeNum); sheet.tokenNumBal = uint32(uint(sheet.tokenNumBal) + takeNum); sheets[index] = sheet; // 7. Calculate the price // According to the current mechanism, the newly added sheet cannot take effect, so the calculated price // is placed before the sheet is added, which can reduce unnecessary traversal _stat(config, channel, sheets); // 8. Create price sheet emit Post(tokenAddress, msg.sender, sheets.length, needEthNum, newTokenAmountPerEth); _createPriceSheet(sheets, accountIndex, uint32(needEthNum), needNest1k, level << 8, newTokenAmountPerEth); } // Create price sheet function _createPriceSheet( PriceSheet[] storage sheets, uint accountIndex, uint32 ethNum, uint nestNum1k, uint level_shares, uint tokenAmountPerEth ) private { sheets.push(PriceSheet( uint32(accountIndex), // uint32 miner; uint32(block.number), // uint32 height; ethNum, // uint32 remainNum; ethNum, // uint32 ethNumBal; ethNum, // uint32 tokenNumBal; uint24(nestNum1k), // uint32 nestNum1k; uint8(level_shares >> 8), // uint8 level; uint8(level_shares & 0xFF), encodeFloat(tokenAmountPerEth) )); } // Nest ore drawing attenuation interval. 2400000 blocks, about one year uint constant NEST_REDUCTION_SPAN = 2400000; // The decay limit of nest ore drawing becomes stable after exceeding this interval. 24 million blocks, about 10 years uint constant NEST_REDUCTION_LIMIT = 24000000; //NEST_REDUCTION_SPAN * 10; // Attenuation gradient array, each attenuation step value occupies 16 bits. The attenuation value is an integer uint constant NEST_REDUCTION_STEPS = 0x280035004300530068008300A300CC010001400190; // 0 // | (uint(400 / uint(1)) << (16 * 0)) // | (uint(400 * 8 / uint(10)) << (16 * 1)) // | (uint(400 * 8 * 8 / uint(10 * 10)) << (16 * 2)) // | (uint(400 * 8 * 8 * 8 / uint(10 * 10 * 10)) << (16 * 3)) // | (uint(400 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10)) << (16 * 4)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10)) << (16 * 5)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10)) << (16 * 6)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 7)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 8)) // | (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 9)) // //| (uint(400 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 * 8 / uint(10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10 * 10)) << (16 * 10)); // | (uint(40) << (16 * 10)); // Calculation of attenuation gradient function _redution(uint delta) private pure returns (uint) { if (delta < NEST_REDUCTION_LIMIT) { return (NEST_REDUCTION_STEPS >> ((delta / NEST_REDUCTION_SPAN) << 4)) & 0xFFFF; } return (NEST_REDUCTION_STEPS >> 160) & 0xFFFF; } /// @notice Close a price sheet of (ETH, USDx) | (ETH, NEST) | (ETH, TOKEN) | (ETH, NTOKEN) /// @dev Here we allow an empty price sheet (still in VERIFICATION-PERIOD) to be closed /// @param tokenAddress The address of TOKEN contract /// @param index The index of the price sheet w.r.t. `token` function close(address tokenAddress, uint index) override external { Config memory config = _config; PriceChannel storage channel = _channels[tokenAddress]; PriceSheet[] storage sheets = channel.sheets; // Load the price channel address ntokenAddress = _getNTokenAddress(tokenAddress); // Call _close() method to close price sheet (uint accountIndex, Tunple memory total) = _close(config, sheets, index, ntokenAddress); if (accountIndex > 0) { // Return eth if (uint(total.ethNum) > 0) { payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); } // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, total.tokenValue, ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } // Calculate the price _stat(config, channel, sheets); } /// @notice Close a batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN contract /// @param indices A list of indices of sheets w.r.t. `token` function closeList(address tokenAddress, uint[] memory indices) override external { // Call _closeList() method to close price sheets ( uint accountIndex, Tunple memory total, address ntokenAddress ) = _closeList(_config, _channels[tokenAddress], tokenAddress, indices); // Return eth payable(indexAddress(accountIndex)).transfer(uint(total.ethNum) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex].balances, tokenAddress, uint(total.tokenValue), ntokenAddress, uint(total.ntokenValue), uint(total.nestValue) ); } /// @notice Close two batch of price sheets passed VERIFICATION-PHASE /// @dev Empty sheets but in VERIFICATION-PHASE aren't allowed /// @param tokenAddress The address of TOKEN1 contract /// @param tokenIndices A list of indices of sheets w.r.t. `token` /// @param ntokenIndices A list of indices of sheets w.r.t. `ntoken` function closeList2( address tokenAddress, uint[] memory tokenIndices, uint[] memory ntokenIndices ) override external { Config memory config = _config; mapping(address=>PriceChannel) storage channels = _channels; // Call _closeList() method to close price sheets ( uint accountIndex1, Tunple memory total1, address ntokenAddress ) = _closeList(config, channels[tokenAddress], tokenAddress, tokenIndices); ( uint accountIndex2, Tunple memory total2, //address ntokenAddress2 ) = _closeList(config, channels[ntokenAddress], ntokenAddress, ntokenIndices); require(accountIndex1 == accountIndex2, "NM:!miner"); //require(ntokenAddress1 == tokenAddress2, "NM:!tokenAddress"); require(uint(total2.ntokenValue) == 0, "NM!ntokenValue"); // Return eth payable(indexAddress(accountIndex1)).transfer((uint(total1.ethNum) + uint(total2.ethNum)) * 1 ether); // Unfreeze assets _unfreeze3( _accounts[accountIndex1].balances, tokenAddress, uint(total1.tokenValue), ntokenAddress, uint(total1.ntokenValue) + uint(total2.tokenValue)/* + uint(total2.ntokenValue) */, uint(total1.nestValue) + uint(total2.nestValue) ); } // Calculation number of blocks which mined function _calcMinedBlocks( PriceSheet[] storage sheets, uint index, PriceSheet memory sheet ) private view returns (uint minedBlocks, uint totalShares) { uint length = sheets.length; uint height = uint(sheet.height); totalShares = uint(sheet.shares); // Backward looking for sheets in the same block for (uint i = index; ++i < length && uint(sheets[i].height) == height;) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[i].shares); } //i = index; // Find sheets in the same block forward uint prev = height; while (index > 0 && uint(prev = sheets[--index].height) == height) { // Multiple sheets in the same block is a small probability event at present, so it can be ignored // to read more than once, if there are always multiple sheets in the same block, it means that the // sheets are very intensive, and the gas consumed here does not have a great impact totalShares += uint(sheets[index].shares); } if (index > 0 || height > prev) { minedBlocks = height - prev; } else { minedBlocks = 10; } } // This structure is for the _close() method to return multiple values struct Tunple { uint tokenValue; uint64 ethNum; uint96 nestValue; uint96 ntokenValue; } // Close price sheet function _close( Config memory config, PriceSheet[] storage sheets, uint index, address ntokenAddress ) private returns (uint accountIndex, Tunple memory value) { PriceSheet memory sheet = sheets[index]; uint height = uint(sheet.height); // Check the status of the price sheet to see if it has reached the effective block interval or has been finished if ((accountIndex = uint(sheet.miner)) > 0 && (height + uint(config.priceEffectSpan) < block.number)) { // TMP: tmp is a polysemous name, here means sheet.shares uint tmp = uint(sheet.shares); // Mining logic // The price sheet which shares is zero dosen't mining if (tmp > 0) { // Currently, mined represents the number of blocks has mined (uint mined, uint totalShares) = _calcMinedBlocks(sheets, index, sheet); // nest mining if (ntokenAddress == NEST_TOKEN_ADDRESS) { // Since then, mined represents the amount of mining // mined = ( // mined // * uint(sheet.shares) // * _redution(height - NEST_GENESIS_BLOCK) // * 1 ether // * uint(config.minerNestReward) // / 10000 // / totalShares // ); // The original expression is shown above. In order to save gas, // the part that can be calculated in advance is calculated first mined = ( mined * tmp * _redution(height - NEST_GENESIS_BLOCK) * uint(config.minerNestReward) * 0.0001 ether / totalShares ); } // ntoken mining else { // The limit blocks can be mined if (mined > uint(config.ntokenMinedBlockLimit)) { mined = uint(config.ntokenMinedBlockLimit); } // Since then, mined represents the amount of mining mined = ( mined * tmp * _redution(height - _getNTokenGenesisBlock(ntokenAddress)) * 0.01 ether / totalShares ); // Put this logic into widhdran() method to reduce gas consumption // ntoken bidders address bidder = INToken(ntokenAddress).checkBidder(); // Legacy ntoken, need separate if (bidder != address(this)) { // Considering that multiple sheets in the same block are small probability events, // we can send token to bidders in each closing operation // 5% for bidder // TMP: tmp is a polysemous name, here means mint ntoken amount for miner tmp = mined * uint(config.minerNTokenReward) / 10000; _unfreeze( _accounts[_addressIndex(bidder)].balances, ntokenAddress, mined - tmp ); // Miner take according proportion which set mined = tmp; } } value.ntokenValue = uint96(mined); } value.nestValue = uint96(uint(sheet.nestNum1k) * 1000 ether); value.ethNum = uint64(sheet.ethNumBal); value.tokenValue = decodeFloat(sheet.priceFloat) * uint(sheet.tokenNumBal); // Set sheet.miner to 0, express the sheet is closed sheet.miner = uint32(0); sheet.ethNumBal = uint32(0); sheet.tokenNumBal = uint32(0); sheets[index] = sheet; } } // Batch close sheets function _closeList( Config memory config, PriceChannel storage channel, address tokenAddress, uint[] memory indices ) private returns (uint accountIndex, Tunple memory total, address ntokenAddress) { ntokenAddress = _getNTokenAddress(tokenAddress); PriceSheet[] storage sheets = channel.sheets; accountIndex = 0; // 1. Traverse sheets for (uint i = indices.length; i > 0;) { // Because too many variables need to be returned, too many variables will be defined, so the structure of tunple is defined (uint minerIndex, Tunple memory value) = _close(config, sheets, indices[--i], ntokenAddress); // Batch closing quotation can only close sheet of the same user if (accountIndex == 0) { // accountIndex == 0 means the first sheet, and the number of this sheet is taken accountIndex = minerIndex; } else { // accountIndex != 0 means that it is a follow-up sheet, and the miner number must be consistent with the previous record require(accountIndex == minerIndex, "NM:!miner"); } total.ntokenValue += value.ntokenValue; total.nestValue += value.nestValue; total.ethNum += value.ethNum; total.tokenValue += value.tokenValue; } _stat(config, channel, sheets); } // Calculate price, average price and volatility function _stat(Config memory config, PriceChannel storage channel, PriceSheet[] storage sheets) private { // Load token price information PriceInfo memory p0 = channel.price; // Length of sheets uint length = sheets.length; // The index of the sheet to be processed in the sheet array uint index = uint(p0.index); // The latest block number for which the price has been calculated uint prev = uint(p0.height); // It's not necessary to load the price information in p0 // Eth count variable used to calculate price uint totalEthNum = 0; // Token count variable for price calculation uint totalTokenValue = 0; // Block number of current sheet uint height = 0; // Traverse the sheets to find the effective price uint effectBlock = block.number - uint(config.priceEffectSpan); PriceSheet memory sheet; for (; ; ++index) { // Gas attack analysis, each post transaction, calculated according to post, needs to write // at least one sheet and freeze two kinds of assets, which needs to consume at least 30000 gas, // In addition to the basic cost of the transaction, at least 50000 gas is required. // In addition, there are other reading and calculation operations. The gas consumed by each // transaction is impossible less than 70000 gas, The attacker can accumulate up to 20 blocks // of sheets to be generated. To ensure that the calculation can be completed in one block, // it is necessary to ensure that the consumption of each price does not exceed 70000 / 20 = 3500 gas, // According to the current logic, each calculation of a price needs to read a storage unit (800) // and calculate the consumption, which can not reach the dangerous value of 3500, so the gas attack // is not considered // Traverse the sheets that has reached the effective interval from the current position bool flag = index >= length || (height = uint((sheet = sheets[index]).height)) >= effectBlock; // Not the same block (or flag is false), calculate the price and update it if (flag || prev != height) { // totalEthNum > 0 Can calculate the price if (totalEthNum > 0) { // Calculate average price and Volatility // Calculation method of volatility of follow-up price uint tmp = decodeFloat(p0.priceFloat); // New price uint price = totalTokenValue / totalEthNum; // Update price p0.remainNum = uint32(totalEthNum); p0.priceFloat = encodeFloat(price); // Clear cumulative values totalEthNum = 0; totalTokenValue = 0; if (tmp > 0) { // Calculate average price // avgPrice[i + 1] = avgPrice[i] * 90% + price[i] * 10% p0.avgFloat = encodeFloat((decodeFloat(p0.avgFloat) * 9 + price) / 10); // When the accuracy of the token is very high or the value of the token relative to // eth is very low, the price may be very large, and there may be overflow problem, // it is not considered for the moment tmp = (price << 48) / tmp; if (tmp > 0x1000000000000) { tmp = tmp - 0x1000000000000; } else { tmp = 0x1000000000000 - tmp; } // earn = price[i] / price[i - 1] - 1; // seconds = time[i] - time[i - 1]; // sigmaSQ[i + 1] = sigmaSQ[i] * 90% + (earn ^ 2 / seconds) * 10% tmp = ( uint(p0.sigmaSQ) * 9 + // It is inevitable that prev greatter than p0.height ((tmp * tmp / ETHEREUM_BLOCK_TIMESPAN / (prev - uint(p0.height))) >> 48) ) / 10; // The current implementation assumes that the volatility cannot exceed 1, and // corresponding to this, when the calculated value exceeds 1, expressed as 0xFFFFFFFFFFFF if (tmp > 0xFFFFFFFFFFFF) { tmp = 0xFFFFFFFFFFFF; } p0.sigmaSQ = uint48(tmp); } // The calculation methods of average price and volatility are different for first price else { // The average price is equal to the price //p0.avgTokenAmount = uint64(price); p0.avgFloat = p0.priceFloat; // The volatility is 0 p0.sigmaSQ = uint48(0); } // Update price block number p0.height = uint32(prev); } // Move to new block number prev = height; } if (flag) { break; } // Cumulative price information totalEthNum += uint(sheet.remainNum); totalTokenValue += decodeFloat(sheet.priceFloat) * uint(sheet.remainNum); } // Update price infomation if (index > uint(p0.index)) { p0.index = uint32(index); channel.price = p0; } } /// @dev The function updates the statistics of price sheets /// It calculates from priceInfo to the newest that is effective. function stat(address tokenAddress) override external { PriceChannel storage channel = _channels[tokenAddress]; _stat(_config, channel, channel.sheets); } // Collect and deposit the commission into NestLedger function _collect( Config memory config, PriceChannel storage channel, address ntokenAddress, uint length, uint currentFee ) private returns (uint) { // Commission is charged for every post(post2), the commission should be deposited to NestLedger, // for saving gas, according to sheets.length, every increase of 256 will deposit once, The calculation formula is: // // totalFee = fee * increment // // In consideration of takeToken, takeEth, change postFeeUnit or miner pay more fee, the formula will be invalid, // at this point, it is need to settle immediately, the details of triggering settlement logic are as follows // // 1. When there is a bite transaction(currentFee is 0), the counter of no fee sheets will be increase 1 // 2. If the Commission of this time is inconsistent with that of last time, deposit immediately // 3. When the increment of sheets.length is 256, deposit immediately // 4. Everyone can trigger immediate settlement by manually calling the settle() method // // In order to realize the logic above, the following values are defined // // 1. PriceChannel.feeInfo // Low 128-bits represent last fee per post // High 128-bits represent the current counter of no fee sheets (including settled) // // 2. COLLECT_REWARD_MASK // The mask of batch deposit trigger, while COLLECT_REWARD_MASK & sheets.length == COLLECT_REWARD_MASK, it will trigger deposit, // COLLECT_REWARD_MASK is set to 0xF for testing (means every 16 sheets will deposit once), // and it will be set to 0xFF for mainnet (means every 256 sheets will deposit once) uint feeUnit = uint(config.postFeeUnit) * DIMI_ETHER; require(currentFee % feeUnit == 0, "NM:!fee"); uint feeInfo = channel.feeInfo; uint oldFee = feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF; // length == 255 means is time to save reward // currentFee != oldFee means the fee is changed, need to settle if (length & COLLECT_REWARD_MASK == COLLECT_REWARD_MASK || (currentFee != oldFee && currentFee > 0)) { // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: currentFee + oldFee * ((length & COLLECT_REWARD_MASK) - (feeInfo >> 128)) } (ntokenAddress); // Update fee information channel.feeInfo = currentFee | (((length + 1) & COLLECT_REWARD_MASK) << 128); } // currentFee is 0, increase no fee counter else if (currentFee == 0) { // channel.feeInfo = feeInfo + (1 << 128); channel.feeInfo = feeInfo + 0x100000000000000000000000000000000; } // Calculate share count return currentFee / feeUnit; } /// @dev Settlement Commission /// @param tokenAddress The token address function settle(address tokenAddress) override external { address ntokenAddress = _getNTokenAddress(tokenAddress); // ntoken is no reward if (tokenAddress != ntokenAddress) { PriceChannel storage channel = _channels[tokenAddress]; uint length = channel.sheets.length & COLLECT_REWARD_MASK; uint feeInfo = channel.feeInfo; // Save reward INestLedger(_nestLedgerAddress).carveETHReward { value: (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) * (length - (feeInfo >> 128)) } (ntokenAddress); // Manual settlement does not need to update Commission variables channel.feeInfo = (feeInfo & 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF) | (length << 128); } } // Convert PriceSheet to PriceSheetView function _toPriceSheetView(PriceSheet memory sheet, uint index) private view returns (PriceSheetView memory) { return PriceSheetView( // Index number uint32(index), // Miner address indexAddress(sheet.miner), // The block number of this price sheet packaged sheet.height, // The remain number of this price sheet sheet.remainNum, // The eth number which miner will got sheet.ethNumBal, // The eth number which equivalent to token's value which miner will got sheet.tokenNumBal, // The pledged number of nest in this sheet. (Unit: 1000nest) sheet.nestNum1k, // The level of this sheet. 0 expresses initial price sheet, a value greater than 0 expresses bite price sheet sheet.level, // Post fee shares sheet.shares, // Price uint152(decodeFloat(sheet.priceFloat)) ); } /// @dev List sheets by page /// @param tokenAddress Destination token address /// @param offset Skip previous (offset) records /// @param count Return (count) records /// @param order Order. 0 reverse order, non-0 positive order /// @return List of price sheets function list( address tokenAddress, uint offset, uint count, uint order ) override external view noContract returns (PriceSheetView[] memory) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheetView[] memory result = new PriceSheetView[](count); uint length = sheets.length; uint i = 0; // Reverse order if (order == 0) { uint index = length - offset; uint end = index > count ? index - count : 0; while (index > end) { --index; result[i++] = _toPriceSheetView(sheets[index], index); } } // Positive order else { uint index = offset; uint end = index + count; if (end > length) { end = length; } while (index < end) { result[i++] = _toPriceSheetView(sheets[index], index); ++index; } } return result; } /// @dev Estimated mining amount /// @param tokenAddress Destination token address /// @return Estimated mining amount function estimate(address tokenAddress) override external view returns (uint) { address ntokenAddress = INTokenController(_nTokenControllerAddress).getNTokenAddress(tokenAddress); if (tokenAddress != ntokenAddress) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint index = sheets.length; while (index > 0) { PriceSheet memory sheet = sheets[--index]; if (uint(sheet.shares) > 0) { // Standard mining amount uint standard = (block.number - uint(sheet.height)) * 1 ether; // Genesis block number of ntoken uint genesisBlock = NEST_GENESIS_BLOCK; // Not nest, the calculation methods of standard mining amount and genesis block number are different if (ntokenAddress != NEST_TOKEN_ADDRESS) { // The standard mining amount of ntoken is 1/100 of nest standard /= 100; // Genesis block number of ntoken is obtained separately (genesisBlock,) = INToken(ntokenAddress).checkBlockInfo(); } return standard * _redution(block.number - genesisBlock); } } } return 0; } /// @dev Query the quantity of the target quotation /// @param tokenAddress Token address. The token can't mine. Please make sure you don't use the token address when calling /// @param index The index of the sheet /// @return minedBlocks Mined block period from previous block /// @return totalShares Total shares of sheets in the block function getMinedBlocks( address tokenAddress, uint index ) override external view returns (uint minedBlocks, uint totalShares) { PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet = sheets[index]; // The bite sheet or ntoken sheet dosen't mining if (uint(sheet.shares) == 0) { return (0, 0); } return _calcMinedBlocks(sheets, index, sheet); } /* ========== Accounts ========== */ /// @dev Withdraw assets /// @param tokenAddress Destination token address /// @param value The value to withdraw function withdraw(address tokenAddress, uint value) override external { // The user's locked nest and the mining pool's nest are stored together. When the nest is mined over, // the problem of taking the locked nest as the ore drawing will appear // As it will take a long time for nest to finish mining, this problem will not be considered for the time being UINT storage balance = _accounts[_accountMapping[msg.sender]].balances[tokenAddress]; //uint balanceValue = balance.value; //require(balanceValue >= value, "NM:!balance"); balance.value -= value; // ntoken mining uint ntokenBalance = INToken(tokenAddress).balanceOf(address(this)); if (ntokenBalance < value) { // mining INToken(tokenAddress).increaseTotal(value - ntokenBalance); } TransferHelper.safeTransfer(tokenAddress, msg.sender, value); } /// @dev View the number of assets specified by the user /// @param tokenAddress Destination token address /// @param addr Destination address /// @return Number of assets function balanceOf(address tokenAddress, address addr) override external view returns (uint) { return _accounts[_accountMapping[addr]].balances[tokenAddress].value; } /// @dev Gets the index number of the specified address. If it does not exist, register /// @param addr Destination address /// @return The index number of the specified address function _addressIndex(address addr) private returns (uint) { uint index = _accountMapping[addr]; if (index == 0) { // If it exceeds the maximum number that 32 bits can store, you can't continue to register a new account. // If you need to support a new account, you need to update the contract require((_accountMapping[addr] = index = _accounts.length) < 0x100000000, "NM:!accounts"); _accounts.push().addr = addr; } return index; } /// @dev Gets the address corresponding to the given index number /// @param index The index number of the specified address /// @return The address corresponding to the given index number function indexAddress(uint index) override public view returns (address) { return _accounts[index].addr; } /// @dev Gets the registration index number of the specified address /// @param addr Destination address /// @return 0 means nonexistent, non-0 means index number function getAccountIndex(address addr) override external view returns (uint) { return _accountMapping[addr]; } /// @dev Get the length of registered account array /// @return The length of registered account array function getAccountCount() override external view returns (uint) { return _accounts.length; } /* ========== Asset management ========== */ /// @dev Freeze token /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param value token amount function _freeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; uint balanceValue = balance.value; if (balanceValue < value) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), value - balanceValue); } else { balance.value = balanceValue - value; } } /// @dev Unfreeze token /// @param balances Balances ledgerBalances ledger /// @param tokenAddress Destination token address /// @param value token amount function _unfreeze(mapping(address=>UINT) storage balances, address tokenAddress, uint value) private { UINT storage balance = balances[tokenAddress]; balance.value += value; } /// @dev freeze token and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param nestValue nest amount function _freeze2( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, uint nestValue ) private { UINT storage balance; uint balanceValue; // If tokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == tokenAddress) { nestValue += tokenValue; } // tokenAddress is not NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[tokenAddress]; balanceValue = balance.value; if (balanceValue < tokenValue) { balance.value = 0; TransferHelper.safeTransferFrom(tokenAddress, msg.sender, address(this), tokenValue - balanceValue); } else { balance.value = balanceValue - tokenValue; } } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balanceValue = balance.value; if (balanceValue < nestValue) { balance.value = 0; TransferHelper.safeTransferFrom(NEST_TOKEN_ADDRESS, msg.sender, address(this), nestValue - balanceValue); } else { balance.value = balanceValue - nestValue; } } /// @dev Unfreeze token, ntoken and nest /// @param balances Balances ledger /// @param tokenAddress Destination token address /// @param tokenValue token amount /// @param ntokenAddress Destination ntoken address /// @param ntokenValue ntoken amount /// @param nestValue nest amount function _unfreeze3( mapping(address=>UINT) storage balances, address tokenAddress, uint tokenValue, address ntokenAddress, uint ntokenValue, uint nestValue ) private { UINT storage balance; // If tokenAddress is ntokenAddress, add it to ntokenValue if (ntokenAddress == tokenAddress) { ntokenValue += tokenValue; } // tokenAddress is not ntokenAddress, unfreeze it else { balance = balances[tokenAddress]; balance.value += tokenValue; } // If ntokenAddress is NEST_TOKEN_ADDRESS, add it to nestValue if (NEST_TOKEN_ADDRESS == ntokenAddress) { nestValue += ntokenValue; } // ntokenAddress is NEST_TOKEN_ADDRESS, unfreeze it else { balance = balances[ntokenAddress]; balance.value += ntokenValue; } // Unfreeze nest balance = balances[NEST_TOKEN_ADDRESS]; balance.value += nestValue; } /* ========== INestQuery ========== */ // Check msg.sender function _check() private view { require(msg.sender == _nestPriceFacadeAddress || msg.sender == tx.origin); } /// @dev Get the latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function triggeredPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return (uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat)); } return (0, 0); } /// @dev Get the full information of latest trigger price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo(address tokenAddress) override public view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat), decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); } /// @dev Find the price at block number /// @param tokenAddress Destination token address /// @param height Destination block number /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function findPrice( address tokenAddress, uint height ) override external view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; uint priceEffectSpan = uint(_config.priceEffectSpan); uint length = sheets.length; uint index = 0; uint sheetHeight; height -= priceEffectSpan; { // If there is no sheet in this channel, length is 0, length - 1 will overflow, uint right = length - 1; uint left = 0; // Find the index use Binary Search while (left < right) { index = (left + right) >> 1; sheetHeight = uint(sheets[index].height); if (height > sheetHeight) { left = ++index; } else if (height < sheetHeight) { // When index = 0, this statement will have an underflow exception, which usually // indicates that the effective block height passed during the call is lower than // the block height of the first quotation right = --index; } else { break; } } } // Calculate price uint totalEthNum = 0; uint totalTokenValue = 0; uint h = 0; uint remainNum; PriceSheet memory sheet; // Find sheets forward for (uint i = index; i < length;) { sheet = sheets[i++]; sheetHeight = uint(sheet.height); if (height < sheetHeight) { break; } remainNum = uint(sheet.remainNum); if (remainNum > 0) { if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } // Find sheets backward while (index > 0) { sheet = sheets[--index]; remainNum = uint(sheet.remainNum); if (remainNum > 0) { sheetHeight = uint(sheet.height); if (h == 0) { h = sheetHeight; } else if (h != sheetHeight) { break; } totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } } if (totalEthNum > 0) { return (h + priceEffectSpan, totalTokenValue / totalEthNum); } return (0, 0); } /// @dev Get the latest effective price /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) function latestPrice(address tokenAddress) override public view returns (uint blockNumber, uint price) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (; ; ) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { return (height + priceEffectSpan, totalTokenValue / totalEthNum); } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return (0, 0); } /// @dev Get the last (num) effective price /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return An array which length is num * 2, each two element expresses one price like blockNumber|price function lastPriceList(address tokenAddress, uint count) override public view returns (uint[] memory) { _check(); PriceSheet[] storage sheets = _channels[tokenAddress].sheets; PriceSheet memory sheet; uint[] memory array = new uint[](count <<= 1); uint priceEffectSpan = uint(_config.priceEffectSpan); uint h = block.number - priceEffectSpan; uint index = sheets.length; uint totalEthNum = 0; uint totalTokenValue = 0; uint height = 0; for (uint i = 0; i < count;) { bool flag = index == 0; if (flag || height != uint((sheet = sheets[--index]).height)) { if (totalEthNum > 0 && height <= h) { array[i++] = height + priceEffectSpan; array[i++] = totalTokenValue / totalEthNum; } if (flag) { break; } totalEthNum = 0; totalTokenValue = 0; height = uint(sheet.height); } uint remainNum = uint(sheet.remainNum); totalEthNum += remainNum; totalTokenValue += decodeFloat(sheet.priceFloat) * remainNum; } return array; } /// @dev Returns the results of latestPrice() and triggeredPriceInfo() /// @param tokenAddress Destination token address /// @return latestPriceBlockNumber The block number of latest price /// @return latestPriceValue The token latest price. (1eth equivalent to (price) token) /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function latestPriceAndTriggeredPriceInfo(address tokenAddress) override external view returns ( uint latestPriceBlockNumber, uint latestPriceValue, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { (latestPriceBlockNumber, latestPriceValue) = latestPrice(tokenAddress); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Returns lastPriceList and triggered price info /// @param tokenAddress Destination token address /// @param count The number of prices that want to return /// @return prices An array which length is num * 2, each two element expresses one price like blockNumber|price /// @return triggeredPriceBlockNumber The block number of triggered price /// @return triggeredPriceValue The token triggered price. (1eth equivalent to (price) token) /// @return triggeredAvgPrice Average price /// @return triggeredSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function lastPriceListAndTriggeredPriceInfo(address tokenAddress, uint count) override external view returns ( uint[] memory prices, uint triggeredPriceBlockNumber, uint triggeredPriceValue, uint triggeredAvgPrice, uint triggeredSigmaSQ ) { prices = lastPriceList(tokenAddress, count); ( triggeredPriceBlockNumber, triggeredPriceValue, triggeredAvgPrice, triggeredSigmaSQ ) = triggeredPriceInfo(tokenAddress); } /// @dev Get the latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function triggeredPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = triggeredPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = triggeredPrice(_addressCache[tokenAddress]); } /// @dev Get the full information of latest trigger price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return avgPrice Average price /// @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) /// @return ntokenAvgPrice Average price of ntoken /// @return ntokenSigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that /// the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, /// it means that the volatility has exceeded the range that can be expressed function triggeredPriceInfo2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ, uint ntokenBlockNumber, uint ntokenPrice, uint ntokenAvgPrice, uint ntokenSigmaSQ ) { (blockNumber, price, avgPrice, sigmaSQ) = triggeredPriceInfo(tokenAddress); ( ntokenBlockNumber, ntokenPrice, ntokenAvgPrice, ntokenSigmaSQ ) = triggeredPriceInfo(_addressCache[tokenAddress]); } /// @dev Get the latest effective price. (token and ntoken) /// @param tokenAddress Destination token address /// @return blockNumber The block number of price /// @return price The token price. (1eth equivalent to (price) token) /// @return ntokenBlockNumber The block number of ntoken price /// @return ntokenPrice The ntoken price. (1eth equivalent to (price) ntoken) function latestPrice2(address tokenAddress) override external view returns ( uint blockNumber, uint price, uint ntokenBlockNumber, uint ntokenPrice ) { (blockNumber, price) = latestPrice(tokenAddress); (ntokenBlockNumber, ntokenPrice) = latestPrice(_addressCache[tokenAddress]); } /* ========== Tools and methods ========== */ /// @dev Encode the uint value as a floating-point representation in the form of fraction * 16 ^ exponent /// @param value Destination uint value /// @return float format function encodeFloat(uint value) private pure returns (uint56) { uint exponent = 0; while (value > 0x3FFFFFFFFFFFF) { value >>= 4; ++exponent; } return uint56((value << 6) | exponent); } /// @dev Decode the floating-point representation of fraction * 16 ^ exponent to uint /// @param floatValue fraction value /// @return decode format function decodeFloat(uint56 floatValue) private pure returns (uint) { return (uint(floatValue) >> 6) << ((uint(floatValue) & 0x3F) << 2); } }
@dev Get the full information of latest trigger price @param tokenAddress Destination token address @return blockNumber The block number of price @return price The token price. (1eth equivalent to (price) token) @return avgPrice Average price @return sigmaSQ The square of the volatility (18 decimal places). The current implementation assumes that the volatility cannot exceed 1. Correspondingly, when the return value is equal to 999999999999996447, it means that the volatility has exceeded the range that can be expressed
function triggeredPriceInfo(address tokenAddress) override public view returns ( uint blockNumber, uint price, uint avgPrice, uint sigmaSQ ) { _check(); PriceInfo memory priceInfo = _channels[tokenAddress].price; if (uint(priceInfo.remainNum) > 0) { return ( uint(priceInfo.height) + uint(_config.priceEffectSpan), decodeFloat(priceInfo.priceFloat), decodeFloat(priceInfo.avgFloat), (uint(priceInfo.sigmaSQ) * 1 ether) >> 48 ); } return (0, 0, 0, 0); }
52,805
[ 1, 967, 326, 1983, 1779, 434, 4891, 3080, 6205, 225, 1147, 1887, 10691, 1147, 1758, 327, 1203, 1854, 1021, 1203, 1300, 434, 6205, 327, 6205, 1021, 1147, 6205, 18, 261, 21, 546, 7680, 358, 261, 8694, 13, 1147, 13, 327, 11152, 5147, 27275, 6205, 327, 7299, 55, 53, 1021, 8576, 434, 326, 6626, 30139, 261, 2643, 6970, 12576, 2934, 1021, 783, 4471, 13041, 716, 540, 326, 6626, 30139, 2780, 9943, 404, 18, 9557, 17863, 310, 715, 16, 1347, 326, 327, 460, 353, 3959, 358, 23841, 7991, 31463, 1105, 9462, 16, 540, 518, 4696, 716, 326, 6626, 30139, 711, 12428, 326, 1048, 716, 848, 506, 26863, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 10861, 5147, 966, 12, 2867, 1147, 1887, 13, 3849, 1071, 1476, 1135, 261, 203, 3639, 2254, 1203, 1854, 16, 203, 3639, 2254, 6205, 16, 203, 3639, 2254, 11152, 5147, 16, 203, 3639, 2254, 7299, 55, 53, 203, 565, 262, 288, 203, 203, 3639, 389, 1893, 5621, 203, 3639, 20137, 966, 3778, 6205, 966, 273, 389, 9114, 63, 2316, 1887, 8009, 8694, 31, 203, 203, 3639, 309, 261, 11890, 12, 8694, 966, 18, 2764, 530, 2578, 13, 405, 374, 13, 288, 203, 5411, 327, 261, 203, 7734, 2254, 12, 8694, 966, 18, 4210, 13, 397, 2254, 24899, 1425, 18, 8694, 12477, 6952, 3631, 203, 7734, 2495, 4723, 12, 8694, 966, 18, 8694, 4723, 3631, 203, 7734, 2495, 4723, 12, 8694, 966, 18, 14141, 4723, 3631, 203, 7734, 261, 11890, 12, 8694, 966, 18, 13201, 55, 53, 13, 380, 404, 225, 2437, 13, 1671, 9934, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 327, 261, 20, 16, 374, 16, 374, 16, 374, 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 ]
./full_match/84531/0xf4020cB4D6AAA20044babC11e5e208071a80800A/sources/contracts/core/connext/facets/RoutersFacet.sol
* @notice Used to set the max amount of routers a payment can be routed through @param _newMaxRouters The new max amount of routers/
function setMaxRoutersPerTransfer(uint256 _newMaxRouters) external onlyOwnerOrAdmin { if (_newMaxRouters == 0 || _newMaxRouters == s.maxRoutersPerTransfer) revert RoutersFacet__setMaxRoutersPerTransfer_invalidMaxRoutersPerTransfer(); emit MaxRoutersPerTransferUpdated(_newMaxRouters, msg.sender); s.maxRoutersPerTransfer = _newMaxRouters; }
11,526,254
[ 1, 6668, 358, 444, 326, 943, 3844, 434, 28944, 279, 5184, 848, 506, 3237, 329, 3059, 225, 389, 2704, 2747, 4583, 414, 1021, 394, 943, 3844, 434, 28944, 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, 225, 445, 10851, 4583, 414, 2173, 5912, 12, 11890, 5034, 389, 2704, 2747, 4583, 414, 13, 3903, 1338, 5541, 1162, 4446, 288, 203, 565, 309, 261, 67, 2704, 2747, 4583, 414, 422, 374, 747, 389, 2704, 2747, 4583, 414, 422, 272, 18, 1896, 4583, 414, 2173, 5912, 13, 203, 1377, 15226, 7271, 414, 11137, 972, 542, 2747, 4583, 414, 2173, 5912, 67, 5387, 2747, 4583, 414, 2173, 5912, 5621, 203, 203, 565, 3626, 4238, 4583, 414, 2173, 5912, 7381, 24899, 2704, 2747, 4583, 414, 16, 1234, 18, 15330, 1769, 203, 203, 565, 272, 18, 1896, 4583, 414, 2173, 5912, 273, 389, 2704, 2747, 4583, 414, 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 ]
./full_match/1/0xA0d4980a9ba0fdB147aFa89d0AFC551f7603D778/sources/contracts/incentives/DistributionManager.sol
* @dev Updates the state of one distribution, mainly rewards index and timestamp @param asset The address of the asset being updated @param assetConfig Storage pointer to the distribution's config @param totalStaked Current total of staked assets for this distribution @return The new distribution index/optimization: storing one after another saves one SSTORE
function _updateAssetStateInternal( address asset, AssetData storage assetConfig, uint256 totalStaked ) internal returns (uint256) { uint256 oldIndex = assetConfig.index; uint256 emissionPerSecond = assetConfig.emissionPerSecond; uint128 lastUpdateTimestamp = assetConfig.lastUpdateTimestamp; if (block.timestamp == lastUpdateTimestamp) { return oldIndex; } uint256 newIndex = _getAssetIndex( oldIndex, emissionPerSecond, lastUpdateTimestamp, totalStaked ); if (newIndex == oldIndex) { assetConfig.lastUpdateTimestamp = uint40(block.timestamp); require(uint104(newIndex) == newIndex, 'Index overflow'); assetConfig.index = uint104(newIndex); assetConfig.lastUpdateTimestamp = uint40(block.timestamp); emit AssetIndexUpdated(asset, newIndex); } return newIndex; }
3,110,567
[ 1, 5121, 326, 919, 434, 1245, 7006, 16, 31457, 283, 6397, 770, 471, 2858, 225, 3310, 1021, 1758, 434, 326, 3310, 3832, 3526, 225, 3310, 809, 5235, 4407, 358, 326, 7006, 1807, 642, 225, 2078, 510, 9477, 6562, 2078, 434, 384, 9477, 7176, 364, 333, 7006, 327, 1021, 394, 7006, 770, 19, 16689, 1588, 30, 15729, 1245, 1839, 4042, 14649, 1245, 348, 13651, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 389, 2725, 6672, 1119, 3061, 12, 203, 565, 1758, 3310, 16, 203, 565, 10494, 751, 2502, 3310, 809, 16, 203, 565, 2254, 5034, 2078, 510, 9477, 203, 225, 262, 2713, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2254, 5034, 1592, 1016, 273, 3310, 809, 18, 1615, 31, 203, 565, 2254, 5034, 801, 19710, 2173, 8211, 273, 3310, 809, 18, 351, 19710, 2173, 8211, 31, 203, 565, 2254, 10392, 1142, 1891, 4921, 273, 3310, 809, 18, 2722, 1891, 4921, 31, 203, 203, 565, 309, 261, 2629, 18, 5508, 422, 1142, 1891, 4921, 13, 288, 203, 1377, 327, 1592, 1016, 31, 203, 565, 289, 203, 203, 565, 2254, 5034, 21309, 273, 389, 588, 6672, 1016, 12, 203, 1377, 1592, 1016, 16, 203, 1377, 801, 19710, 2173, 8211, 16, 203, 1377, 1142, 1891, 4921, 16, 203, 1377, 2078, 510, 9477, 203, 565, 11272, 203, 203, 565, 309, 261, 2704, 1016, 422, 1592, 1016, 13, 288, 203, 1377, 3310, 809, 18, 2722, 1891, 4921, 273, 2254, 7132, 12, 2629, 18, 5508, 1769, 203, 1377, 2583, 12, 11890, 21869, 12, 2704, 1016, 13, 422, 21309, 16, 296, 1016, 9391, 8284, 203, 1377, 3310, 809, 18, 1615, 273, 2254, 21869, 12, 2704, 1016, 1769, 203, 1377, 3310, 809, 18, 2722, 1891, 4921, 273, 2254, 7132, 12, 2629, 18, 5508, 1769, 203, 1377, 3626, 10494, 1016, 7381, 12, 9406, 16, 21309, 1769, 203, 565, 289, 203, 203, 565, 327, 21309, 31, 203, 225, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity 0.8.1; import "./itemsFactory.sol"; /** * @title Change the cases in items * @notice This contract allows players to change the reward earned for NFT * @dev The selected items given to the players come from the data base create in the factory by the administrator. * Only unlock items can be distributed */ contract convertRewardNFT is itemsFactory { ///@dev RandNonce for the random Item uint private randNonce = 1; event rewardWithdrawn(string tokenName,address indexed _to); ///@dev Transform the reward as a NFT function getReward () public { require (balanceOf(_administrator) != 0, "None available item for now"); require (multiverseData[msg.sender].isRegistered, "Not a regitered player"); require (multiverseData[msg.sender].rewardLv1 != 0 || multiverseData[msg.sender].rewardLv2 != 0, "You have no rewards to get"); randNonce ++; if (multiverseData[msg.sender].rewardLv1 != 0){ for (uint i = multiverseData[msg.sender].rewardLv1; i > 0; i-- ){ uint idItem = getAvailableItem(1); _transfer(_administrator, msg.sender, idItem); emit rewardWithdrawn(items[idItem].name, msg.sender); } multiverseData[msg.sender].rewardLv1 = 0; } if (multiverseData[msg.sender].rewardLv2 != 0){ for (uint i = multiverseData[msg.sender].rewardLv2; i > 0; i-- ){ uint idItem = getAvailableItem(2); _transfer(_administrator, msg.sender, idItem); emit rewardWithdrawn(items[idItem].name, msg.sender); } multiverseData[msg.sender].rewardLv2 = 0; } } /** * @dev Get an available item in the main database of unlock items. * First we create the size of an array, then we fill it with the eligible token * and at the end we send the Id of the won token */ function getAvailableItem(uint8 _level) private view returns(uint){ uint sizeArray; uint Id; for (uint k; k < balanceOf(_administrator); k++){ if (!items[tokenOfOwnerByIndex(_administrator,k)].locked && items[tokenOfOwnerByIndex(_administrator,k)].levelItem == _level){ sizeArray++; } } if (sizeArray == 0){ revert('There is not enough item availbale, please come back later'); } else { uint[] memory availableItem = new uint[](sizeArray); for (uint k; k <balanceOf(_administrator); k++){ if (!items[tokenOfOwnerByIndex(_administrator,k)].locked && items[tokenOfOwnerByIndex(_administrator,k)].levelItem == _level){ availableItem[Id] = tokenOfOwnerByIndex(_administrator,k); Id++; } } uint randReward = uint(keccak256 (abi.encodePacked(block.timestamp, msg.sender, randNonce))) % availableItem.length; return availableItem[randReward]; } } }
* @dev Get an available item in the main database of unlock items. First we create the size of an array, then we fill it with the eligible token and at the end we send the Id of the won token/
function getAvailableItem(uint8 _level) private view returns(uint){ uint sizeArray; uint Id; for (uint k; k < balanceOf(_administrator); k++){ if (!items[tokenOfOwnerByIndex(_administrator,k)].locked && items[tokenOfOwnerByIndex(_administrator,k)].levelItem == _level){ sizeArray++; } } if (sizeArray == 0){ revert('There is not enough item availbale, please come back later'); uint[] memory availableItem = new uint[](sizeArray); for (uint k; k <balanceOf(_administrator); k++){ if (!items[tokenOfOwnerByIndex(_administrator,k)].locked && items[tokenOfOwnerByIndex(_administrator,k)].levelItem == _level){ availableItem[Id] = tokenOfOwnerByIndex(_administrator,k); Id++; } } uint randReward = uint(keccak256 (abi.encodePacked(block.timestamp, msg.sender, randNonce))) % availableItem.length; return availableItem[randReward]; } }
12,585,965
[ 1, 967, 392, 2319, 761, 316, 326, 2774, 2063, 434, 7186, 1516, 18, 5783, 732, 752, 326, 963, 434, 392, 526, 16, 1508, 732, 3636, 518, 598, 326, 21351, 1147, 471, 622, 326, 679, 732, 1366, 326, 3124, 434, 326, 8462, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 15796, 1180, 12, 11890, 28, 389, 2815, 13, 3238, 1476, 1135, 12, 11890, 15329, 203, 27699, 3639, 2254, 963, 1076, 31, 203, 3639, 2254, 3124, 31, 203, 540, 203, 3639, 364, 261, 11890, 417, 31, 417, 411, 11013, 951, 24899, 3666, 14207, 1769, 417, 27245, 95, 203, 5411, 309, 16051, 3319, 63, 2316, 951, 5541, 21268, 24899, 3666, 14207, 16, 79, 13, 8009, 15091, 597, 1516, 63, 2316, 951, 5541, 21268, 24899, 3666, 14207, 16, 79, 13, 8009, 2815, 1180, 422, 389, 2815, 15329, 203, 2868, 963, 1076, 9904, 31, 203, 5411, 289, 203, 1850, 289, 203, 377, 203, 3639, 309, 261, 1467, 1076, 422, 374, 15329, 203, 1850, 15226, 2668, 9828, 353, 486, 7304, 761, 15783, 70, 5349, 16, 9582, 12404, 1473, 5137, 8284, 203, 377, 203, 1850, 2254, 8526, 3778, 2319, 1180, 273, 394, 2254, 8526, 12, 1467, 1076, 1769, 27699, 377, 203, 1850, 364, 261, 11890, 417, 31, 417, 411, 12296, 951, 24899, 3666, 14207, 1769, 417, 27245, 95, 203, 5411, 309, 16051, 3319, 63, 2316, 951, 5541, 21268, 24899, 3666, 14207, 16, 79, 13, 8009, 15091, 597, 1516, 63, 2316, 951, 5541, 21268, 24899, 3666, 14207, 16, 79, 13, 8009, 2815, 1180, 422, 389, 2815, 15329, 203, 2868, 2319, 1180, 63, 548, 65, 273, 1147, 951, 5541, 21268, 24899, 3666, 14207, 16, 79, 1769, 203, 2868, 3124, 9904, 31, 203, 5411, 289, 203, 1850, 289, 203, 1850, 2254, 5605, 17631, 1060, 273, 2254, 12, 79, 24410, 581, 5034, 261, 21457, 18, 3015, 4420, 329, 12, 2629, 18, 5508, 2 ]
./full_match/80001/0x75D1E3Cd2Efd27cC9143B3f72d46e5f012D205f3/sources/KonzaApp.sol
The number of tokens burned.
uint256 public _burnCounter;
856,737
[ 1, 1986, 1300, 434, 2430, 18305, 329, 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, 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, 2254, 5034, 1071, 389, 70, 321, 4789, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-09-18 */ /** *Submitted for verification at Etherscan.io on 2020-09-18 */ // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/token/ERC20/IERC20.sol pragma solidity 0.5.7; /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ interface IERC20 { function transfer(address to, uint256 value) external returns (bool); function approve(address spender, uint256 value) external returns (bool); function transferFrom(address from, address to, uint256 value) external returns (bool); function totalSupply() external view returns (uint256); function balanceOf(address who) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); event Transfer( address indexed from, address indexed to, uint256 value ); event Approval( address indexed owner, address indexed spender, uint256 value ); } // File: nexusmutual-contracts/contracts/external/openzeppelin-solidity/math/SafeMath.sol pragma solidity 0.5.7; /** * @title SafeMath * @dev Math operations with safety checks that revert 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 = 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; } } // File: nexusmutual-contracts/contracts/NXMToken.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract NXMToken is IERC20 { using SafeMath for uint256; event WhiteListed(address indexed member); event BlackListed(address indexed member); mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; mapping (address => bool) public whiteListed; mapping(address => uint) public isLockedForMV; uint256 private _totalSupply; string public name = "NXM"; string public symbol = "NXM"; uint8 public decimals = 18; address public operator; modifier canTransfer(address _to) { require(whiteListed[_to]); _; } modifier onlyOperator() { if (operator != address(0)) require(msg.sender == operator); _; } constructor(address _founderAddress, uint _initialSupply) public { _mint(_founderAddress, _initialSupply); } /** * @dev Total number of tokens in existence */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public view returns (uint256) { return _balances[owner]; } /** * @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 ) public view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Approve the passed address to spend the specified amount of tokens on behalf 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 spender The address which will spend the funds. * @param value The amount of tokens to be spent. */ function approve(address spender, uint256 value) public returns (bool) { require(spender != address(0)); _allowed[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 spender The address which will spend the funds. * @param addedValue The amount of tokens to increase the allowance by. */ 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; } /** * @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 spender The address which will spend the funds. * @param subtractedValue The amount of tokens to decrease the allowance by. */ 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; } /** * @dev Adds a user to whitelist * @param _member address to add to whitelist */ function addToWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = true; emit WhiteListed(_member); return true; } /** * @dev removes a user from whitelist * @param _member address to remove from whitelist */ function removeFromWhiteList(address _member) public onlyOperator returns (bool) { whiteListed[_member] = false; emit BlackListed(_member); return true; } /** * @dev change operator address * @param _newOperator address of new operator */ function changeOperator(address _newOperator) public onlyOperator returns (bool) { operator = _newOperator; return true; } /** * @dev burns an amount of the tokens of the message sender * account. * @param amount The amount that will be burnt. */ function burn(uint256 amount) public returns (bool) { _burn(msg.sender, amount); return true; } /** * @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 returns (bool) { _burnFrom(from, value); return true; } /** * @dev function that mints an amount of the token and assigns it to * an account. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function mint(address account, uint256 amount) public onlyOperator { _mint(account, amount); } /** * @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 canTransfer(to) returns (bool) { require(isLockedForMV[msg.sender] < now); // if not voted under governance require(value <= _balances[msg.sender]); _transfer(to, value); return true; } /** * @dev Transfer tokens to the operator from the specified address * @param from The address to transfer from. * @param value The amount to be transferred. */ function operatorTransfer(address from, uint256 value) public onlyOperator returns (bool) { require(value <= _balances[from]); _transferFrom(from, operator, 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 canTransfer(to) returns (bool) { require(isLockedForMV[from] < now); // if not voted under governance require(value <= _balances[from]); require(value <= _allowed[from][msg.sender]); _transferFrom(from, to, value); return true; } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyOperator { if (_days.add(now) > isLockedForMV[_of]) isLockedForMV[_of] = _days.add(now); } /** * @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) internal { _balances[msg.sender] = _balances[msg.sender].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(msg.sender, to, value); } /** * @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 ) internal { _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _allowed[from][msg.sender] = _allowed[from][msg.sender].sub(value); emit Transfer(from, to, value); } /** * @dev Internal function that mints an amount of the token and assigns it to * an account. This encapsulates the modification of balances such that the * proper events are emitted. * @param account The account that will receive the created tokens. * @param amount The amount that will be created. */ function _mint(address account, uint256 amount) internal { require(account != address(0)); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param amount The amount that will be burnt. */ function _burn(address account, uint256 amount) internal { require(amount <= _balances[account]); _totalSupply = _totalSupply.sub(amount); _balances[account] = _balances[account].sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Internal function that burns an amount of the token of a given * account, deducting from the sender's allowance for said account. Uses the * internal burn function. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { require(value <= _allowed[account][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[account][msg.sender] = _allowed[account][msg.sender].sub( value); _burn(account, value); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IProposalCategory { event Category( uint indexed categoryId, string categoryName, string actionHash ); /// @dev Adds new category /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external; /// @dev gets category details function category(uint _categoryId) external view returns( uint categoryId, uint memberRoleToVote, uint majorityVotePerc, uint quorumPerc, uint[] memory allowedToCreateProposal, uint closingTime, uint minStake ); ///@dev gets category action details function categoryAction(uint _categoryId) external view returns( uint categoryId, address contractAddress, bytes2 contractName, uint defaultIncentive ); /// @dev Gets Total number of categories added till now function totalCategories() external view returns(uint numberOfCategories); /// @dev Updates category details /// @param _categoryId Category id that needs to be updated /// @param _name Category name /// @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. /// @param _allowedToCreateProposal Member roles allowed to create the proposal /// @param _majorityVotePerc Majority Vote threshold for Each voting layer /// @param _quorumPerc minimum threshold percentage required in voting to calculate result /// @param _closingTime Vote closing time for Each voting layer /// @param _actionHash hash of details containing the action that has to be performed after proposal is accepted /// @param _contractAddress address of contract to call after proposal is accepted /// @param _contractName name of contract to be called after proposal is accepted /// @param _incentives rewards to distributed after proposal is accepted function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public; } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/Governed.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMaster { function getLatestAddress(bytes2 _module) public view returns(address); } contract Governed { address public masterAddress; // Name of the dApp, needs to be set by contracts inheriting this contract /// @dev modifier that allows only the authorized addresses to execute the function modifier onlyAuthorizedToGovern() { IMaster ms = IMaster(masterAddress); require(ms.getLatestAddress("GV") == msg.sender, "Not authorized"); _; } /// @dev checks if an address is authorized to govern function isAuthorizedToGovern(address _toCheck) public view returns(bool) { IMaster ms = IMaster(masterAddress); return (ms.getLatestAddress("GV") == _toCheck); } } // File: nexusmutual-contracts/contracts/INXMMaster.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract INXMMaster { address public tokenAddress; address public owner; uint public pauseTime; function delegateCallBack(bytes32 myid) external; function masterInitialized() public view returns(bool); function isInternal(address _add) public view returns(bool); function isPause() public view returns(bool check); function isOwner(address _add) public view returns(bool); function isMember(address _add) public view returns(bool); function checkIsAuthToGoverned(address _add) public view returns(bool); function updatePauseTime(uint _time) public; function dAppLocker() public view returns(address _add); function dAppToken() public view returns(address _add); function getLatestAddress(bytes2 _contractName) public view returns(address payable contractAddress); } // File: nexusmutual-contracts/contracts/Iupgradable.sol pragma solidity 0.5.7; contract Iupgradable { INXMMaster public ms; address public nxMasterAddress; modifier onlyInternal { require(ms.isInternal(msg.sender)); _; } modifier isMemberAndcheckPause { require(ms.isPause() == false && ms.isMember(msg.sender) == true); _; } modifier onlyOwner { require(ms.isOwner(msg.sender)); _; } modifier checkPause { require(ms.isPause() == false); _; } modifier isMember { require(ms.isMember(msg.sender), "Not member"); _; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public; /** * @dev change master address * @param _masterAddress is the new address */ function changeMasterAddress(address _masterAddress) public { if (address(ms) != address(0)) { require(address(ms) == msg.sender, "Not master"); } ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } } // File: nexusmutual-contracts/contracts/interfaces/IPooledStaking.sol pragma solidity ^0.5.7; interface IPooledStaking { function accumulateReward(address contractAddress, uint amount) external; function pushBurn(address contractAddress, uint amount) external; function hasPendingActions() external view returns (bool); function contractStake(address contractAddress) external view returns (uint); function stakerReward(address staker) external view returns (uint); function stakerDeposit(address staker) external view returns (uint); function stakerContractStake(address staker, address contractAddress) external view returns (uint); function withdraw(uint amount) external; function stakerMaxWithdrawable(address stakerAddress) external view returns (uint); function withdrawReward(address stakerAddress) external; } // File: nexusmutual-contracts/contracts/TokenFunctions.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenFunctions is Iupgradable { using SafeMath for uint; MCR internal m1; MemberRoles internal mr; NXMToken public tk; TokenController internal tc; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; PoolData internal pd; IPooledStaking pooledStaking; event BurnCATokens(uint claimId, address addr, uint amount); /** * @dev Rewards stakers on purchase of cover on smart contract. * @param _contractAddress smart contract address. * @param _coverPriceNXM cover price in NXM. */ function pushStakerRewards(address _contractAddress, uint _coverPriceNXM) external onlyInternal { uint rewardValue = _coverPriceNXM.mul(td.stakerCommissionPer()).div(100); pooledStaking.accumulateReward(_contractAddress, rewardValue); } /** * @dev Deprecated in favor of burnStakedTokens */ function burnStakerLockedToken(uint, bytes4, uint) external { // noop } /** * @dev Burns tokens staked on smart contract covered by coverId. Called when a payout is succesfully executed. * @param coverId cover id * @param coverCurrency cover currency * @param sumAssured amount of $curr to burn */ function burnStakedTokens(uint coverId, bytes4 coverCurrency, uint sumAssured) external onlyInternal { (, address scAddress) = qd.getscAddressOfCover(coverId); uint tokenPrice = m1.calculateTokenPrice(coverCurrency); uint burnNXMAmount = sumAssured.mul(1e18).div(tokenPrice); pooledStaking.pushBurn(scAddress, burnNXMAmount); } /** * @dev Gets the total staked NXM tokens against * Smart contract by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function deprecated_getTotalStakedTokensOnSmartContract( address _stakedContractAddress ) external view returns(uint) { uint stakedAmount = 0; address stakerAddress; uint staketLen = td.getStakedContractStakersLength(_stakedContractAddress); for (uint i = 0; i < staketLen; i++) { stakerAddress = td.getStakedContractStakerByIndex(_stakedContractAddress, i); uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(stakerAddress, _stakedContractAddress, stakerIndex); stakedAmount = stakedAmount.add(currentlyStaked); } return stakedAmount; } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function getUserLockedCNTokens(address _of, uint _coverId) external view returns(uint) { return _getUserLockedCNTokens(_of, _coverId); } /** * @dev to get the all the cover locked tokens of a user * @param _of is the user address in concern * @return amount locked */ function getUserAllLockedCNTokens(address _of) external view returns(uint amount) { for (uint i = 0; i < qd.getUserCoverLength(_of); i++) { amount = amount.add(_getUserLockedCNTokens(_of, qd.getAllCoversOfUser(_of)[i])); } } /** * @dev Returns amount of NXM Tokens locked as Cover Note against given coverId. * @param _coverId coverId of the cover. */ function getLockedCNAgainstCover(uint _coverId) external view returns(uint) { return _getLockedCNAgainstCover(_coverId); } /** * @dev Returns total amount of staked NXM Tokens on all smart contracts. * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllLockedTokens(address _stakerAddress) external view returns (uint amount) { uint stakedAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); uint currentlyStaked; (, currentlyStaked) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, scAddress, i); stakedAmount = stakedAmount.add(currentlyStaked); } amount = stakedAmount; } /** * @dev Returns total unlockable amount of staked NXM Tokens on all smart contract . * @param _stakerAddress address of the Staker. */ function deprecated_getStakerAllUnlockableStakedTokens( address _stakerAddress ) external view returns (uint amount) { uint unlockableAmount = 0; address scAddress; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = unlockableAmount.add( _deprecated_getStakerUnlockableTokensOnSmartContract(_stakerAddress, scAddress, scIndex)); } amount = unlockableAmount; } /** * @dev Change Dependent Contract Address */ function changeDependentContractAddress() public { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tc = TokenController(ms.getLatestAddress("TC")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); gv = Governance(ms.getLatestAddress("GV")); mr = MemberRoles(ms.getLatestAddress("MR")); pd = PoolData(ms.getLatestAddress("PD")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /** * @dev Gets the Token price in a given currency * @param curr Currency name. * @return price Token Price. */ function getTokenPrice(bytes4 curr) public view returns(uint price) { price = m1.calculateTokenPrice(curr); } /** * @dev Set the flag to check if cover note is deposited against the cover id * @param coverId Cover Id. */ function depositCN(uint coverId) public onlyInternal returns (bool success) { require(_getLockedCNAgainstCover(coverId) > 0, "No cover note available"); td.setDepositCN(coverId, true); success = true; } /** * @param _of address of Member * @param _coverId Cover Id * @param _lockTime Pending Time + Cover Period 7*1 days */ function extendCNEPOff(address _of, uint _coverId, uint _lockTime) public onlyInternal { uint timeStamp = now.add(_lockTime); uint coverValidUntil = qd.getValidityOfCover(_coverId); if (timeStamp >= coverValidUntil) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); tc.extendLockOf(_of, reason, timeStamp); } } /** * @dev to burn the deposited cover tokens * @param coverId is id of cover whose tokens have to be burned * @return the status of the successful burning */ function burnDepositCN(uint coverId) public onlyInternal returns (bool success) { address _of = qd.getCoverMemberAddress(coverId); uint amount; (amount, ) = td.depositedCN(coverId); amount = (amount.mul(50)).div(100); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); tc.burnLockedTokens(_of, reason, amount); success = true; } /** * @dev Unlocks covernote locked against a given cover * @param coverId id of cover */ function unlockCN(uint coverId) public onlyInternal { (, bool isDeposited) = td.depositedCN(coverId); require(!isDeposited,"Cover note is deposited and can not be released"); uint lockedCN = _getLockedCNAgainstCover(coverId); if (lockedCN != 0) { address coverHolder = qd.getCoverMemberAddress(coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, coverId)); tc.releaseLockedTokens(coverHolder, reason, lockedCN); } } /** * @dev Burns tokens used for fraudulent voting against a claim * @param claimid Claim Id. * @param _value number of tokens to be burned * @param _of Claim Assessor's address. */ function burnCAToken(uint claimid, uint _value, address _of) public { require(ms.checkIsAuthToGoverned(msg.sender)); tc.burnLockedTokens(_of, "CLA", _value); emit BurnCATokens(claimid, _of, _value); } /** * @dev to lock cover note tokens * @param coverNoteAmount is number of tokens to be locked * @param coverPeriod is cover period in concern * @param coverId is the cover id of cover in concern * @param _of address whose tokens are to be locked */ function lockCN( uint coverNoteAmount, uint coverPeriod, uint coverId, address _of ) public onlyInternal { uint validity = (coverPeriod * 1 days).add(td.lockTokenTimeAfterCoverExp()); bytes32 reason = keccak256(abi.encodePacked("CN", _of, coverId)); td.setDepositCNAmount(coverId, coverNoteAmount); tc.lockOf(_of, reason, coverNoteAmount, validity); } /** * @dev to check if a member is locked for member vote * @param _of is the member address in concern * @return the boolean status */ function isLockedForMemberVote(address _of) public view returns(bool) { return now < tk.isLockedForMV(_of); } /** * @dev Internal function to gets amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { amount = _deprecated_getStakerLockedTokensOnSmartContract(_stakerAddress, _stakedContractAddress, _stakedContractIndex); } /** * @dev Function to gets unlockable amount of locked NXM * tokens, staked against smartcontract by index * @param stakerAddress address of staker * @param stakedContractAddress staked contract address * @param stakerIndex index of staking */ function deprecated_getStakerUnlockableTokensOnSmartContract ( address stakerAddress, address stakedContractAddress, uint stakerIndex ) public view returns (uint) { return _deprecated_getStakerUnlockableTokensOnSmartContract(stakerAddress, stakedContractAddress, td.getStakerStakedContractIndex(stakerAddress, stakerIndex)); } /** * @dev releases unlockable staked tokens to staker */ function deprecated_unlockStakerUnlockableTokens(address _stakerAddress) public checkPause { uint unlockableAmount; address scAddress; bytes32 reason; uint scIndex; for (uint i = 0; i < td.getStakerStakedContractLength(_stakerAddress); i++) { scAddress = td.getStakerStakedContractByIndex(_stakerAddress, i); scIndex = td.getStakerStakedContractIndex(_stakerAddress, i); unlockableAmount = _deprecated_getStakerUnlockableTokensOnSmartContract( _stakerAddress, scAddress, scIndex); td.setUnlockableBeforeLastBurnTokens(_stakerAddress, i, 0); td.pushUnlockedStakedTokens(_stakerAddress, i, unlockableAmount); reason = keccak256(abi.encodePacked("UW", _stakerAddress, scAddress, scIndex)); tc.releaseLockedTokens(_stakerAddress, reason, unlockableAmount); } } /** * @dev to get tokens of staker locked before burning that are allowed to burn * @param stakerAdd is the address of the staker * @param stakedAdd is the address of staked contract in concern * @param stakerIndex is the staker index in concern * @return amount of unlockable tokens * @return amount of tokens that can burn */ function _deprecated_unlockableBeforeBurningAndCanBurn( address stakerAdd, address stakedAdd, uint stakerIndex ) public view returns (uint amount, uint canBurn) { uint dateAdd; uint initialStake; uint totalBurnt; uint ub; (, , dateAdd, initialStake, , totalBurnt, ub) = td.stakerStakedContracts(stakerAdd, stakerIndex); canBurn = _deprecated_calculateStakedTokens(initialStake, now.sub(dateAdd).div(1 days), td.scValidDays()); // Can't use SafeMaths for int. int v = int(initialStake - (canBurn) - (totalBurnt) - ( td.getStakerUnlockedStakedTokens(stakerAdd, stakerIndex)) - (ub)); uint currentLockedTokens = _deprecated_getStakerLockedTokensOnSmartContract( stakerAdd, stakedAdd, td.getStakerStakedContractIndex(stakerAdd, stakerIndex)); if (v < 0) { v = 0; } amount = uint(v); if (canBurn > currentLockedTokens.sub(amount).sub(ub)) { canBurn = currentLockedTokens.sub(amount).sub(ub); } } /** * @dev to get tokens of staker that are unlockable * @param _stakerAddress is the address of the staker * @param _stakedContractAddress is the address of staked contract in concern * @param _stakedContractIndex is the staked contract index in concern * @return amount of unlockable tokens */ function _deprecated_getStakerUnlockableTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint amount) { uint initialStake; uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); uint burnt; (, , , initialStake, , burnt,) = td.stakerStakedContracts(_stakerAddress, stakerIndex); uint alreadyUnlocked = td.getStakerUnlockedStakedTokens(_stakerAddress, stakerIndex); uint currentStakedTokens; (, currentStakedTokens) = _deprecated_unlockableBeforeBurningAndCanBurn(_stakerAddress, _stakedContractAddress, stakerIndex); amount = initialStake.sub(currentStakedTokens).sub(alreadyUnlocked).sub(burnt); } /** * @dev Internal function to get the amount of locked NXM tokens, * staked against smartcontract by index * @param _stakerAddress address of user * @param _stakedContractAddress staked contract address * @param _stakedContractIndex index of staking */ function _deprecated_getStakerLockedTokensOnSmartContract ( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex ) internal view returns (uint amount) { bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); amount = tc.tokensLocked(_stakerAddress, reason); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _coverId coverId of the cover. */ function _getLockedCNAgainstCover(uint _coverId) internal view returns(uint) { address coverHolder = qd.getCoverMemberAddress(_coverId); bytes32 reason = keccak256(abi.encodePacked("CN", coverHolder, _coverId)); return tc.tokensLockedAtTime(coverHolder, reason, now); } /** * @dev Returns amount of NXM Tokens locked as Cover Note for given coverId. * @param _of address of the coverHolder. * @param _coverId coverId of the cover. */ function _getUserLockedCNTokens(address _of, uint _coverId) internal view returns(uint) { bytes32 reason = keccak256(abi.encodePacked("CN", _of, _coverId)); return tc.tokensLockedAtTime(_of, reason, now); } /** * @dev Internal function to gets remaining amount of staked NXM tokens, * against smartcontract by index * @param _stakeAmount address of user * @param _stakeDays staked contract address * @param _validDays index of staking */ function _deprecated_calculateStakedTokens( uint _stakeAmount, uint _stakeDays, uint _validDays ) internal pure returns (uint amount) { if (_validDays > _stakeDays) { uint rf = ((_validDays.sub(_stakeDays)).mul(100000)).div(_validDays); amount = (rf.mul(_stakeAmount)).div(100000); } else { amount = 0; } } /** * @dev Gets the total staked NXM tokens against Smart contract * by all stakers * @param _stakedContractAddress smart contract address. * @return amount total staked NXM tokens. */ function _deprecated_burnStakerTokenLockedAgainstSmartContract( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _amount ) internal { uint stakerIndex = td.getStakedContractStakerIndex( _stakedContractAddress, _stakedContractIndex); td.pushBurnedTokens(_stakerAddress, stakerIndex, _amount); bytes32 reason = keccak256(abi.encodePacked("UW", _stakerAddress, _stakedContractAddress, _stakedContractIndex)); tc.burnLockedTokens(_stakerAddress, reason, _amount); } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IMemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IMemberRoles { event MemberRole(uint256 indexed roleId, bytes32 roleName, string roleDescription); /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole(bytes32 _roleName, string memory _roleDescription, address _authorized) public; /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole(address _memberAddress, uint _roleId, bool _active) public; /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _authorized New authorized address against role id function changeAuthorized(uint _roleId, address _authorized) public; /// @dev Return number of member roles function totalRoles() public view returns(uint256); /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory allMemberAddress); /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberAddress.length Member length function numberOfMembers(uint _memberRoleId) public view returns(uint); /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address); /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory assignedRoles); /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool); } // File: nexusmutual-contracts/contracts/external/ERC1132/IERC1132.sol pragma solidity 0.5.7; /** * @title ERC1132 interface * @dev see https://github.com/ethereum/EIPs/issues/1132 */ contract IERC1132 { /** * @dev Reasons why a user's tokens have been locked */ mapping(address => bytes32[]) public lockReason; /** * @dev locked token structure */ struct LockToken { uint256 amount; uint256 validity; bool claimed; } /** * @dev Holds number & validity of tokens locked for a given reason for * a specified address */ mapping(address => mapping(bytes32 => LockToken)) public locked; /** * @dev Records data of all the tokens Locked */ event Locked( address indexed _of, bytes32 indexed _reason, uint256 _amount, uint256 _validity ); /** * @dev Records data of all the tokens unlocked */ event Unlocked( address indexed _of, bytes32 indexed _reason, uint256 _amount ); /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public returns (bool); /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount); /** * @dev Returns total tokens held by an address (locked + transferable) * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount); /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public returns (bool); /** * @dev Increase number of tokens locked for a specified reason * @param _reason The reason to lock tokens * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public returns (bool); /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount); /** * @dev Unlocks the unlockable tokens of a specified address * @param _of Address of user, claiming back unlockable tokens */ function unlock(address _of) public returns (uint256 unlockableTokens); /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens); } // File: nexusmutual-contracts/contracts/TokenController.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenController is IERC1132, Iupgradable { using SafeMath for uint256; event Burned(address indexed member, bytes32 lockedUnder, uint256 amount); NXMToken public token; IPooledStaking public pooledStaking; uint public minCALockTime = uint(30).mul(1 days); bytes32 private constant CLA = bytes32("CLA"); /** * @dev Just for interface */ function changeDependentContractAddress() public { token = NXMToken(ms.tokenAddress()); pooledStaking = IPooledStaking(ms.getLatestAddress('PS')); } /** * @dev to change the operator address * @param _newOperator is the new address of operator */ function changeOperator(address _newOperator) public onlyInternal { token.changeOperator(_newOperator); } /** * @dev Proxies token transfer through this contract to allow staking when members are locked for voting * @param _from Source address * @param _to Destination address * @param _value Amount to transfer */ function operatorTransfer(address _from, address _to, uint _value) onlyInternal external returns (bool) { require(msg.sender == address(pooledStaking), "Call is only allowed from PooledStaking address"); require(token.operatorTransfer(_from, _value), "Operator transfer failed"); require(token.transfer(_to, _value), "Internal transfer failed"); return true; } /** * @dev Locks a specified amount of tokens, * for CLA reason and for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function lock(bytes32 _reason, uint256 _amount, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(minCALockTime <= _time,"Should lock for minimum time"); // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(msg.sender, _reason, _amount, _time); return true; } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds * @param _of address whose tokens are to be locked */ function lockOf(address _of, bytes32 _reason, uint256 _amount, uint256 _time) public onlyInternal returns (bool) { // If tokens are already locked, then functions extendLock or // increaseLockAmount should be used to make any changes _lock(_of, _reason, _amount, _time); return true; } /** * @dev Extends lock for reason CLA for a specified time * @param _reason The reason to lock tokens, currently restricted to CLA * @param _time Lock extension time in seconds */ function extendLock(bytes32 _reason, uint256 _time) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); _extendLock(msg.sender, _reason, _time); return true; } /** * @dev Extends lock for a specified reason and time * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function extendLockOf(address _of, bytes32 _reason, uint256 _time) public onlyInternal returns (bool) { _extendLock(_of, _reason, _time); return true; } /** * @dev Increase number of tokens locked for a CLA reason * @param _reason The reason to lock tokens, currently restricted to CLA * @param _amount Number of tokens to be increased */ function increaseLockAmount(bytes32 _reason, uint256 _amount) public checkPause returns (bool) { require(_reason == CLA,"Restricted to reason CLA"); require(_tokensLocked(msg.sender, _reason) > 0); token.operatorTransfer(msg.sender, _amount); locked[msg.sender][_reason].amount = locked[msg.sender][_reason].amount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Locked(msg.sender, _reason, _amount, locked[msg.sender][_reason].validity); return true; } /** * @dev burns tokens of an address * @param _of is the address to burn tokens of * @param amount is the amount to burn * @return the boolean status of the burning process */ function burnFrom (address _of, uint amount) public onlyInternal returns (bool) { return token.burnFrom(_of, amount); } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _burnLockedTokens(_of, _reason, _amount); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function reduceLock(address _of, bytes32 _reason, uint256 _time) public onlyInternal { _reduceLock(_of, _reason, _time); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) public onlyInternal { _releaseLockedTokens(_of, _reason, _amount); } /** * @dev Adds an address to whitelist maintained in the contract * @param _member address to add to whitelist */ function addToWhitelist(address _member) public onlyInternal { token.addToWhiteList(_member); } /** * @dev Removes an address from the whitelist in the token * @param _member address to remove */ function removeFromWhitelist(address _member) public onlyInternal { token.removeFromWhiteList(_member); } /** * @dev Mints new token for an address * @param _member address to reward the minted tokens * @param _amount number of tokens to mint */ function mint(address _member, uint _amount) public onlyInternal { token.mint(_member, _amount); } /** * @dev Lock the user's tokens * @param _of user's address. */ function lockForMemberVote(address _of, uint _days) public onlyInternal { token.lockForMemberVote(_of, _days); } /** * @dev Unlocks the unlockable tokens against CLA of a specified address * @param _of Address of user, claiming back unlockable tokens against CLA */ function unlock(address _of) public checkPause returns (uint256 unlockableTokens) { unlockableTokens = _tokensUnlockable(_of, CLA); if (unlockableTokens > 0) { locked[_of][CLA].claimed = true; emit Unlocked(_of, CLA, unlockableTokens); require(token.transfer(_of, unlockableTokens)); } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MNCLT") { minCALockTime = val.mul(1 days); } else { revert("Invalid param code"); } } /** * @dev Gets the validity of locked tokens of a specified address * @param _of The address to query the validity * @param reason reason for which tokens were locked */ function getLockedTokensValidity(address _of, bytes32 reason) public view returns (uint256 validity) { validity = locked[_of][reason].validity; } /** * @dev Gets the unlockable tokens of a specified address * @param _of The address to query the the unlockable token count of */ function getUnlockableTokens(address _of) public view returns (uint256 unlockableTokens) { for (uint256 i = 0; i < lockReason[_of].length; i++) { unlockableTokens = unlockableTokens.add(_tokensUnlockable(_of, lockReason[_of][i])); } } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function tokensLocked(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensLocked(_of, _reason); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function tokensUnlockable(address _of, bytes32 _reason) public view returns (uint256 amount) { return _tokensUnlockable(_of, _reason); } function totalSupply() public view returns (uint256) { return token.totalSupply(); } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) public view returns (uint256 amount) { return _tokensLockedAtTime(_of, _reason, _time); } /** * @dev Returns the total amount of tokens held by an address: * transferable + locked + staked for pooled staking - pending burns. * Used by Claims and Governance in member voting to calculate the user's vote weight. * * @param _of The address to query the total balance of * @param _of The address to query the total balance of */ function totalBalanceOf(address _of) public view returns (uint256 amount) { amount = token.balanceOf(_of); for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLocked(_of, lockReason[_of][i])); } uint stakerReward = pooledStaking.stakerReward(_of); uint stakerDeposit = pooledStaking.stakerDeposit(_of); amount = amount.add(stakerDeposit).add(stakerReward); } /** * @dev Returns the total locked tokens at time * Returns the total amount of locked and staked tokens at a given time. Used by MemberRoles to check eligibility * for withdraw / switch membership. Includes tokens locked for Claim Assessment and staked for Risk Assessment. * Does not take into account pending burns. * * @param _of member whose locked tokens are to be calculate * @param _time timestamp when the tokens should be locked */ function totalLockedBalance(address _of, uint256 _time) public view returns (uint256 amount) { for (uint256 i = 0; i < lockReason[_of].length; i++) { amount = amount.add(_tokensLockedAtTime(_of, lockReason[_of][i], _time)); } amount = amount.add(pooledStaking.stakerDeposit(_of)); } /** * @dev Locks a specified amount of tokens against an address, * for a specified reason and time * @param _of address whose tokens are to be locked * @param _reason The reason to lock tokens * @param _amount Number of tokens to be locked * @param _time Lock time in seconds */ function _lock(address _of, bytes32 _reason, uint256 _amount, uint256 _time) internal { require(_tokensLocked(_of, _reason) == 0); require(_amount != 0); if (locked[_of][_reason].amount == 0) { lockReason[_of].push(_reason); } require(token.operatorTransfer(_of, _amount)); uint256 validUntil = now.add(_time); //solhint-disable-line locked[_of][_reason] = LockToken(_amount, validUntil, false); emit Locked(_of, _reason, _amount, validUntil); } /** * @dev Returns tokens locked for a specified address for a * specified reason * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for */ function _tokensLocked(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (!locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Returns tokens locked for a specified address for a * specified reason at a specific time * * @param _of The address whose tokens are locked * @param _reason The reason to query the lock tokens for * @param _time The timestamp to query the lock tokens for */ function _tokensLockedAtTime(address _of, bytes32 _reason, uint256 _time) internal view returns (uint256 amount) { if (locked[_of][_reason].validity > _time) { amount = locked[_of][_reason].amount; } } /** * @dev Extends lock for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock extension time in seconds */ function _extendLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.add(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev reduce lock duration for a specified reason and time * @param _of The address whose tokens are locked * @param _reason The reason to lock tokens * @param _time Lock reduction time in seconds */ function _reduceLock(address _of, bytes32 _reason, uint256 _time) internal { require(_tokensLocked(_of, _reason) > 0); emit Unlocked(_of, _reason, locked[_of][_reason].amount); locked[_of][_reason].validity = locked[_of][_reason].validity.sub(_time); emit Locked(_of, _reason, locked[_of][_reason].amount, locked[_of][_reason].validity); } /** * @dev Returns unlockable tokens for a specified address for a specified reason * @param _of The address to query the the unlockable token count of * @param _reason The reason to query the unlockable tokens for */ function _tokensUnlockable(address _of, bytes32 _reason) internal view returns (uint256 amount) { if (locked[_of][_reason].validity <= now && !locked[_of][_reason].claimed) { amount = locked[_of][_reason].amount; } } /** * @dev Burns locked tokens of a user * @param _of address whose tokens are to be burned * @param _reason lock reason for which tokens are to be burned * @param _amount amount of tokens to burn */ function _burnLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } token.burn(_amount); emit Burned(_of, _reason, _amount); } /** * @dev Released locked tokens of an address locked for a specific reason * @param _of address whose tokens are to be released from lock * @param _reason reason of the lock * @param _amount amount of tokens to release */ function _releaseLockedTokens(address _of, bytes32 _reason, uint256 _amount) internal { uint256 amount = _tokensLocked(_of, _reason); require(amount >= _amount); if (amount == _amount) { locked[_of][_reason].claimed = true; } locked[_of][_reason].amount = locked[_of][_reason].amount.sub(_amount); if (locked[_of][_reason].amount == 0) { _removeReason(_of, _reason); } require(token.transfer(_of, _amount)); emit Unlocked(_of, _reason, _amount); } function _removeReason(address _of, bytes32 _reason) internal { uint len = lockReason[_of].length; for (uint i = 0; i < len; i++) { if (lockReason[_of][i] == _reason) { lockReason[_of][i] = lockReason[_of][len.sub(1)]; lockReason[_of].pop(); break; } } } } // File: nexusmutual-contracts/contracts/ClaimsData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ClaimsData is Iupgradable { using SafeMath for uint; struct Claim { uint coverId; uint dateUpd; } struct Vote { address voter; uint tokens; uint claimId; int8 verdict; bool rewardClaimed; } struct ClaimsPause { uint coverid; uint dateUpd; bool submit; } struct ClaimPauseVoting { uint claimid; uint pendingTime; bool voting; } struct RewardDistributed { uint lastCAvoteIndex; uint lastMVvoteIndex; } struct ClaimRewardDetails { uint percCA; uint percMV; uint tokenToBeDist; } struct ClaimTotalTokens { uint accept; uint deny; } struct ClaimRewardStatus { uint percCA; uint percMV; } ClaimRewardStatus[] internal rewardStatus; Claim[] internal allClaims; Vote[] internal allvotes; ClaimsPause[] internal claimPause; ClaimPauseVoting[] internal claimPauseVotingEP; mapping(address => RewardDistributed) internal voterVoteRewardReceived; mapping(uint => ClaimRewardDetails) internal claimRewardDetail; mapping(uint => ClaimTotalTokens) internal claimTokensCA; mapping(uint => ClaimTotalTokens) internal claimTokensMV; mapping(uint => int8) internal claimVote; mapping(uint => uint) internal claimsStatus; mapping(uint => uint) internal claimState12Count; mapping(uint => uint[]) internal claimVoteCA; mapping(uint => uint[]) internal claimVoteMember; mapping(address => uint[]) internal voteAddressCA; mapping(address => uint[]) internal voteAddressMember; mapping(address => uint[]) internal allClaimsByAddress; mapping(address => mapping(uint => uint)) internal userClaimVoteCA; mapping(address => mapping(uint => uint)) internal userClaimVoteMember; mapping(address => uint) public userClaimVotePausedOn; uint internal claimPauseLastsubmit; uint internal claimStartVotingFirstIndex; uint public pendingClaimStart; uint public claimDepositTime; uint public maxVotingTime; uint public minVotingTime; uint public payoutRetryTime; uint public claimRewardPerc; uint public minVoteThreshold; uint public maxVoteThreshold; uint public majorityConsensus; uint public pauseDaysCA; event ClaimRaise( uint indexed coverId, address indexed userAddress, uint claimId, uint dateSubmit ); event VoteCast( address indexed userAddress, uint indexed claimId, bytes4 indexed typeOf, uint tokens, uint submitDate, int8 verdict ); constructor() public { pendingClaimStart = 1; maxVotingTime = 48 * 1 hours; minVotingTime = 12 * 1 hours; payoutRetryTime = 24 * 1 hours; allvotes.push(Vote(address(0), 0, 0, 0, false)); allClaims.push(Claim(0, 0)); claimDepositTime = 7 days; claimRewardPerc = 20; minVoteThreshold = 5; maxVoteThreshold = 10; majorityConsensus = 70; pauseDaysCA = 3 days; _addRewardIncentive(); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function setpendingClaimStart(uint _start) external onlyInternal { require(pendingClaimStart <= _start); pendingClaimStart = _start; } /** * @dev Updates the max vote index for which claim assessor has received reward * @param _voter address of the voter. * @param caIndex last index till which reward was distributed for CA */ function setRewardDistributedIndexCA(address _voter, uint caIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastCAvoteIndex = caIndex; } /** * @dev Used to pause claim assessor activity for 3 days * @param user Member address whose claim voting ability needs to be paused */ function setUserClaimVotePausedOn(address user) external { require(ms.checkIsAuthToGoverned(msg.sender)); userClaimVotePausedOn[user] = now; } /** * @dev Updates the max vote index for which member has received reward * @param _voter address of the voter. * @param mvIndex last index till which reward was distributed for member */ function setRewardDistributedIndexMV(address _voter, uint mvIndex) external onlyInternal { voterVoteRewardReceived[_voter].lastMVvoteIndex = mvIndex; } /** * @param claimid claim id. * @param percCA reward Percentage reward for claim assessor * @param percMV reward Percentage reward for members * @param tokens total tokens to be rewarded */ function setClaimRewardDetail( uint claimid, uint percCA, uint percMV, uint tokens ) external onlyInternal { claimRewardDetail[claimid].percCA = percCA; claimRewardDetail[claimid].percMV = percMV; claimRewardDetail[claimid].tokenToBeDist = tokens; } /** * @dev Sets the reward claim status against a vote id. * @param _voteid vote Id. * @param claimed true if reward for vote is claimed, else false. */ function setRewardClaimed(uint _voteid, bool claimed) external onlyInternal { allvotes[_voteid].rewardClaimed = claimed; } /** * @dev Sets the final vote's result(either accepted or declined)of a claim. * @param _claimId Claim Id. * @param _verdict 1 if claim is accepted,-1 if declined. */ function changeFinalVerdict(uint _claimId, int8 _verdict) external onlyInternal { claimVote[_claimId] = _verdict; } /** * @dev Creates a new claim. */ function addClaim( uint _claimId, uint _coverId, address _from, uint _nowtime ) external onlyInternal { allClaims.push(Claim(_coverId, _nowtime)); allClaimsByAddress[_from].push(_claimId); } /** * @dev Add Vote's details of a given claim. */ function addVote( address _voter, uint _tokens, uint claimId, int8 _verdict ) external onlyInternal { allvotes.push(Vote(_voter, _tokens, claimId, _verdict, false)); } /** * @dev Stores the id of the claim assessor vote given to a claim. * Maintains record of all votes given by all the CA to a claim. * @param _claimId Claim Id to which vote has given by the CA. * @param _voteid Vote Id. */ function addClaimVoteCA(uint _claimId, uint _voteid) external onlyInternal { claimVoteCA[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Claim assessor's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the CA. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteCA( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteCA[_from][_claimId] = _voteid; voteAddressCA[_from].push(_voteid); } /** * @dev Stores the tokens locked by the Claim Assessors during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensCA(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensCA[_claimId].accept = claimTokensCA[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensCA[_claimId].deny = claimTokensCA[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the tokens locked by the Members during voting of a given claim. * @param _claimId Claim Id. * @param _vote 1 for accept and increases the tokens of claim as accept, * -1 for deny and increases the tokens of claim as deny. * @param _tokens Number of tokens. */ function setClaimTokensMV(uint _claimId, int8 _vote, uint _tokens) external onlyInternal { if (_vote == 1) claimTokensMV[_claimId].accept = claimTokensMV[_claimId].accept.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW if (_vote == -1) claimTokensMV[_claimId].deny = claimTokensMV[_claimId].deny.add(_tokens); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Stores the id of the member vote given to a claim. * Maintains record of all votes given by all the Members to a claim. * @param _claimId Claim Id to which vote has been given by the Member. * @param _voteid Vote Id. */ function addClaimVotemember(uint _claimId, uint _voteid) external onlyInternal { claimVoteMember[_claimId].push(_voteid); } /** * @dev Sets the id of the vote. * @param _from Member's address who has given the vote. * @param _claimId Claim Id for which vote has been given by the Member. * @param _voteid Vote Id which will be stored against the given _from and claimid. */ function setUserClaimVoteMember( address _from, uint _claimId, uint _voteid ) external onlyInternal { userClaimVoteMember[_from][_claimId] = _voteid; voteAddressMember[_from].push(_voteid); } /** * @dev Increases the count of failure until payout of a claim is successful. */ function updateState12Count(uint _claimId, uint _cnt) external onlyInternal { claimState12Count[_claimId] = claimState12Count[_claimId].add(_cnt); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Sets status of a claim. * @param _claimId Claim Id. * @param _stat Status number. */ function setClaimStatus(uint _claimId, uint _stat) external onlyInternal { claimsStatus[_claimId] = _stat; } /** * @dev Sets the timestamp of a given claim at which the Claim's details has been updated. * @param _claimId Claim Id of claim which has been changed. * @param _dateUpd timestamp at which claim is updated. */ function setClaimdateUpd(uint _claimId, uint _dateUpd) external onlyInternal { allClaims[_claimId].dateUpd = _dateUpd; } /** @dev Queues Claims during Emergency Pause. */ function setClaimAtEmergencyPause( uint _coverId, uint _dateUpd, bool _submit ) external onlyInternal { claimPause.push(ClaimsPause(_coverId, _dateUpd, _submit)); } /** * @dev Set submission flag for Claims queued during emergency pause. * Set to true after EP is turned off and the claim is submitted . */ function setClaimSubmittedAtEPTrue(uint _index, bool _submit) external onlyInternal { claimPause[_index].submit = _submit; } /** * @dev Sets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function setFirstClaimIndexToSubmitAfterEP( uint _firstClaimIndexToSubmit ) external onlyInternal { claimPauseLastsubmit = _firstClaimIndexToSubmit; } /** * @dev Sets the pending vote duration for a claim in case of emergency pause. */ function setPendingClaimDetails( uint _claimId, uint _pendingTime, bool _voting ) external onlyInternal { claimPauseVotingEP.push(ClaimPauseVoting(_claimId, _pendingTime, _voting)); } /** * @dev Sets voting flag true after claim is reopened for voting after emergency pause. */ function setPendingClaimVoteStatus(uint _claimId, bool _vote) external onlyInternal { claimPauseVotingEP[_claimId].voting = _vote; } /** * @dev Sets the index from which claim needs to be * reopened when emergency pause is swithched off. */ function setFirstClaimIndexToStartVotingAfterEP( uint _claimStartVotingFirstIndex ) external onlyInternal { claimStartVotingFirstIndex = _claimStartVotingFirstIndex; } /** * @dev Calls Vote Event. */ function callVoteEvent( address _userAddress, uint _claimId, bytes4 _typeOf, uint _tokens, uint _submitDate, int8 _verdict ) external onlyInternal { emit VoteCast( _userAddress, _claimId, _typeOf, _tokens, _submitDate, _verdict ); } /** * @dev Calls Claim Event. */ function callClaimEvent( uint _coverId, address _userAddress, uint _claimId, uint _datesubmit ) external onlyInternal { emit ClaimRaise(_coverId, _userAddress, _claimId, _datesubmit); } /** * @dev Gets Uint Parameters by parameter code * @param code whose details we want * @return string value of the parameter * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns (bytes8 codeVal, uint val) { codeVal = code; if (code == "CAMAXVT") { val = maxVotingTime / (1 hours); } else if (code == "CAMINVT") { val = minVotingTime / (1 hours); } else if (code == "CAPRETRY") { val = payoutRetryTime / (1 hours); } else if (code == "CADEPT") { val = claimDepositTime / (1 days); } else if (code == "CAREWPER") { val = claimRewardPerc; } else if (code == "CAMINTH") { val = minVoteThreshold; } else if (code == "CAMAXTH") { val = maxVoteThreshold; } else if (code == "CACONPER") { val = majorityConsensus; } else if (code == "CAPAUSET") { val = pauseDaysCA / (1 days); } } /** * @dev Get claim queued during emergency pause by index. */ function getClaimOfEmergencyPauseByIndex( uint _index ) external view returns( uint coverId, uint dateUpd, bool submit ) { coverId = claimPause[_index].coverid; dateUpd = claimPause[_index].dateUpd; submit = claimPause[_index].submit; } /** * @dev Gets the Claim's details of given claimid. */ function getAllClaimsByIndex( uint _claimId ) external view returns( uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return( allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the vote id of a given claim of a given Claim Assessor. */ function getUserClaimVoteCA( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteCA[_add][_claimId]; } /** * @dev Gets the vote id of a given claim of a given member. */ function getUserClaimVoteMember( address _add, uint _claimId ) external view returns(uint idVote) { return userClaimVoteMember[_add][_claimId]; } /** * @dev Gets the count of all votes. */ function getAllVoteLength() external view returns(uint voteCount) { return allvotes.length.sub(1); //Start Index always from 1. } /** * @dev Gets the status number of a given claim. * @param _claimId Claim id. * @return statno Status Number. */ function getClaimStatusNumber(uint _claimId) external view returns(uint claimId, uint statno) { return (_claimId, claimsStatus[_claimId]); } /** * @dev Gets the reward percentage to be distributed for a given status id * @param statusNumber the number of type of status * @return percCA reward Percentage for claim assessor * @return percMV reward Percentage for members */ function getRewardStatus(uint statusNumber) external view returns(uint percCA, uint percMV) { return (rewardStatus[statusNumber].percCA, rewardStatus[statusNumber].percMV); } /** * @dev Gets the number of tries that have been made for a successful payout of a Claim. */ function getClaimState12Count(uint _claimId) external view returns(uint num) { num = claimState12Count[_claimId]; } /** * @dev Gets the last update date of a claim. */ function getClaimDateUpd(uint _claimId) external view returns(uint dateupd) { dateupd = allClaims[_claimId].dateUpd; } /** * @dev Gets all Claims created by a user till date. * @param _member user's address. * @return claimarr List of Claims id. */ function getAllClaimsByAddress(address _member) external view returns(uint[] memory claimarr) { return allClaimsByAddress[_member]; } /** * @dev Gets the number of tokens that has been locked * while giving vote to a claim by Claim Assessors. * @param _claimId Claim Id. * @return accept Total number of tokens when CA accepts the claim. * @return deny Total number of tokens when CA declines the claim. */ function getClaimsTokenCA( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensCA[_claimId].accept, claimTokensCA[_claimId].deny ); } /** * @dev Gets the number of tokens that have been * locked while assessing a claim as a member. * @param _claimId Claim Id. * @return accept Total number of tokens in acceptance of the claim. * @return deny Total number of tokens against the claim. */ function getClaimsTokenMV( uint _claimId ) external view returns( uint claimId, uint accept, uint deny ) { return ( _claimId, claimTokensMV[_claimId].accept, claimTokensMV[_claimId].deny ); } /** * @dev Gets the total number of votes cast as Claims assessor for/against a given claim */ function getCaClaimVotesToken(uint _claimId) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets the total number of tokens cast as a member for/against a given claim */ function getMemberClaimVotesToken( uint _claimId ) external view returns(uint claimId, uint cnt) { claimId = _claimId; cnt = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { cnt = cnt.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @dev Provides information of a vote when given its vote id. * @param _voteid Vote Id. */ function getVoteDetails(uint _voteid) external view returns( uint tokens, uint claimId, int8 verdict, bool rewardClaimed ) { return ( allvotes[_voteid].tokens, allvotes[_voteid].claimId, allvotes[_voteid].verdict, allvotes[_voteid].rewardClaimed ); } /** * @dev Gets the voter's address of a given vote id. */ function getVoterVote(uint _voteid) external view returns(address voter) { return allvotes[_voteid].voter; } /** * @dev Provides information of a Claim when given its claim id. * @param _claimId Claim Id. */ function getClaim( uint _claimId ) external view returns( uint claimId, uint coverId, int8 vote, uint status, uint dateUpd, uint state12Count ) { return ( _claimId, allClaims[_claimId].coverId, claimVote[_claimId], claimsStatus[_claimId], allClaims[_claimId].dateUpd, claimState12Count[_claimId] ); } /** * @dev Gets the total number of votes of a given claim. * @param _claimId Claim Id. * @param _ca if 1: votes given by Claim Assessors to a claim, * else returns the number of votes of given by Members to a claim. * @return len total number of votes for/against a given claim. */ function getClaimVoteLength( uint _claimId, uint8 _ca ) external view returns(uint claimId, uint len) { claimId = _claimId; if (_ca == 1) len = claimVoteCA[_claimId].length; else len = claimVoteMember[_claimId].length; } /** * @dev Gets the verdict of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return ver 1 if vote was given in favour,-1 if given in against. */ function getVoteVerdict( uint _claimId, uint _index, uint8 _ca ) external view returns(int8 ver) { if (_ca == 1) ver = allvotes[claimVoteCA[_claimId][_index]].verdict; else ver = allvotes[claimVoteMember[_claimId][_index]].verdict; } /** * @dev Gets the Number of tokens of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return tok Number of tokens. */ function getVoteToken( uint _claimId, uint _index, uint8 _ca ) external view returns(uint tok) { if (_ca == 1) tok = allvotes[claimVoteCA[_claimId][_index]].tokens; else tok = allvotes[claimVoteMember[_claimId][_index]].tokens; } /** * @dev Gets the Voter's address of a vote using claim id and index. * @param _ca 1 for vote given as a CA, else for vote given as a member. * @return voter Voter's address. */ function getVoteVoter( uint _claimId, uint _index, uint8 _ca ) external view returns(address voter) { if (_ca == 1) voter = allvotes[claimVoteCA[_claimId][_index]].voter; else voter = allvotes[claimVoteMember[_claimId][_index]].voter; } /** * @dev Gets total number of Claims created by a user till date. * @param _add User's address. */ function getUserClaimCount(address _add) external view returns(uint len) { len = allClaimsByAddress[_add].length; } /** * @dev Calculates number of Claims that are in pending state. */ function getClaimLength() external view returns(uint len) { len = allClaims.length.sub(pendingClaimStart); } /** * @dev Gets the Number of all the Claims created till date. */ function actualClaimLength() external view returns(uint len) { len = allClaims.length; } /** * @dev Gets details of a claim. * @param _index claim id = pending claim start + given index * @param _add User's address. * @return coverid cover against which claim has been submitted. * @return claimId Claim Id. * @return voteCA verdict of vote given as a Claim Assessor. * @return voteMV verdict of vote given as a Member. * @return statusnumber Status of claim. */ function getClaimFromNewStart( uint _index, address _add ) external view returns( uint coverid, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { uint i = pendingClaimStart.add(_index); coverid = allClaims[i].coverId; claimId = i; if (userClaimVoteCA[_add][i] > 0) voteCA = allvotes[userClaimVoteCA[_add][i]].verdict; else voteCA = 0; if (userClaimVoteMember[_add][i] > 0) voteMV = allvotes[userClaimVoteMember[_add][i]].verdict; else voteMV = 0; statusnumber = claimsStatus[i]; } /** * @dev Gets details of a claim of a user at a given index. */ function getUserClaimByIndex( uint _index, address _add ) external view returns( uint status, uint coverid, uint claimId ) { claimId = allClaimsByAddress[_add][_index]; status = claimsStatus[claimId]; coverid = allClaims[claimId].coverId; } /** * @dev Gets Id of all the votes given to a claim. * @param _claimId Claim Id. * @return ca id of all the votes given by Claim assessors to a claim. * @return mv id of all the votes given by members to a claim. */ function getAllVotesForClaim( uint _claimId ) external view returns( uint claimId, uint[] memory ca, uint[] memory mv ) { return (_claimId, claimVoteCA[_claimId], claimVoteMember[_claimId]); } /** * @dev Gets Number of tokens deposit in a vote using * Claim assessor's address and claim id. * @return tokens Number of deposited tokens. */ function getTokensClaim( address _of, uint _claimId ) external view returns( uint claimId, uint tokens ) { return (_claimId, allvotes[userClaimVoteCA[_of][_claimId]].tokens); } /** * @param _voter address of the voter. * @return lastCAvoteIndex last index till which reward was distributed for CA * @return lastMVvoteIndex last index till which reward was distributed for member */ function getRewardDistributedIndex( address _voter ) external view returns( uint lastCAvoteIndex, uint lastMVvoteIndex ) { return ( voterVoteRewardReceived[_voter].lastCAvoteIndex, voterVoteRewardReceived[_voter].lastMVvoteIndex ); } /** * @param claimid claim id. * @return perc_CA reward Percentage for claim assessor * @return perc_MV reward Percentage for members * @return tokens total tokens to be rewarded */ function getClaimRewardDetail( uint claimid ) external view returns( uint percCA, uint percMV, uint tokens ) { return ( claimRewardDetail[claimid].percCA, claimRewardDetail[claimid].percMV, claimRewardDetail[claimid].tokenToBeDist ); } /** * @dev Gets cover id of a claim. */ function getClaimCoverId(uint _claimId) external view returns(uint claimId, uint coverid) { return (_claimId, allClaims[_claimId].coverId); } /** * @dev Gets total number of tokens staked during voting by Claim Assessors. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or deny on the basis of verdict given as parameter). */ function getClaimVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteCA[_claimId].length; i++) { if (allvotes[claimVoteCA[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteCA[_claimId][i]].tokens); } } /** * @dev Gets total number of tokens staked during voting by Members. * @param _claimId Claim Id. * @param _verdict 1 to get total number of accept tokens, * -1 to get total number of deny tokens. * @return token token Number of tokens(either accept or * deny on the basis of verdict given as parameter). */ function getClaimMVote(uint _claimId, int8 _verdict) external view returns(uint claimId, uint token) { claimId = _claimId; token = 0; for (uint i = 0; i < claimVoteMember[_claimId].length; i++) { if (allvotes[claimVoteMember[_claimId][i]].verdict == _verdict) token = token.add(allvotes[claimVoteMember[_claimId][i]].tokens); } } /** * @param _voter address of voteid * @param index index to get voteid in CA */ function getVoteAddressCA(address _voter, uint index) external view returns(uint) { return voteAddressCA[_voter][index]; } /** * @param _voter address of voter * @param index index to get voteid in member vote */ function getVoteAddressMember(address _voter, uint index) external view returns(uint) { return voteAddressMember[_voter][index]; } /** * @param _voter address of voter */ function getVoteAddressCALength(address _voter) external view returns(uint) { return voteAddressCA[_voter].length; } /** * @param _voter address of voter */ function getVoteAddressMemberLength(address _voter) external view returns(uint) { return voteAddressMember[_voter].length; } /** * @dev Gets the Final result of voting of a claim. * @param _claimId Claim id. * @return verdict 1 if claim is accepted, -1 if declined. */ function getFinalVerdict(uint _claimId) external view returns(int8 verdict) { return claimVote[_claimId]; } /** * @dev Get number of Claims queued for submission during emergency pause. */ function getLengthOfClaimSubmittedAtEP() external view returns(uint len) { len = claimPause.length; } /** * @dev Gets the index from which claim needs to be * submitted when emergency pause is swithched off. */ function getFirstClaimIndexToSubmitAfterEP() external view returns(uint indexToSubmit) { indexToSubmit = claimPauseLastsubmit; } /** * @dev Gets number of Claims to be reopened for voting post emergency pause period. */ function getLengthOfClaimVotingPause() external view returns(uint len) { len = claimPauseVotingEP.length; } /** * @dev Gets claim details to be reopened for voting after emergency pause. */ function getPendingClaimDetailsByIndex( uint _index ) external view returns( uint claimId, uint pendingTime, bool voting ) { claimId = claimPauseVotingEP[_index].claimid; pendingTime = claimPauseVotingEP[_index].pendingTime; voting = claimPauseVotingEP[_index].voting; } /** * @dev Gets the index from which claim needs to be reopened when emergency pause is swithched off. */ function getFirstClaimIndexToStartVotingAfterEP() external view returns(uint firstindex) { firstindex = claimStartVotingFirstIndex; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "CAMAXVT") { _setMaxVotingTime(val * 1 hours); } else if (code == "CAMINVT") { _setMinVotingTime(val * 1 hours); } else if (code == "CAPRETRY") { _setPayoutRetryTime(val * 1 hours); } else if (code == "CADEPT") { _setClaimDepositTime(val * 1 days); } else if (code == "CAREWPER") { _setClaimRewardPerc(val); } else if (code == "CAMINTH") { _setMinVoteThreshold(val); } else if (code == "CAMAXTH") { _setMaxVoteThreshold(val); } else if (code == "CACONPER") { _setMajorityConsensus(val); } else if (code == "CAPAUSET") { _setPauseDaysCA(val * 1 days); } else { revert("Invalid param code"); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal {} /** * @dev Adds status under which a claim can lie. * @param percCA reward percentage for claim assessor * @param percMV reward percentage for members */ function _pushStatus(uint percCA, uint percMV) internal { rewardStatus.push(ClaimRewardStatus(percCA, percMV)); } /** * @dev adds reward incentive for all possible claim status for Claim assessors and members */ function _addRewardIncentive() internal { _pushStatus(0, 0); //0 Pending-Claim Assessor Vote _pushStatus(0, 0); //1 Pending-Claim Assessor Vote Denied, Pending Member Vote _pushStatus(0, 0); //2 Pending-CA Vote Threshold not Reached Accept, Pending Member Vote _pushStatus(0, 0); //3 Pending-CA Vote Threshold not Reached Deny, Pending Member Vote _pushStatus(0, 0); //4 Pending-CA Consensus not reached Accept, Pending Member Vote _pushStatus(0, 0); //5 Pending-CA Consensus not reached Deny, Pending Member Vote _pushStatus(100, 0); //6 Final-Claim Assessor Vote Denied _pushStatus(100, 0); //7 Final-Claim Assessor Vote Accepted _pushStatus(0, 100); //8 Final-Claim Assessor Vote Denied, MV Accepted _pushStatus(0, 100); //9 Final-Claim Assessor Vote Denied, MV Denied _pushStatus(0, 0); //10 Final-Claim Assessor Vote Accept, MV Nodecision _pushStatus(0, 0); //11 Final-Claim Assessor Vote Denied, MV Nodecision _pushStatus(0, 0); //12 Claim Accepted Payout Pending _pushStatus(0, 0); //13 Claim Accepted No Payout _pushStatus(0, 0); //14 Claim Accepted Payout Done } /** * @dev Sets Maximum time(in seconds) for which claim assessment voting is open */ function _setMaxVotingTime(uint _time) internal { maxVotingTime = _time; } /** * @dev Sets Minimum time(in seconds) for which claim assessment voting is open */ function _setMinVotingTime(uint _time) internal { minVotingTime = _time; } /** * @dev Sets Minimum vote threshold required */ function _setMinVoteThreshold(uint val) internal { minVoteThreshold = val; } /** * @dev Sets Maximum vote threshold required */ function _setMaxVoteThreshold(uint val) internal { maxVoteThreshold = val; } /** * @dev Sets the value considered as Majority Consenus in voting */ function _setMajorityConsensus(uint val) internal { majorityConsensus = val; } /** * @dev Sets the payout retry time */ function _setPayoutRetryTime(uint _time) internal { payoutRetryTime = _time; } /** * @dev Sets percentage of reward given for claim assessment */ function _setClaimRewardPerc(uint _val) internal { claimRewardPerc = _val; } /** * @dev Sets the time for which claim is deposited. */ function _setClaimDepositTime(uint _time) internal { claimDepositTime = _time; } /** * @dev Sets number of days claim assessment will be paused */ function _setPauseDaysCA(uint val) internal { pauseDaysCA = val; } } // File: nexusmutual-contracts/contracts/PoolData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract DSValue { function peek() public view returns (bytes32, bool); function read() public view returns (bytes32); } contract PoolData is Iupgradable { using SafeMath for uint; struct ApiId { bytes4 typeOf; bytes4 currency; uint id; uint64 dateAdd; uint64 dateUpd; } struct CurrencyAssets { address currAddress; uint baseMin; uint varMin; } struct InvestmentAssets { address currAddress; bool status; uint64 minHoldingPercX100; uint64 maxHoldingPercX100; uint8 decimals; } struct IARankDetails { bytes4 maxIACurr; uint64 maxRate; bytes4 minIACurr; uint64 minRate; } struct McrData { uint mcrPercx100; uint mcrEther; uint vFull; //Pool funds uint64 date; } IARankDetails[] internal allIARankDetails; McrData[] public allMCRData; bytes4[] internal allInvestmentCurrencies; bytes4[] internal allCurrencies; bytes32[] public allAPIcall; mapping(bytes32 => ApiId) public allAPIid; mapping(uint64 => uint) internal datewiseId; mapping(bytes16 => uint) internal currencyLastIndex; mapping(bytes4 => CurrencyAssets) internal allCurrencyAssets; mapping(bytes4 => InvestmentAssets) internal allInvestmentAssets; mapping(bytes4 => uint) internal caAvgRate; mapping(bytes4 => uint) internal iaAvgRate; address public notariseMCR; address public daiFeedAddress; uint private constant DECIMAL1E18 = uint(10) ** 18; uint public uniswapDeadline; uint public liquidityTradeCallbackTime; uint public lastLiquidityTradeTrigger; uint64 internal lastDate; uint public variationPercX100; uint public iaRatesTime; uint public minCap; uint public mcrTime; uint public a; uint public shockParameter; uint public c; uint public mcrFailTime; uint public ethVolumeLimit; uint public capReached; uint public capacityLimit; constructor(address _notariseAdd, address _daiFeedAdd, address _daiAdd) public { notariseMCR = _notariseAdd; daiFeedAddress = _daiFeedAdd; c = 5800000; a = 1028; mcrTime = 24 hours; mcrFailTime = 6 hours; allMCRData.push(McrData(0, 0, 0, 0)); minCap = 12000 * DECIMAL1E18; shockParameter = 50; variationPercX100 = 100; //1% iaRatesTime = 24 hours; //24 hours in seconds uniswapDeadline = 20 minutes; liquidityTradeCallbackTime = 4 hours; ethVolumeLimit = 4; capacityLimit = 10; allCurrencies.push("ETH"); allCurrencyAssets["ETH"] = CurrencyAssets(address(0), 1000 * DECIMAL1E18, 0); allCurrencies.push("DAI"); allCurrencyAssets["DAI"] = CurrencyAssets(_daiAdd, 50000 * DECIMAL1E18, 0); allInvestmentCurrencies.push("ETH"); allInvestmentAssets["ETH"] = InvestmentAssets(address(0), true, 2500, 10000, 18); allInvestmentCurrencies.push("DAI"); allInvestmentAssets["DAI"] = InvestmentAssets(_daiAdd, true, 250, 1500, 18); } /** * @dev to set the maximum cap allowed * @param val is the new value */ function setCapReached(uint val) external onlyInternal { capReached = val; } /// @dev Updates the 3 day average rate of a IA currency. /// To be replaced by MakerDao's on chain rates /// @param curr IA Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateIAAvgRate(bytes4 curr, uint rate) external onlyInternal { iaAvgRate[curr] = rate; } /// @dev Updates the 3 day average rate of a CA currency. /// To be replaced by MakerDao's on chain rates /// @param curr Currency Name. /// @param rate Average exchange rate X 100 (of last 3 days). function updateCAAvgRate(bytes4 curr, uint rate) external onlyInternal { caAvgRate[curr] = rate; } /// @dev Adds details of (Minimum Capital Requirement)MCR. /// @param mcrp Minimum Capital Requirement percentage (MCR% * 100 ,Ex:for 54.56% ,given 5456) /// @param vf Pool fund value in Ether used in the last full daily calculation from the Capital model. function pushMCRData(uint mcrp, uint mcre, uint vf, uint64 time) external onlyInternal { allMCRData.push(McrData(mcrp, mcre, vf, time)); } /** * @dev Updates the Timestamp at which result of oracalize call is received. */ function updateDateUpdOfAPI(bytes32 myid) external onlyInternal { allAPIid[myid].dateUpd = uint64(now); } /** * @dev Saves the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal,quote,cover etc. for which oraclize call is made */ function saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) external onlyInternal { allAPIid[myid] = ApiId(_typeof, "", id, uint64(now), uint64(now)); } /** * @dev Stores the id return by the oraclize query. * Maintains record of all the Ids return by oraclize query. * @param myid Id return by the oraclize query. */ function addInAllApiCall(bytes32 myid) external onlyInternal { allAPIcall.push(myid); } /** * @dev Saves investment asset rank details. * @param maxIACurr Maximum ranked investment asset currency. * @param maxRate Maximum ranked investment asset rate. * @param minIACurr Minimum ranked investment asset currency. * @param minRate Minimum ranked investment asset rate. * @param date in yyyymmdd. */ function saveIARankDetails( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate, uint64 date ) external onlyInternal { allIARankDetails.push(IARankDetails(maxIACurr, maxRate, minIACurr, minRate)); datewiseId[date] = allIARankDetails.length.sub(1); } /** * @dev to get the time for the laste liquidity trade trigger */ function setLastLiquidityTradeTrigger() external onlyInternal { lastLiquidityTradeTrigger = now; } /** * @dev Updates Last Date. */ function updatelastDate(uint64 newDate) external onlyInternal { lastDate = newDate; } /** * @dev Adds currency asset currency. * @param curr currency of the asset * @param currAddress address of the currency * @param baseMin base minimum in 10^18. */ function addCurrencyAssetCurrency( bytes4 curr, address currAddress, uint baseMin ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencies.push(curr); allCurrencyAssets[curr] = CurrencyAssets(currAddress, baseMin, 0); } /** * @dev Adds investment asset. */ function addInvestmentAssetCurrency( bytes4 curr, address currAddress, bool status, uint64 minHoldingPercX100, uint64 maxHoldingPercX100, uint8 decimals ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentCurrencies.push(curr); allInvestmentAssets[curr] = InvestmentAssets(currAddress, status, minHoldingPercX100, maxHoldingPercX100, decimals); } /** * @dev Changes base minimum of a given currency asset. */ function changeCurrencyAssetBaseMin(bytes4 curr, uint baseMin) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].baseMin = baseMin; } /** * @dev changes variable minimum of a given currency asset. */ function changeCurrencyAssetVarMin(bytes4 curr, uint varMin) external onlyInternal { allCurrencyAssets[curr].varMin = varMin; } /** * @dev Changes the investment asset status. */ function changeInvestmentAssetStatus(bytes4 curr, bool status) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].status = status; } /** * @dev Changes the investment asset Holding percentage of a given currency. */ function changeInvestmentAssetHoldingPerc( bytes4 curr, uint64 minPercX100, uint64 maxPercX100 ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].minHoldingPercX100 = minPercX100; allInvestmentAssets[curr].maxHoldingPercX100 = maxPercX100; } /** * @dev Gets Currency asset token address. */ function changeCurrencyAssetAddress(bytes4 curr, address currAdd) external { require(ms.checkIsAuthToGoverned(msg.sender)); allCurrencyAssets[curr].currAddress = currAdd; } /** * @dev Changes Investment asset token address. */ function changeInvestmentAssetAddressAndDecimal( bytes4 curr, address currAdd, uint8 newDecimal ) external { require(ms.checkIsAuthToGoverned(msg.sender)); allInvestmentAssets[curr].currAddress = currAdd; allInvestmentAssets[curr].decimals = newDecimal; } /// @dev Changes address allowed to post MCR. function changeNotariseAddress(address _add) external onlyInternal { notariseMCR = _add; } /// @dev updates daiFeedAddress address. /// @param _add address of DAI feed. function changeDAIfeedAddress(address _add) external onlyInternal { daiFeedAddress = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "MCRTIM") { val = mcrTime / (1 hours); } else if (code == "MCRFTIM") { val = mcrFailTime / (1 hours); } else if (code == "MCRMIN") { val = minCap; } else if (code == "MCRSHOCK") { val = shockParameter; } else if (code == "MCRCAPL") { val = capacityLimit; } else if (code == "IMZ") { val = variationPercX100; } else if (code == "IMRATET") { val = iaRatesTime / (1 hours); } else if (code == "IMUNIDL") { val = uniswapDeadline / (1 minutes); } else if (code == "IMLIQT") { val = liquidityTradeCallbackTime / (1 hours); } else if (code == "IMETHVL") { val = ethVolumeLimit; } else if (code == "C") { val = c; } else if (code == "A") { val = a; } } /// @dev Checks whether a given address can notaise MCR data or not. /// @param _add Address. /// @return res Returns 0 if address is not authorized, else 1. function isnotarise(address _add) external view returns(bool res) { res = false; if (_add == notariseMCR) res = true; } /// @dev Gets the details of last added MCR. /// @return mcrPercx100 Total Minimum Capital Requirement percentage of that month of year(multiplied by 100). /// @return vFull Total Pool fund value in Ether used in the last full daily calculation. function getLastMCR() external view returns(uint mcrPercx100, uint mcrEtherx1E18, uint vFull, uint64 date) { uint index = allMCRData.length.sub(1); return ( allMCRData[index].mcrPercx100, allMCRData[index].mcrEther, allMCRData[index].vFull, allMCRData[index].date ); } /// @dev Gets last Minimum Capital Requirement percentage of Capital Model /// @return val MCR% value,multiplied by 100. function getLastMCRPerc() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrPercx100; } /// @dev Gets last Ether price of Capital Model /// @return val ether value,multiplied by 100. function getLastMCREther() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].mcrEther; } /// @dev Gets Pool fund value in Ether used in the last full daily calculation from the Capital model. function getLastVfull() external view returns(uint) { return allMCRData[allMCRData.length.sub(1)].vFull; } /// @dev Gets last Minimum Capital Requirement in Ether. /// @return date of MCR. function getLastMCRDate() external view returns(uint64 date) { date = allMCRData[allMCRData.length.sub(1)].date; } /// @dev Gets details for token price calculation. function getTokenPriceDetails(bytes4 curr) external view returns(uint _a, uint _c, uint rate) { _a = a; _c = c; rate = _getAvgRate(curr, false); } /// @dev Gets the total number of times MCR calculation has been made. function getMCRDataLength() external view returns(uint len) { len = allMCRData.length; } /** * @dev Gets investment asset rank details by given date. */ function getIARankDetailsByDate( uint64 date ) external view returns( bytes4 maxIACurr, uint64 maxRate, bytes4 minIACurr, uint64 minRate ) { uint index = datewiseId[date]; return ( allIARankDetails[index].maxIACurr, allIARankDetails[index].maxRate, allIARankDetails[index].minIACurr, allIARankDetails[index].minRate ); } /** * @dev Gets Last Date. */ function getLastDate() external view returns(uint64 date) { return lastDate; } /** * @dev Gets investment currency for a given index. */ function getInvestmentCurrencyByIndex(uint index) external view returns(bytes4 currName) { return allInvestmentCurrencies[index]; } /** * @dev Gets count of investment currency. */ function getInvestmentCurrencyLen() external view returns(uint len) { return allInvestmentCurrencies.length; } /** * @dev Gets all the investment currencies. */ function getAllInvestmentCurrencies() external view returns(bytes4[] memory currencies) { return allInvestmentCurrencies; } /** * @dev Gets All currency for a given index. */ function getCurrenciesByIndex(uint index) external view returns(bytes4 currName) { return allCurrencies[index]; } /** * @dev Gets count of All currency. */ function getAllCurrenciesLen() external view returns(uint len) { return allCurrencies.length; } /** * @dev Gets all currencies */ function getAllCurrencies() external view returns(bytes4[] memory currencies) { return allCurrencies; } /** * @dev Gets currency asset details for a given currency. */ function getCurrencyAssetVarBase( bytes4 curr ) external view returns( bytes4 currency, uint baseMin, uint varMin ) { return ( curr, allCurrencyAssets[curr].baseMin, allCurrencyAssets[curr].varMin ); } /** * @dev Gets minimum variable value for currency asset. */ function getCurrencyAssetVarMin(bytes4 curr) external view returns(uint varMin) { return allCurrencyAssets[curr].varMin; } /** * @dev Gets base minimum of a given currency asset. */ function getCurrencyAssetBaseMin(bytes4 curr) external view returns(uint baseMin) { return allCurrencyAssets[curr].baseMin; } /** * @dev Gets investment asset maximum and minimum holding percentage of a given currency. */ function getInvestmentAssetHoldingPerc( bytes4 curr ) external view returns( uint64 minHoldingPercX100, uint64 maxHoldingPercX100 ) { return ( allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100 ); } /** * @dev Gets investment asset decimals. */ function getInvestmentAssetDecimals(bytes4 curr) external view returns(uint8 decimal) { return allInvestmentAssets[curr].decimals; } /** * @dev Gets investment asset maximum holding percentage of a given currency. */ function getInvestmentAssetMaxHoldingPerc(bytes4 curr) external view returns(uint64 maxHoldingPercX100) { return allInvestmentAssets[curr].maxHoldingPercX100; } /** * @dev Gets investment asset minimum holding percentage of a given currency. */ function getInvestmentAssetMinHoldingPerc(bytes4 curr) external view returns(uint64 minHoldingPercX100) { return allInvestmentAssets[curr].minHoldingPercX100; } /** * @dev Gets investment asset details of a given currency */ function getInvestmentAssetDetails( bytes4 curr ) external view returns( bytes4 currency, address currAddress, bool status, uint64 minHoldingPerc, uint64 maxHoldingPerc, uint8 decimals ) { return ( curr, allInvestmentAssets[curr].currAddress, allInvestmentAssets[curr].status, allInvestmentAssets[curr].minHoldingPercX100, allInvestmentAssets[curr].maxHoldingPercX100, allInvestmentAssets[curr].decimals ); } /** * @dev Gets Currency asset token address. */ function getCurrencyAssetAddress(bytes4 curr) external view returns(address) { return allCurrencyAssets[curr].currAddress; } /** * @dev Gets investment asset token address. */ function getInvestmentAssetAddress(bytes4 curr) external view returns(address) { return allInvestmentAssets[curr].currAddress; } /** * @dev Gets investment asset active Status of a given currency. */ function getInvestmentAssetStatus(bytes4 curr) external view returns(bool status) { return allInvestmentAssets[curr].status; } /** * @dev Gets type of oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return _typeof It could be of type "quote","quotation","cover","claim" etc. */ function getApiIdTypeOf(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].typeOf; } /** * @dev Gets ID associated to oraclize query for a given Oraclize Query ID. * @param myid Oraclize Query ID identifying the query for which the result is being received. * @return id1 It could be the ID of "proposal","quotation","cover","claim" etc. */ function getIdOfApiId(bytes32 myid) external view returns(uint) { return allAPIid[myid].id; } /** * @dev Gets the Timestamp of a oracalize call. */ function getDateAddOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateAdd; } /** * @dev Gets the Timestamp at which result of oracalize call is received. */ function getDateUpdOfAPI(bytes32 myid) external view returns(uint64) { return allAPIid[myid].dateUpd; } /** * @dev Gets currency by oracalize id. */ function getCurrOfApiId(bytes32 myid) external view returns(bytes4) { return allAPIid[myid].currency; } /** * @dev Gets ID return by the oraclize query of a given index. * @param index Index. * @return myid ID return by the oraclize query. */ function getApiCallIndex(uint index) external view returns(bytes32 myid) { myid = allAPIcall[index]; } /** * @dev Gets Length of API call. */ function getApilCallLength() external view returns(uint) { return allAPIcall.length; } /** * @dev Get Details of Oraclize API when given Oraclize Id. * @param myid ID return by the oraclize query. * @return _typeof ype of the query for which oraclize * call is made.("proposal","quote","quotation" etc.) */ function getApiCallDetails( bytes32 myid ) external view returns( bytes4 _typeof, bytes4 curr, uint id, uint64 dateAdd, uint64 dateUpd ) { return ( allAPIid[myid].typeOf, allAPIid[myid].currency, allAPIid[myid].id, allAPIid[myid].dateAdd, allAPIid[myid].dateUpd ); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "MCRTIM") { _changeMCRTime(val * 1 hours); } else if (code == "MCRFTIM") { _changeMCRFailTime(val * 1 hours); } else if (code == "MCRMIN") { _changeMinCap(val); } else if (code == "MCRSHOCK") { _changeShockParameter(val); } else if (code == "MCRCAPL") { _changeCapacityLimit(val); } else if (code == "IMZ") { _changeVariationPercX100(val); } else if (code == "IMRATET") { _changeIARatesTime(val * 1 hours); } else if (code == "IMUNIDL") { _changeUniswapDeadlineTime(val * 1 minutes); } else if (code == "IMLIQT") { _changeliquidityTradeCallbackTime(val * 1 hours); } else if (code == "IMETHVL") { _setEthVolumeLimit(val); } else if (code == "C") { _changeC(val); } else if (code == "A") { _changeA(val); } else { revert("Invalid param code"); } } /** * @dev to get the average rate of currency rate * @param curr is the currency in concern * @return required rate */ function getCAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, false); } /** * @dev to get the average rate of investment rate * @param curr is the investment in concern * @return required rate */ function getIAAvgRate(bytes4 curr) public view returns(uint rate) { return _getAvgRate(curr, true); } function changeDependentContractAddress() public onlyInternal {} /// @dev Gets the average rate of a CA currency. /// @param curr Currency Name. /// @return rate Average rate X 100(of last 3 days). function _getAvgRate(bytes4 curr, bool isIA) internal view returns(uint rate) { if (curr == "DAI") { DSValue ds = DSValue(daiFeedAddress); rate = uint(ds.read()).div(uint(10) ** 16); } else if (isIA) { rate = iaAvgRate[curr]; } else { rate = caAvgRate[curr]; } } /** * @dev to set the ethereum volume limit * @param val is the new limit value */ function _setEthVolumeLimit(uint val) internal { ethVolumeLimit = val; } /// @dev Sets minimum Cap. function _changeMinCap(uint newCap) internal { minCap = newCap; } /// @dev Sets Shock Parameter. function _changeShockParameter(uint newParam) internal { shockParameter = newParam; } /// @dev Changes time period for obtaining new MCR data from external oracle query. function _changeMCRTime(uint _time) internal { mcrTime = _time; } /// @dev Sets MCR Fail time. function _changeMCRFailTime(uint _time) internal { mcrFailTime = _time; } /** * @dev to change the uniswap deadline time * @param newDeadline is the value */ function _changeUniswapDeadlineTime(uint newDeadline) internal { uniswapDeadline = newDeadline; } /** * @dev to change the liquidity trade call back time * @param newTime is the new value to be set */ function _changeliquidityTradeCallbackTime(uint newTime) internal { liquidityTradeCallbackTime = newTime; } /** * @dev Changes time after which investment asset rates need to be fed. */ function _changeIARatesTime(uint _newTime) internal { iaRatesTime = _newTime; } /** * @dev Changes the variation range percentage. */ function _changeVariationPercX100(uint newPercX100) internal { variationPercX100 = newPercX100; } /// @dev Changes Growth Step function _changeC(uint newC) internal { c = newC; } /// @dev Changes scaling factor. function _changeA(uint val) internal { a = val; } /** * @dev to change the capacity limit * @param val is the new value */ function _changeCapacityLimit(uint val) internal { capacityLimit = val; } } // File: nexusmutual-contracts/contracts/QuotationData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract QuotationData is Iupgradable { using SafeMath for uint; enum HCIDStatus { NA, kycPending, kycPass, kycFailedOrRefunded, kycPassNoCover } enum CoverStatus { Active, ClaimAccepted, ClaimDenied, CoverExpired, ClaimSubmitted, Requested } struct Cover { address payable memberAddress; bytes4 currencyCode; uint sumAssured; uint16 coverPeriod; uint validUntil; address scAddress; uint premiumNXM; } struct HoldCover { uint holdCoverId; address payable userAddress; address scAddress; bytes4 coverCurr; uint[] coverDetails; uint16 coverPeriod; } address public authQuoteEngine; mapping(bytes4 => uint) internal currencyCSA; mapping(address => uint[]) internal userCover; mapping(address => uint[]) public userHoldedCover; mapping(address => bool) public refundEligible; mapping(address => mapping(bytes4 => uint)) internal currencyCSAOfSCAdd; mapping(uint => uint8) public coverStatus; mapping(uint => uint) public holdedCoverIDStatus; mapping(uint => bool) public timestampRepeated; Cover[] internal allCovers; HoldCover[] internal allCoverHolded; uint public stlp; uint public stl; uint public pm; uint public minDays; uint public tokensRetained; address public kycAuthAddress; event CoverDetailsEvent( uint indexed cid, address scAdd, uint sumAssured, uint expiry, uint premium, uint premiumNXM, bytes4 curr ); event CoverStatusEvent(uint indexed cid, uint8 statusNum); constructor(address _authQuoteAdd, address _kycAuthAdd) public { authQuoteEngine = _authQuoteAdd; kycAuthAddress = _kycAuthAdd; stlp = 90; stl = 100; pm = 30; minDays = 30; tokensRetained = 10; allCovers.push(Cover(address(0), "0x00", 0, 0, 0, address(0), 0)); uint[] memory arr = new uint[](1); allCoverHolded.push(HoldCover(0, address(0), address(0), 0x00, arr, 0)); } /// @dev Adds the amount in Total Sum Assured of a given currency of a given smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be added. function addInTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Subtracts the amount from Total Sum Assured of a given currency and smart contract address. /// @param _add Smart Contract Address. /// @param _amount Amount to be subtracted. function subFromTotalSumAssuredSC(address _add, bytes4 _curr, uint _amount) external onlyInternal { currencyCSAOfSCAdd[_add][_curr] = currencyCSAOfSCAdd[_add][_curr].sub(_amount); } /// @dev Subtracts the amount from Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be subtracted. function subFromTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].sub(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev Adds the amount in Total Sum Assured of a given currency. /// @param _curr Currency Name. /// @param _amount Amount to be added. function addInTotalSumAssured(bytes4 _curr, uint _amount) external onlyInternal { currencyCSA[_curr] = currencyCSA[_curr].add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /// @dev sets bit for timestamp to avoid replay attacks. function setTimestampRepeated(uint _timestamp) external onlyInternal { timestampRepeated[_timestamp] = true; } /// @dev Creates a blank new cover. function addCover( uint16 _coverPeriod, uint _sumAssured, address payable _userAddress, bytes4 _currencyCode, address _scAddress, uint premium, uint premiumNXM ) external onlyInternal { uint expiryDate = now.add(uint(_coverPeriod).mul(1 days)); allCovers.push(Cover(_userAddress, _currencyCode, _sumAssured, _coverPeriod, expiryDate, _scAddress, premiumNXM)); uint cid = allCovers.length.sub(1); userCover[_userAddress].push(cid); emit CoverDetailsEvent(cid, _scAddress, _sumAssured, expiryDate, premium, premiumNXM, _currencyCode); } /// @dev create holded cover which will process after verdict of KYC. function addHoldCover( address payable from, address scAddress, bytes4 coverCurr, uint[] calldata coverDetails, uint16 coverPeriod ) external onlyInternal { uint holdedCoverLen = allCoverHolded.length; holdedCoverIDStatus[holdedCoverLen] = uint(HCIDStatus.kycPending); allCoverHolded.push(HoldCover(holdedCoverLen, from, scAddress, coverCurr, coverDetails, coverPeriod)); userHoldedCover[from].push(allCoverHolded.length.sub(1)); } ///@dev sets refund eligible bit. ///@param _add user address. ///@param status indicates if user have pending kyc. function setRefundEligible(address _add, bool status) external onlyInternal { refundEligible[_add] = status; } /// @dev to set current status of particular holded coverID (1 for not completed KYC, /// 2 for KYC passed, 3 for failed KYC or full refunded, /// 4 for KYC completed but cover not processed) function setHoldedCoverIDStatus(uint holdedCoverID, uint status) external onlyInternal { holdedCoverIDStatus[holdedCoverID] = status; } /** * @dev to set address of kyc authentication * @param _add is the new address */ function setKycAuthAddress(address _add) external onlyInternal { kycAuthAddress = _add; } /// @dev Changes authorised address for generating quote off chain. function changeAuthQuoteEngine(address _add) external onlyInternal { authQuoteEngine = _add; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "STLP") { val = stlp; } else if (code == "STL") { val = stl; } else if (code == "PM") { val = pm; } else if (code == "QUOMIND") { val = minDays; } else if (code == "QUOTOK") { val = tokensRetained; } } /// @dev Gets Product details. /// @return _minDays minimum cover period. /// @return _PM Profit margin. /// @return _STL short term Load. /// @return _STLP short term load period. function getProductDetails() external view returns ( uint _minDays, uint _pm, uint _stl, uint _stlp ) { _minDays = minDays; _pm = pm; _stl = stl; _stlp = stlp; } /// @dev Gets total number covers created till date. function getCoverLength() external view returns(uint len) { return (allCovers.length); } /// @dev Gets Authorised Engine address. function getAuthQuoteEngine() external view returns(address _add) { _add = authQuoteEngine; } /// @dev Gets the Total Sum Assured amount of a given currency. function getTotalSumAssured(bytes4 _curr) external view returns(uint amount) { amount = currencyCSA[_curr]; } /// @dev Gets all the Cover ids generated by a given address. /// @param _add User's address. /// @return allCover array of covers. function getAllCoversOfUser(address _add) external view returns(uint[] memory allCover) { return (userCover[_add]); } /// @dev Gets total number of covers generated by a given address function getUserCoverLength(address _add) external view returns(uint len) { len = userCover[_add].length; } /// @dev Gets the status of a given cover. function getCoverStatusNo(uint _cid) external view returns(uint8) { return coverStatus[_cid]; } /// @dev Gets the Cover Period (in days) of a given cover. function getCoverPeriod(uint _cid) external view returns(uint32 cp) { cp = allCovers[_cid].coverPeriod; } /// @dev Gets the Sum Assured Amount of a given cover. function getCoverSumAssured(uint _cid) external view returns(uint sa) { sa = allCovers[_cid].sumAssured; } /// @dev Gets the Currency Name in which a given cover is assured. function getCurrencyOfCover(uint _cid) external view returns(bytes4 curr) { curr = allCovers[_cid].currencyCode; } /// @dev Gets the validity date (timestamp) of a given cover. function getValidityOfCover(uint _cid) external view returns(uint date) { date = allCovers[_cid].validUntil; } /// @dev Gets Smart contract address of cover. function getscAddressOfCover(uint _cid) external view returns(uint, address) { return (_cid, allCovers[_cid].scAddress); } /// @dev Gets the owner address of a given cover. function getCoverMemberAddress(uint _cid) external view returns(address payable _add) { _add = allCovers[_cid].memberAddress; } /// @dev Gets the premium amount of a given cover in NXM. function getCoverPremiumNXM(uint _cid) external view returns(uint _premiumNXM) { _premiumNXM = allCovers[_cid].premiumNXM; } /// @dev Provides the details of a cover Id /// @param _cid cover Id /// @return memberAddress cover user address. /// @return scAddress smart contract Address /// @return currencyCode currency of cover /// @return sumAssured sum assured of cover /// @return premiumNXM premium in NXM function getCoverDetailsByCoverID1( uint _cid ) external view returns ( uint cid, address _memberAddress, address _scAddress, bytes4 _currencyCode, uint _sumAssured, uint premiumNXM ) { return ( _cid, allCovers[_cid].memberAddress, allCovers[_cid].scAddress, allCovers[_cid].currencyCode, allCovers[_cid].sumAssured, allCovers[_cid].premiumNXM ); } /// @dev Provides details of a cover Id /// @param _cid cover Id /// @return status status of cover. /// @return sumAssured Sum assurance of cover. /// @return coverPeriod Cover Period of cover (in days). /// @return validUntil is validity of cover. function getCoverDetailsByCoverID2( uint _cid ) external view returns ( uint cid, uint8 status, uint sumAssured, uint16 coverPeriod, uint validUntil ) { return ( _cid, coverStatus[_cid], allCovers[_cid].sumAssured, allCovers[_cid].coverPeriod, allCovers[_cid].validUntil ); } /// @dev Provides details of a holded cover Id /// @param _hcid holded cover Id /// @return scAddress SmartCover address of cover. /// @return coverCurr currency of cover. /// @return coverPeriod Cover Period of cover (in days). function getHoldedCoverDetailsByID1( uint _hcid ) external view returns ( uint hcid, address scAddress, bytes4 coverCurr, uint16 coverPeriod ) { return ( _hcid, allCoverHolded[_hcid].scAddress, allCoverHolded[_hcid].coverCurr, allCoverHolded[_hcid].coverPeriod ); } /// @dev Gets total number holded covers created till date. function getUserHoldedCoverLength(address _add) external view returns (uint) { return userHoldedCover[_add].length; } /// @dev Gets holded cover index by index of user holded covers. function getUserHoldedCoverByIndex(address _add, uint index) external view returns (uint) { return userHoldedCover[_add][index]; } /// @dev Provides the details of a holded cover Id /// @param _hcid holded cover Id /// @return memberAddress holded cover user address. /// @return coverDetails array contains SA, Cover Currency Price,Price in NXM, Expiration time of Qoute. function getHoldedCoverDetailsByID2( uint _hcid ) external view returns ( uint hcid, address payable memberAddress, uint[] memory coverDetails ) { return ( _hcid, allCoverHolded[_hcid].userAddress, allCoverHolded[_hcid].coverDetails ); } /// @dev Gets the Total Sum Assured amount of a given currency and smart contract address. function getTotalSumAssuredSC(address _add, bytes4 _curr) external view returns(uint amount) { amount = currencyCSAOfSCAdd[_add][_curr]; } //solhint-disable-next-line function changeDependentContractAddress() public {} /// @dev Changes the status of a given cover. /// @param _cid cover Id. /// @param _stat New status. function changeCoverStatusNo(uint _cid, uint8 _stat) public onlyInternal { coverStatus[_cid] = _stat; emit CoverStatusEvent(_cid, _stat); } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "STLP") { _changeSTLP(val); } else if (code == "STL") { _changeSTL(val); } else if (code == "PM") { _changePM(val); } else if (code == "QUOMIND") { _changeMinDays(val); } else if (code == "QUOTOK") { _setTokensRetained(val); } else { revert("Invalid param code"); } } /// @dev Changes the existing Profit Margin value function _changePM(uint _pm) internal { pm = _pm; } /// @dev Changes the existing Short Term Load Period (STLP) value. function _changeSTLP(uint _stlp) internal { stlp = _stlp; } /// @dev Changes the existing Short Term Load (STL) value. function _changeSTL(uint _stl) internal { stl = _stl; } /// @dev Changes the existing Minimum cover period (in days) function _changeMinDays(uint _days) internal { minDays = _days; } /** * @dev to set the the amount of tokens retained * @param val is the amount retained */ function _setTokensRetained(uint val) internal { tokensRetained = val; } } // File: nexusmutual-contracts/contracts/TokenData.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract TokenData is Iupgradable { using SafeMath for uint; address payable public walletAddress; uint public lockTokenTimeAfterCoverExp; uint public bookTime; uint public lockCADays; uint public lockMVDays; uint public scValidDays; uint public joiningFee; uint public stakerCommissionPer; uint public stakerMaxCommissionPer; uint public tokenExponent; uint public priceStep; struct StakeCommission { uint commissionEarned; uint commissionRedeemed; } struct Stake { address stakedContractAddress; uint stakedContractIndex; uint dateAdd; uint stakeAmount; uint unlockedAmount; uint burnedAmount; uint unLockableBeforeLastBurn; } struct Staker { address stakerAddress; uint stakerIndex; } struct CoverNote { uint amount; bool isDeposited; } /** * @dev mapping of uw address to array of sc address to fetch * all staked contract address of underwriter, pushing * data into this array of Stake returns stakerIndex */ mapping(address => Stake[]) public stakerStakedContracts; /** * @dev mapping of sc address to array of UW address to fetch * all underwritters of the staked smart contract * pushing data into this mapped array returns scIndex */ mapping(address => Staker[]) public stakedContractStakers; /** * @dev mapping of staked contract Address to the array of StakeCommission * here index of this array is stakedContractIndex */ mapping(address => mapping(uint => StakeCommission)) public stakedContractStakeCommission; mapping(address => uint) public lastCompletedStakeCommission; /** * @dev mapping of the staked contract address to the current * staker index who will receive commission. */ mapping(address => uint) public stakedContractCurrentCommissionIndex; /** * @dev mapping of the staked contract address to the * current staker index to burn token from. */ mapping(address => uint) public stakedContractCurrentBurnIndex; /** * @dev mapping to return true if Cover Note deposited against coverId */ mapping(uint => CoverNote) public depositedCN; mapping(address => uint) internal isBookedTokens; event Commission( address indexed stakedContractAddress, address indexed stakerAddress, uint indexed scIndex, uint commissionAmount ); constructor(address payable _walletAdd) public { walletAddress = _walletAdd; bookTime = 12 hours; joiningFee = 2000000000000000; // 0.002 Ether lockTokenTimeAfterCoverExp = 35 days; scValidDays = 250; lockCADays = 7 days; lockMVDays = 2 days; stakerCommissionPer = 20; stakerMaxCommissionPer = 50; tokenExponent = 4; priceStep = 1000; } /** * @dev Change the wallet address which receive Joining Fee */ function changeWalletAddress(address payable _address) external onlyInternal { walletAddress = _address; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "TOKEXP") { val = tokenExponent; } else if (code == "TOKSTEP") { val = priceStep; } else if (code == "RALOCKT") { val = scValidDays; } else if (code == "RACOMM") { val = stakerCommissionPer; } else if (code == "RAMAXC") { val = stakerMaxCommissionPer; } else if (code == "CABOOKT") { val = bookTime / (1 hours); } else if (code == "CALOCKT") { val = lockCADays / (1 days); } else if (code == "MVLOCKT") { val = lockMVDays / (1 days); } else if (code == "QUOLOCKT") { val = lockTokenTimeAfterCoverExp / (1 days); } else if (code == "JOINFEE") { val = joiningFee; } } /** * @dev Just for interface */ function changeDependentContractAddress() public { //solhint-disable-line } /** * @dev to get the contract staked by a staker * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return the address of staked contract */ function getStakerStakedContractByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (address stakedContractAddress) { stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; } /** * @dev to get the staker's staked burned * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount burned */ function getStakerStakedBurnedByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint burnedAmount) { burnedAmount = stakerStakedContracts[ _stakerAddress][_stakerIndex].burnedAmount; } /** * @dev to get the staker's staked unlockable before the last burn * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return unlockable staked tokens */ function getStakerStakedUnlockableBeforeLastBurnByIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint unlockable) { unlockable = stakerStakedContracts[ _stakerAddress][_stakerIndex].unLockableBeforeLastBurn; } /** * @dev to get the staker's staked contract index * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return is the index of the smart contract address */ function getStakerStakedContractIndex( address _stakerAddress, uint _stakerIndex ) public view returns (uint scIndex) { scIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; } /** * @dev to get the staker index of the staked contract * @param _stakedContractAddress is the address of the staked contract * @param _stakedContractIndex is the index of staked contract * @return is the index of the staker */ function getStakedContractStakerIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (uint sIndex) { sIndex = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerIndex; } /** * @dev to get the staker's initial staked amount on the contract * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return staked amount */ function getStakerInitialStakedAmountOnContract( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakeAmount; } /** * @dev to get the staker's staked contract length * @param _stakerAddress is the address of the staker * @return length of staked contract */ function getStakerStakedContractLength( address _stakerAddress ) public view returns (uint length) { length = stakerStakedContracts[_stakerAddress].length; } /** * @dev to get the staker's unlocked tokens which were staked * @param _stakerAddress is the address of the staker * @param _stakerIndex is the index of staker * @return amount */ function getStakerUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex ) public view returns (uint amount) { amount = stakerStakedContracts[ _stakerAddress][_stakerIndex].unlockedAmount; } /** * @dev pushes the unlocked staked tokens by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushUnlockedStakedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].unlockedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the Burned tokens for a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be burned. */ function pushBurnedTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount = stakerStakedContracts[_stakerAddress][ _stakerIndex].burnedAmount.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev pushes the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function pushUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev sets the unLockable tokens for a staker before last burn. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker. * @param _amount amount to be added to unlockable. */ function setUnlockableBeforeLastBurnTokens( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { stakerStakedContracts[_stakerAddress][ _stakerIndex].unLockableBeforeLastBurn = _amount; } /** * @dev pushes the earned commission earned by a staker. * @param _stakerAddress address of staker. * @param _stakedContractAddress address of smart contract. * @param _stakedContractIndex index of the staker to distribute commission. * @param _commissionAmount amount to be given as commission. */ function pushEarnedStakeCommissions( address _stakerAddress, address _stakedContractAddress, uint _stakedContractIndex, uint _commissionAmount ) public onlyInternal { stakedContractStakeCommission[_stakedContractAddress][_stakedContractIndex]. commissionEarned = stakedContractStakeCommission[_stakedContractAddress][ _stakedContractIndex].commissionEarned.add(_commissionAmount); //injected INTEGER OVERFLOW OR UNDERFLOW emit Commission( _stakerAddress, _stakedContractAddress, _stakedContractIndex, _commissionAmount ); } /** * @dev pushes the redeemed commission redeemed by a staker. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker to distribute commission. * @param _amount amount to be given as commission. */ function pushRedeemedStakeCommissions( address _stakerAddress, uint _stakerIndex, uint _amount ) public onlyInternal { uint stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; address stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; stakedContractStakeCommission[stakedContractAddress][stakedContractIndex]. commissionRedeemed = stakedContractStakeCommission[ stakedContractAddress][stakedContractIndex].commissionRedeemed.add(_amount); //injected INTEGER OVERFLOW OR UNDERFLOW } /** * @dev Gets stake commission given to an underwriter * for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerEarnedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets stake commission redeemed by an underwriter * for particular staked contract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. * @return commissionEarned total amount given to staker. */ function getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) public view returns (uint) { return _getStakerRedeemedStakeCommission(_stakerAddress, _stakerIndex); } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalEarnedStakeCommission( address _stakerAddress ) public view returns (uint totalCommissionEarned) { totalCommissionEarned = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionEarned = totalCommissionEarned. add(_getStakerEarnedStakeCommission(_stakerAddress, i)); } } /** * @dev Gets total stake commission given to an underwriter * @param _stakerAddress address of staker. * @return totalCommissionEarned total commission earned by staker. */ function getStakerTotalReedmedStakeCommission( address _stakerAddress ) public view returns(uint totalCommissionRedeemed) { totalCommissionRedeemed = 0; for (uint i = 0; i < stakerStakedContracts[_stakerAddress].length; i++) { totalCommissionRedeemed = totalCommissionRedeemed.add( _getStakerRedeemedStakeCommission(_stakerAddress, i)); } } /** * @dev set flag to deposit/ undeposit cover note * against a cover Id * @param coverId coverId of Cover * @param flag true/false for deposit/undeposit */ function setDepositCN(uint coverId, bool flag) public onlyInternal { if (flag == true) { require(!depositedCN[coverId].isDeposited, "Cover note already deposited"); } depositedCN[coverId].isDeposited = flag; } /** * @dev set locked cover note amount * against a cover Id * @param coverId coverId of Cover * @param amount amount of nxm to be locked */ function setDepositCNAmount(uint coverId, uint amount) public onlyInternal { depositedCN[coverId].amount = amount; } /** * @dev to get the staker address on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @param _stakedContractIndex is the index of staked contract's index * @return address of staker */ function getStakedContractStakerByIndex( address _stakedContractAddress, uint _stakedContractIndex ) public view returns (address stakerAddress) { stakerAddress = stakedContractStakers[ _stakedContractAddress][_stakedContractIndex].stakerAddress; } /** * @dev to get the length of stakers on a staked contract * @param _stakedContractAddress is the address of the staked contract in concern * @return length in concern */ function getStakedContractStakersLength( address _stakedContractAddress ) public view returns (uint length) { length = stakedContractStakers[_stakedContractAddress].length; } /** * @dev Adds a new stake record. * @param _stakerAddress staker address. * @param _stakedContractAddress smart contract address. * @param _amount amountof NXM to be staked. */ function addStake( address _stakerAddress, address _stakedContractAddress, uint _amount ) public onlyInternal returns(uint scIndex) { scIndex = (stakedContractStakers[_stakedContractAddress].push( Staker(_stakerAddress, stakerStakedContracts[_stakerAddress].length))).sub(1); stakerStakedContracts[_stakerAddress].push( Stake(_stakedContractAddress, scIndex, now, _amount, 0, 0, 0)); } /** * @dev books the user's tokens for maintaining Assessor Velocity, * i.e. once a token is used to cast a vote as a Claims assessor, * @param _of user's address. */ function bookCATokens(address _of) public onlyInternal { require(!isCATokensBooked(_of), "Tokens already booked"); isBookedTokens[_of] = now.add(bookTime); } /** * @dev to know if claim assessor's tokens are booked or not * @param _of is the claim assessor's address in concern * @return boolean representing the status of tokens booked */ function isCATokensBooked(address _of) public view returns(bool res) { if (now < isBookedTokens[_of]) res = true; } /** * @dev Sets the index which will receive commission. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentCommissionIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentCommissionIndex[_stakedContractAddress] = _index; } /** * @dev Sets the last complete commission index * @param _stakerAddress smart contract address. * @param _index current index. */ function setLastCompletedStakeCommissionIndex( address _stakerAddress, uint _index ) public onlyInternal { lastCompletedStakeCommission[_stakerAddress] = _index; } /** * @dev Sets the index till which commission is distrubuted. * @param _stakedContractAddress smart contract address. * @param _index current index. */ function setStakedContractCurrentBurnIndex( address _stakedContractAddress, uint _index ) public onlyInternal { stakedContractCurrentBurnIndex[_stakedContractAddress] = _index; } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "TOKEXP") { _setTokenExponent(val); } else if (code == "TOKSTEP") { _setPriceStep(val); } else if (code == "RALOCKT") { _changeSCValidDays(val); } else if (code == "RACOMM") { _setStakerCommissionPer(val); } else if (code == "RAMAXC") { _setStakerMaxCommissionPer(val); } else if (code == "CABOOKT") { _changeBookTime(val * 1 hours); } else if (code == "CALOCKT") { _changelockCADays(val * 1 days); } else if (code == "MVLOCKT") { _changelockMVDays(val * 1 days); } else if (code == "QUOLOCKT") { _setLockTokenTimeAfterCoverExp(val * 1 days); } else if (code == "JOINFEE") { _setJoiningFee(val); } else { revert("Invalid param code"); } } /** * @dev Internal function to get stake commission given to an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerEarnedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionEarned; } /** * @dev Internal function to get stake commission redeemed by an * underwriter for particular stakedcontract on given index. * @param _stakerAddress address of staker. * @param _stakerIndex index of the staker commission. */ function _getStakerRedeemedStakeCommission( address _stakerAddress, uint _stakerIndex ) internal view returns (uint amount) { uint _stakedContractIndex; address _stakedContractAddress; _stakedContractAddress = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractAddress; _stakedContractIndex = stakerStakedContracts[ _stakerAddress][_stakerIndex].stakedContractIndex; amount = stakedContractStakeCommission[ _stakedContractAddress][_stakedContractIndex].commissionRedeemed; } /** * @dev to set the percentage of staker commission * @param _val is new percentage value */ function _setStakerCommissionPer(uint _val) internal { stakerCommissionPer = _val; } /** * @dev to set the max percentage of staker commission * @param _val is new percentage value */ function _setStakerMaxCommissionPer(uint _val) internal { stakerMaxCommissionPer = _val; } /** * @dev to set the token exponent value * @param _val is new value */ function _setTokenExponent(uint _val) internal { tokenExponent = _val; } /** * @dev to set the price step * @param _val is new value */ function _setPriceStep(uint _val) internal { priceStep = _val; } /** * @dev Changes number of days for which NXM needs to staked in case of underwriting */ function _changeSCValidDays(uint _days) internal { scValidDays = _days; } /** * @dev Changes the time period up to which tokens will be locked. * Used to generate the validity period of tokens booked by * a user for participating in claim's assessment/claim's voting. */ function _changeBookTime(uint _time) internal { bookTime = _time; } /** * @dev Changes lock CA days - number of days for which tokens * are locked while submitting a vote. */ function _changelockCADays(uint _val) internal { lockCADays = _val; } /** * @dev Changes lock MV days - number of days for which tokens are locked * while submitting a vote. */ function _changelockMVDays(uint _val) internal { lockMVDays = _val; } /** * @dev Changes extra lock period for a cover, post its expiry. */ function _setLockTokenTimeAfterCoverExp(uint time) internal { lockTokenTimeAfterCoverExp = time; } /** * @dev Set the joining fee for membership */ function _setJoiningFee(uint _amount) internal { joiningFee = _amount; } } // File: nexusmutual-contracts/contracts/external/oraclize/ethereum-api/usingOraclize.sol /* ORACLIZE_API Copyright (c) 2015-2016 Oraclize SRL Copyright (c) 2016 Oraclize LTD 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. */ pragma solidity >= 0.5.0 < 0.6.0; // Incompatible compiler version - please select a compiler within the stated pragma range, or use a different version of the oraclizeAPI! // Dummy contract only used to emit to end-user they are using wrong solc contract solcChecker { /* INCOMPATIBLE SOLC: import the following instead: "github.com/oraclize/ethereum-api/oraclizeAPI_0.4.sol" */ function f(bytes calldata x) external; } contract OraclizeI { address public cbAddress; function setProofType(byte _proofType) external; function setCustomGasPrice(uint _gasPrice) external; function getPrice(string memory _datasource) public returns (uint _dsprice); function randomDS_getSessionPubKeyHash() external view returns (bytes32 _sessionKeyHash); function getPrice(string memory _datasource, uint _gasLimit) public returns (uint _dsprice); function queryN(uint _timestamp, string memory _datasource, bytes memory _argN) public payable returns (bytes32 _id); function query(uint _timestamp, string calldata _datasource, string calldata _arg) external payable returns (bytes32 _id); function query2(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) public payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg, uint _gasLimit) external payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string calldata _datasource, bytes calldata _argN, uint _gasLimit) external payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string calldata _datasource, string calldata _arg1, string calldata _arg2, uint _gasLimit) external payable returns (bytes32 _id); } contract OraclizeAddrResolverI { function getAddress() public returns (address _address); } /* Begin solidity-cborutils https://github.com/smartcontractkit/solidity-cborutils MIT License Copyright (c) 2018 SmartContract ChainLink, Ltd. 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. */ library Buffer { struct buffer { bytes buf; uint capacity; } function init(buffer memory _buf, uint _capacity) internal pure { uint capacity = _capacity; if (capacity % 32 != 0) { capacity += 32 - (capacity % 32); } _buf.capacity = capacity; // Allocate space for the buffer data assembly { let ptr := mload(0x40) mstore(_buf, ptr) mstore(ptr, 0) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory _buf, uint _capacity) private pure { bytes memory oldbuf = _buf.buf; init(_buf, _capacity); append(_buf, oldbuf); } function max(uint _a, uint _b) private pure returns (uint _max) { if (_a > _b) { return _a; } return _b; } /** * @dev Appends a byte array to the end of the buffer. Resizes if doing so * would exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, bytes memory _data) internal pure returns (buffer memory _buffer) { if (_data.length + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _data.length) * 2); } uint dest; uint src; uint len = _data.length; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data dest := add(add(bufptr, buflen), 32) // Start address = buffer address + buffer length + sizeof(buffer length) mstore(bufptr, add(buflen, mload(_data))) // Update buffer length src := add(_data, 32) } for(; len >= 32; len -= 32) { // Copy word-length chunks while possible assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } uint mask = 256 ** (32 - len) - 1; // Copy remaining bytes assembly { let srcpart := and(mload(src), not(mask)) let destpart := and(mload(dest), mask) mstore(dest, or(destpart, srcpart)) } return _buf; } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function append(buffer memory _buf, uint8 _data) internal pure { if (_buf.buf.length + 1 > _buf.capacity) { resize(_buf, _buf.capacity * 2); } assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), 32) // Address = buffer address + buffer length + sizeof(buffer length) mstore8(dest, _data) mstore(bufptr, add(buflen, 1)) // Update buffer length } } /** * * @dev Appends a byte to the end of the buffer. Resizes if doing so would * exceed the capacity of the buffer. * @param _buf The buffer to append to. * @param _data The data to append. * @return The original buffer. * */ function appendInt(buffer memory _buf, uint _data, uint _len) internal pure returns (buffer memory _buffer) { if (_len + _buf.buf.length > _buf.capacity) { resize(_buf, max(_buf.capacity, _len) * 2); } uint mask = 256 ** _len - 1; assembly { let bufptr := mload(_buf) // Memory address of the buffer data let buflen := mload(bufptr) // Length of existing buffer data let dest := add(add(bufptr, buflen), _len) // Address = buffer address + buffer length + sizeof(buffer length) + len mstore(dest, or(and(mload(dest), not(mask)), _data)) mstore(bufptr, add(buflen, _len)) // Update buffer length } return _buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function encodeType(Buffer.buffer memory _buf, uint8 _major, uint _value) private pure { if (_value <= 23) { _buf.append(uint8((_major << 5) | _value)); } else if (_value <= 0xFF) { _buf.append(uint8((_major << 5) | 24)); _buf.appendInt(_value, 1); } else if (_value <= 0xFFFF) { _buf.append(uint8((_major << 5) | 25)); _buf.appendInt(_value, 2); } else if (_value <= 0xFFFFFFFF) { _buf.append(uint8((_major << 5) | 26)); _buf.appendInt(_value, 4); } else if (_value <= 0xFFFFFFFFFFFFFFFF) { _buf.append(uint8((_major << 5) | 27)); _buf.appendInt(_value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory _buf, uint8 _major) private pure { _buf.append(uint8((_major << 5) | 31)); } function encodeUInt(Buffer.buffer memory _buf, uint _value) internal pure { encodeType(_buf, MAJOR_TYPE_INT, _value); } function encodeInt(Buffer.buffer memory _buf, int _value) internal pure { if (_value >= 0) { encodeType(_buf, MAJOR_TYPE_INT, uint(_value)); } else { encodeType(_buf, MAJOR_TYPE_NEGATIVE_INT, uint(-1 - _value)); } } function encodeBytes(Buffer.buffer memory _buf, bytes memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_BYTES, _value.length); _buf.append(_value); } function encodeString(Buffer.buffer memory _buf, string memory _value) internal pure { encodeType(_buf, MAJOR_TYPE_STRING, bytes(_value).length); _buf.append(bytes(_value)); } function startArray(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory _buf) internal pure { encodeIndefiniteLengthType(_buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { using CBOR for Buffer.buffer; OraclizeI oraclize; OraclizeAddrResolverI OAR; uint constant day = 60 * 60 * 24; uint constant week = 60 * 60 * 24 * 7; uint constant month = 60 * 60 * 24 * 30; byte constant proofType_NONE = 0x00; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; byte constant proofType_Android = 0x40; byte constant proofType_TLSNotary = 0x10; string oraclize_network_name; uint8 constant networkID_auto = 0; uint8 constant networkID_morden = 2; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_consensys = 161; mapping(bytes32 => bytes32) oraclize_randomDS_args; mapping(bytes32 => bool) oraclize_randomDS_sessionKeysHashVerified; modifier oraclizeAPI { if ((address(OAR) == address(0)) || (getCodeSize(address(OAR)) == 0)) { oraclize_setNetwork(networkID_auto); } if (address(oraclize) != OAR.getAddress()) { oraclize = OraclizeI(OAR.getAddress()); } _; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string memory _result, bytes memory _proof) { // RandomDS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) require((_proof[0] == "L") && (_proof[1] == "P") && (uint8(_proof[2]) == uint8(1))); bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); require(proofVerified); _; } function oraclize_setNetwork(uint8 _networkID) internal returns (bool _networkSet) { return oraclize_setNetwork(); _networkID; // silence the warning and remain backwards compatible } function oraclize_setNetworkName(string memory _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal view returns (string memory _networkName) { return oraclize_network_name; } function oraclize_setNetwork() internal returns (bool _networkSet) { if (getCodeSize(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed) > 0) { //mainnet OAR = OraclizeAddrResolverI(0x1d3B2638a7cC9f2CB3D298A3DA7a90B67E5506ed); oraclize_setNetworkName("eth_mainnet"); return true; } if (getCodeSize(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1) > 0) { //ropsten testnet OAR = OraclizeAddrResolverI(0xc03A2615D5efaf5F49F60B7BB6583eaec212fdf1); oraclize_setNetworkName("eth_ropsten3"); return true; } if (getCodeSize(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e) > 0) { //kovan testnet OAR = OraclizeAddrResolverI(0xB7A07BcF2Ba2f2703b24C0691b5278999C59AC7e); oraclize_setNetworkName("eth_kovan"); return true; } if (getCodeSize(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48) > 0) { //rinkeby testnet OAR = OraclizeAddrResolverI(0x146500cfd35B22E4A392Fe0aDc06De1a1368Ed48); oraclize_setNetworkName("eth_rinkeby"); return true; } if (getCodeSize(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41) > 0) { //goerli testnet OAR = OraclizeAddrResolverI(0xa2998EFD205FB9D4B4963aFb70778D6354ad3A41); oraclize_setNetworkName("eth_goerli"); return true; } if (getCodeSize(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475) > 0) { //ethereum-bridge OAR = OraclizeAddrResolverI(0x6f485C8BF6fc43eA212E93BBF8ce046C7f1cb475); return true; } if (getCodeSize(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF) > 0) { //ether.camp ide OAR = OraclizeAddrResolverI(0x20e12A1F859B3FeaE5Fb2A0A32C18F5a65555bBF); return true; } if (getCodeSize(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA) > 0) { //browser-solidity OAR = OraclizeAddrResolverI(0x51efaF4c8B3C9AfBD5aB9F4bbC82784Ab6ef8fAA); return true; } return false; } function __callback(bytes32 _myid, string memory _result) public { __callback(_myid, _result, new bytes(0)); } function __callback(bytes32 _myid, string memory _result, bytes memory _proof) public { return; _myid; _result; _proof; // Silence compiler warnings } function oraclize_getPrice(string memory _datasource) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource); } function oraclize_getPrice(string memory _datasource, uint _gasLimit) oraclizeAPI internal returns (uint _queryPrice) { return oraclize.getPrice(_datasource, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(0, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query.value(price)(_timestamp, _datasource, _arg); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource,_gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(_timestamp, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query_withGasLimit.value(price)(0, _datasource, _arg, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(0, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } return oraclize.query2.value(price)(_timestamp, _datasource, _arg1, _arg2); } function oraclize_query(uint _timestamp, string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(_timestamp, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string memory _arg1, string memory _arg2, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } return oraclize.query2_withGasLimit.value(price)(0, _datasource, _arg1, _arg2, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = stra2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, string[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { string[] memory dynargs = new string[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(0, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource); if (price > 1 ether + tx.gasprice * 200000) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN.value(price)(_timestamp, _datasource, args); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(_timestamp, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[] memory _argN, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { uint price = oraclize.getPrice(_datasource, _gasLimit); if (price > 1 ether + tx.gasprice * _gasLimit) { return 0; // Unexpectedly high price } bytes memory args = ba2cbor(_argN); return oraclize.queryN_withGasLimit.value(price)(0, _datasource, args, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[1] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](1); dynargs[0] = _args[0]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[2] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](2); dynargs[0] = _args[0]; dynargs[1] = _args[1]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[3] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](3); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[4] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](4); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs); } function oraclize_query(uint _timestamp, string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_timestamp, _datasource, dynargs, _gasLimit); } function oraclize_query(string memory _datasource, bytes[5] memory _args, uint _gasLimit) oraclizeAPI internal returns (bytes32 _id) { bytes[] memory dynargs = new bytes[](5); dynargs[0] = _args[0]; dynargs[1] = _args[1]; dynargs[2] = _args[2]; dynargs[3] = _args[3]; dynargs[4] = _args[4]; return oraclize_query(_datasource, dynargs, _gasLimit); } function oraclize_setProof(byte _proofP) oraclizeAPI internal { return oraclize.setProofType(_proofP); } function oraclize_cbAddress() oraclizeAPI internal returns (address _callbackAddress) { return oraclize.cbAddress(); } function getCodeSize(address _addr) view internal returns (uint _size) { assembly { _size := extcodesize(_addr) } } function oraclize_setCustomGasPrice(uint _gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(_gasPrice); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32 _sessionKeyHash) { return oraclize.randomDS_getSessionPubKeyHash(); } function parseAddr(string memory _a) internal pure returns (address _parsedAddress) { bytes memory tmp = bytes(_a); uint160 iaddr = 0; uint160 b1; uint160 b2; for (uint i = 2; i < 2 + 2 * 20; i += 2) { iaddr *= 256; b1 = uint160(uint8(tmp[i])); b2 = uint160(uint8(tmp[i + 1])); if ((b1 >= 97) && (b1 <= 102)) { b1 -= 87; } else if ((b1 >= 65) && (b1 <= 70)) { b1 -= 55; } else if ((b1 >= 48) && (b1 <= 57)) { b1 -= 48; } if ((b2 >= 97) && (b2 <= 102)) { b2 -= 87; } else if ((b2 >= 65) && (b2 <= 70)) { b2 -= 55; } else if ((b2 >= 48) && (b2 <= 57)) { b2 -= 48; } iaddr += (b1 * 16 + b2); } return address(iaddr); } function strCompare(string memory _a, string memory _b) internal pure returns (int _returnCode) { bytes memory a = bytes(_a); bytes memory b = bytes(_b); uint minLength = a.length; if (b.length < minLength) { minLength = b.length; } for (uint i = 0; i < minLength; i ++) { if (a[i] < b[i]) { return -1; } else if (a[i] > b[i]) { return 1; } } if (a.length < b.length) { return -1; } else if (a.length > b.length) { return 1; } else { return 0; } } function indexOf(string memory _haystack, string memory _needle) internal pure returns (int _returnCode) { bytes memory h = bytes(_haystack); bytes memory n = bytes(_needle); if (h.length < 1 || n.length < 1 || (n.length > h.length)) { return -1; } else if (h.length > (2 ** 128 - 1)) { return -1; } else { uint subindex = 0; for (uint i = 0; i < h.length; i++) { if (h[i] == n[0]) { subindex = 1; while(subindex < n.length && (i + subindex) < h.length && h[i + subindex] == n[subindex]) { subindex++; } if (subindex == n.length) { return int(i); } } } return -1; } } function strConcat(string memory _a, string memory _b) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, "", "", ""); } function strConcat(string memory _a, string memory _b, string memory _c) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d) internal pure returns (string memory _concatenatedString) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string memory _a, string memory _b, string memory _c, string memory _d, string memory _e) internal pure returns (string memory _concatenatedString) { bytes memory _ba = bytes(_a); bytes memory _bb = bytes(_b); bytes memory _bc = bytes(_c); bytes memory _bd = bytes(_d); bytes memory _be = bytes(_e); string memory abcde = new string(_ba.length + _bb.length + _bc.length + _bd.length + _be.length); bytes memory babcde = bytes(abcde); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { babcde[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { babcde[k++] = _bb[i]; } for (i = 0; i < _bc.length; i++) { babcde[k++] = _bc[i]; } for (i = 0; i < _bd.length; i++) { babcde[k++] = _bd[i]; } for (i = 0; i < _be.length; i++) { babcde[k++] = _be[i]; } return string(babcde); } function safeParseInt(string memory _a) internal pure returns (uint _parsedInt) { return safeParseInt(_a, 0); } function safeParseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) break; else _b--; } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { require(!decimals, 'More than one decimal encountered in string!'); decimals = true; } else { revert("Non-numeral character encountered in string!"); } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function parseInt(string memory _a) internal pure returns (uint _parsedInt) { return parseInt(_a, 0); } function parseInt(string memory _a, uint _b) internal pure returns (uint _parsedInt) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i = 0; i < bresult.length; i++) { if ((uint(uint8(bresult[i])) >= 48) && (uint(uint8(bresult[i])) <= 57)) { if (decimals) { if (_b == 0) { break; } else { _b--; } } mint *= 10; mint += uint(uint8(bresult[i])) - 48; } else if (uint(uint8(bresult[i])) == 46) { decimals = true; } } if (_b > 0) { mint *= 10 ** _b; } return mint; } function uint2str(uint _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; while (_i != 0) { bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } return string(bstr); } function stra2cbor(string[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeString(_arr[i]); } buf.endSequence(); return buf.buf; } function ba2cbor(bytes[] memory _arr) internal pure returns (bytes memory _cborEncoding) { safeMemoryCleaner(); Buffer.buffer memory buf; Buffer.init(buf, 1024); buf.startArray(); for (uint i = 0; i < _arr.length; i++) { buf.encodeBytes(_arr[i]); } buf.endSequence(); return buf.buf; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32 _queryId) { require((_nbytes > 0) && (_nbytes <= 32)); _delay *= 10; // Convert from seconds to ledger timer ticks bytes memory nbytes = new bytes(1); nbytes[0] = byte(uint8(_nbytes)); bytes memory unonce = new bytes(32); bytes memory sessionKeyHash = new bytes(32); bytes32 sessionKeyHash_bytes32 = oraclize_randomDS_getSessionPubKeyHash(); assembly { mstore(unonce, 0x20) /* The following variables can be relaxed. Check the relaxed random contract at https://github.com/oraclize/ethereum-examples for an idea on how to override and replace commit hash variables. */ mstore(add(unonce, 0x20), xor(blockhash(sub(number, 1)), xor(coinbase, timestamp))) mstore(sessionKeyHash, 0x20) mstore(add(sessionKeyHash, 0x20), sessionKeyHash_bytes32) } bytes memory delay = new bytes(32); assembly { mstore(add(delay, 0x20), _delay) } bytes memory delay_bytes8 = new bytes(8); copyBytes(delay, 24, 8, delay_bytes8, 0); bytes[4] memory args = [unonce, nbytes, sessionKeyHash, delay]; bytes32 queryId = oraclize_query("random", args, _customGasLimit); bytes memory delay_bytes8_left = new bytes(8); assembly { let x := mload(add(delay_bytes8, 0x20)) mstore8(add(delay_bytes8_left, 0x27), div(x, 0x100000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x26), div(x, 0x1000000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x25), div(x, 0x10000000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x24), div(x, 0x100000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x23), div(x, 0x1000000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x22), div(x, 0x10000000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x21), div(x, 0x100000000000000000000000000000000000000000000000000)) mstore8(add(delay_bytes8_left, 0x20), div(x, 0x1000000000000000000000000000000000000000000000000)) } oraclize_randomDS_setCommitment(queryId, keccak256(abi.encodePacked(delay_bytes8_left, args[1], sha256(args[0]), args[2]))); return queryId; } function oraclize_randomDS_setCommitment(bytes32 _queryId, bytes32 _commitment) internal { oraclize_randomDS_args[_queryId] = _commitment; } function verifySig(bytes32 _tosignh, bytes memory _dersig, bytes memory _pubkey) internal returns (bool _sigVerified) { bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4 + (uint(uint8(_dersig[3])) - 0x20); sigr_ = copyBytes(_dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(_dersig, offset + (uint(uint8(_dersig[offset - 1])) - 0x20), 32, sigs_, 0); assembly { sigr := mload(add(sigr_, 32)) sigs := mload(add(sigs_, 32)) } (sigok, signer) = safer_ecrecover(_tosignh, 27, sigr, sigs); if (address(uint160(uint256(keccak256(_pubkey)))) == signer) { return true; } else { (sigok, signer) = safer_ecrecover(_tosignh, 28, sigr, sigs); return (address(uint160(uint256(keccak256(_pubkey)))) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes memory _proof, uint _sig2offset) internal returns (bool _proofVerified) { bool sigok; // Random DS Proof Step 6: Verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(uint8(_proof[_sig2offset + 1])) + 2); copyBytes(_proof, _sig2offset, sig2.length, sig2, 0); bytes memory appkey1_pubkey = new bytes(64); copyBytes(_proof, 3 + 1, 64, appkey1_pubkey, 0); bytes memory tosign2 = new bytes(1 + 65 + 32); tosign2[0] = byte(uint8(1)); //role copyBytes(_proof, _sig2offset - 65, 65, tosign2, 1); bytes memory CODEHASH = hex"fd94fa71bc0ba10d39d464d0d8f465efeef0a2764e3887fcc9df41ded20f505c"; copyBytes(CODEHASH, 0, 32, tosign2, 1 + 65); sigok = verifySig(sha256(tosign2), sig2, appkey1_pubkey); if (!sigok) { return false; } // Random DS Proof Step 7: Verify the APPKEY1 provenance (must be signed by Ledger) bytes memory LEDGERKEY = hex"7fb956469c5c9b89840d55b43537e66a98dd4811ea0a27224272c2e5622911e8537a2f8e86a46baec82864e98dd01e9ccc2f8bc5dfc9cbe5a91a290498dd96e4"; bytes memory tosign3 = new bytes(1 + 65); tosign3[0] = 0xFE; copyBytes(_proof, 3, 65, tosign3, 1); bytes memory sig3 = new bytes(uint(uint8(_proof[3 + 65 + 1])) + 2); copyBytes(_proof, 3 + 65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string memory _result, bytes memory _proof) internal returns (uint8 _returnCode) { // Random DS Proof Step 1: The prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L") || (_proof[1] != "P") || (uint8(_proof[2]) != uint8(1))) { return 1; } bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (!proofVerified) { return 2; } return 0; } function matchBytes32Prefix(bytes32 _content, bytes memory _prefix, uint _nRandomBytes) internal pure returns (bool _matchesPrefix) { bool match_ = true; require(_prefix.length == _nRandomBytes); for (uint256 i = 0; i< _nRandomBytes; i++) { if (_content[i] != _prefix[i]) { match_ = false; } } return match_; } function oraclize_randomDS_proofVerify__main(bytes memory _proof, bytes32 _queryId, bytes memory _result, string memory _contextName) internal returns (bool _proofVerified) { // Random DS Proof Step 2: The unique keyhash has to match with the sha256 of (context name + _queryId) uint ledgerProofLength = 3 + 65 + (uint(uint8(_proof[3 + 65 + 1])) + 2) + 32; bytes memory keyhash = new bytes(32); copyBytes(_proof, ledgerProofLength, 32, keyhash, 0); if (!(keccak256(keyhash) == keccak256(abi.encodePacked(sha256(abi.encodePacked(_contextName, _queryId)))))) { return false; } bytes memory sig1 = new bytes(uint(uint8(_proof[ledgerProofLength + (32 + 8 + 1 + 32) + 1])) + 2); copyBytes(_proof, ledgerProofLength + (32 + 8 + 1 + 32), sig1.length, sig1, 0); // Random DS Proof Step 3: We assume sig1 is valid (it will be verified during step 5) and we verify if '_result' is the _prefix of sha256(sig1) if (!matchBytes32Prefix(sha256(sig1), _result, uint(uint8(_proof[ledgerProofLength + 32 + 8])))) { return false; } // Random DS Proof Step 4: Commitment match verification, keccak256(delay, nbytes, unonce, sessionKeyHash) == commitment in storage. // This is to verify that the computed args match with the ones specified in the query. bytes memory commitmentSlice1 = new bytes(8 + 1 + 32); copyBytes(_proof, ledgerProofLength + 32, 8 + 1 + 32, commitmentSlice1, 0); bytes memory sessionPubkey = new bytes(64); uint sig2offset = ledgerProofLength + 32 + (8 + 1 + 32) + sig1.length + 65; copyBytes(_proof, sig2offset - 64, 64, sessionPubkey, 0); bytes32 sessionPubkeyHash = sha256(sessionPubkey); if (oraclize_randomDS_args[_queryId] == keccak256(abi.encodePacked(commitmentSlice1, sessionPubkeyHash))) { //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[_queryId]; } else return false; // Random DS Proof Step 5: Validity verification for sig1 (keyhash and args signed with the sessionKey) bytes memory tosign1 = new bytes(32 + 8 + 1 + 32); copyBytes(_proof, ledgerProofLength, 32 + 8 + 1 + 32, tosign1, 0); if (!verifySig(sha256(tosign1), sig1, sessionPubkey)) { return false; } // Verify if sessionPubkeyHash was verified already, if not.. let's do it! if (!oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]) { oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash] = oraclize_randomDS_proofVerify__sessionKeyValidity(_proof, sig2offset); } return oraclize_randomDS_sessionKeysHashVerified[sessionPubkeyHash]; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function copyBytes(bytes memory _from, uint _fromOffset, uint _length, bytes memory _to, uint _toOffset) internal pure returns (bytes memory _copiedBytes) { uint minLength = _length + _toOffset; require(_to.length >= minLength); // Buffer too small. Should be a better way? uint i = 32 + _fromOffset; // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint j = 32 + _toOffset; while (i < (32 + _fromOffset + _length)) { assembly { let tmp := mload(add(_from, i)) mstore(add(_to, j), tmp) } i += 32; j += 32; } return _to; } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license Duplicate Solidity's ecrecover, but catching the CALL return value */ function safer_ecrecover(bytes32 _hash, uint8 _v, bytes32 _r, bytes32 _s) internal returns (bool _success, address _recoveredAddress) { /* We do our own memory management here. Solidity uses memory offset 0x40 to store the current end of memory. We write past it (as writes are memory extensions), but don't update the offset so Solidity will reuse it. The memory used here is only needed for this context. FIXME: inline assembly can't access return values */ bool ret; address addr; assembly { let size := mload(0x40) mstore(size, _hash) mstore(add(size, 32), _v) mstore(add(size, 64), _r) mstore(add(size, 96), _s) ret := call(3000, 1, 0, size, 128, size, 32) // NOTE: we can reuse the request memory because we deal with the return code. addr := mload(size) } return (ret, addr); } /* The following function has been written by Alex Beregszaszi (@axic), use it under the terms of the MIT license */ function ecrecovery(bytes32 _hash, bytes memory _sig) internal returns (bool _success, address _recoveredAddress) { bytes32 r; bytes32 s; uint8 v; if (_sig.length != 65) { return (false, address(0)); } /* The signature format is a compact form of: {bytes32 r}{bytes32 s}{uint8 v} Compact means, uint8 is not padded to 32 bytes. */ assembly { r := mload(add(_sig, 32)) s := mload(add(_sig, 64)) /* Here we are loading the last 32 bytes. We exploit the fact that 'mload' will pad with zeroes if we overread. There is no 'mload8' to do this, but that would be nicer. */ v := byte(0, mload(add(_sig, 96))) /* Alternative solution: 'byte' is not working due to the Solidity parser, so lets use the second best option, 'and' v := and(mload(add(_sig, 65)), 255) */ } /* albeit non-transactional signatures are not specified by the YP, one would expect it to match the YP range of [27, 28] geth uses [0, 1] and some clients have followed. This might change, see: https://github.com/ethereum/go-ethereum/issues/2053 */ if (v < 27) { v += 27; } if (v != 27 && v != 28) { return (false, address(0)); } return safer_ecrecover(_hash, v, r, s); } function safeMemoryCleaner() internal pure { assembly { let fmem := mload(0x40) codecopy(fmem, codesize, sub(msize, fmem)) } } } /* END ORACLIZE_API */ // File: nexusmutual-contracts/contracts/Quotation.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Quotation is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; TokenController internal tc; TokenData internal td; Pool1 internal p1; PoolData internal pd; QuotationData internal qd; MCR internal m1; MemberRoles internal mr; bool internal locked; event RefundEvent(address indexed user, bool indexed status, uint holdedCoverID, bytes32 reason); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); mr = MemberRoles(ms.getLatestAddress("MR")); } function sendEther() public payable { } /** * @dev Expires a cover after a set period of time. * Changes the status of the Cover and reduces the current * sum assured of all areas in which the quotation lies * Unlocks the CN tokens of the cover. Updates the Total Sum Assured value. * @param _cid Cover Id. */ function expireCover(uint _cid) public { require(checkCoverExpired(_cid) && qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.CoverExpired)); tf.unlockCN(_cid); bytes4 curr; address scAddress; uint sumAssured; (, , scAddress, curr, sumAssured, ) = qd.getCoverDetailsByCoverID1(_cid); if (qd.getCoverStatusNo(_cid) != uint(QuotationData.CoverStatus.ClaimAccepted)) _removeSAFromCSA(_cid, sumAssured); qd.changeCoverStatusNo(_cid, uint8(QuotationData.CoverStatus.CoverExpired)); } /** * @dev Checks if a cover should get expired/closed or not. * @param _cid Cover Index. * @return expire true if the Cover's time has expired, false otherwise. */ function checkCoverExpired(uint _cid) public view returns(bool expire) { expire = qd.getValidityOfCover(_cid) < uint64(now); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function removeSAFromCSA(uint _cid, uint _amount) public onlyInternal { _removeSAFromCSA(_cid, _amount); } /** * @dev Makes Cover funded via NXM tokens. * @param smartCAdd Smart Contract Address */ function makeCoverUsingNXMTokens( uint[] memory coverDetails, uint16 coverPeriod, bytes4 coverCurr, address smartCAdd, uint8 _v, bytes32 _r, bytes32 _s ) public isMemberAndcheckPause { tc.burnFrom(msg.sender, coverDetails[2]); //need burn allowance _verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Verifies cover details signed off chain. * @param from address of funder. * @param scAddress Smart Contract Address */ function verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public onlyInternal { _verifyCoverDetails( from, scAddress, coverCurr, coverDetails, coverPeriod, _v, _r, _s ); } /** * @dev Verifies signature. * @param coverDetails details related to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. * @param _v argument from vrs hash. * @param _r argument from vrs hash. * @param _s argument from vrs hash. */ function verifySign( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA, uint8 _v, bytes32 _r, bytes32 _s ) public view returns(bool) { require(smaratCA != address(0)); require(pd.capReached() == 1, "Can not buy cover until cap reached for 1st time"); bytes32 hash = getOrderHash(coverDetails, coverPeriod, curr, smaratCA); return isValidSignature(hash, _v, _r, _s); } /** * @dev Gets order hash for given cover details. * @param coverDetails details realted to cover. * @param coverPeriod validity of cover. * @param smaratCA smarat contract address. */ function getOrderHash( uint[] memory coverDetails, uint16 coverPeriod, bytes4 curr, address smaratCA ) public view returns(bytes32) { return keccak256( abi.encodePacked( coverDetails[0], curr, coverPeriod, smaratCA, coverDetails[1], coverDetails[2], coverDetails[3], coverDetails[4], address(this) ) ); } /** * @dev Verifies signature. * @param hash order hash * @param v argument from vrs hash. * @param r argument from vrs hash. * @param s argument from vrs hash. */ function isValidSignature(bytes32 hash, uint8 v, bytes32 r, bytes32 s) public view returns(bool) { bytes memory prefix = "\x19Ethereum Signed Message:\n32"; bytes32 prefixedHash = keccak256(abi.encodePacked(prefix, hash)); address a = ecrecover(prefixedHash, v, r, s); return (a == qd.getAuthQuoteEngine()); } /** * @dev to get the status of recently holded coverID * @param userAdd is the user address in concern * @return the status of the concerned coverId */ function getRecentHoldedCoverIdStatus(address userAdd) public view returns(int) { uint holdedCoverLen = qd.getUserHoldedCoverLength(userAdd); if (holdedCoverLen == 0) { return -1; } else { uint holdedCoverID = qd.getUserHoldedCoverByIndex(userAdd, holdedCoverLen.sub(1)); return int(qd.holdedCoverIDStatus(holdedCoverID)); } } /** * @dev to initiate the membership and the cover * @param smartCAdd is the smart contract address to make cover on * @param coverCurr is the currency used to make cover * @param coverDetails list of details related to cover like cover amount, expire time, coverCurrPrice and priceNXM * @param coverPeriod is cover period for which cover is being bought * @param _v argument from vrs hash * @param _r argument from vrs hash * @param _s argument from vrs hash */ function initiateMembershipAndCover( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public payable checkPause { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(!ms.isMember(msg.sender)); require(qd.refundEligible(msg.sender) == false); uint joinFee = td.joiningFee(); uint totalFee = joinFee; if (coverCurr == "ETH") { totalFee = joinFee.add(coverDetails[1]); } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1])); } require(msg.value == totalFee); require(verifySign(coverDetails, coverPeriod, coverCurr, smartCAdd, _v, _r, _s)); qd.addHoldCover(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod); qd.setRefundEligible(msg.sender, true); } /** * @dev to get the verdict of kyc process * @param status is the kyc status * @param _add is the address of member */ function kycVerdict(address _add, bool status) public checkPause noReentrancy { require(msg.sender == qd.kycAuthAddress()); _kycTrigger(status, _add); } /** * @dev transfering Ethers to newly created quotation contract. */ function transferAssetsToNewContract(address newAdd) public onlyInternal noReentrancy { uint amount = address(this).balance; IERC20 erc20; if (amount > 0) { // newAdd.transfer(amount); Quotation newQT = Quotation(newAdd); newQT.sendEther.value(amount)(); } uint currAssetLen = pd.getAllCurrenciesLen(); for (uint64 i = 1; i < currAssetLen; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); address currAddr = pd.getCurrencyAssetAddress(currName); erc20 = IERC20(currAddr); //solhint-disable-line if (erc20.balanceOf(address(this)) > 0) { require(erc20.transfer(newAdd, erc20.balanceOf(address(this)))); } } } /** * @dev Creates cover of the quotation, changes the status of the quotation , * updates the total sum assured and locks the tokens of the cover against a quote. * @param from Quote member Ethereum address. */ function _makeCover ( //solhint-disable-line address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod ) internal { uint cid = qd.getCoverLength(); qd.addCover(coverPeriod, coverDetails[0], from, coverCurr, scAddress, coverDetails[1], coverDetails[2]); // if cover period of quote is less than 60 days. if (coverPeriod <= 60) { p1.closeCoverOraclise(cid, uint64(uint(coverPeriod).mul(1 days))); } uint coverNoteAmount = (coverDetails[2].mul(qd.tokensRetained())).div(100); tc.mint(from, coverNoteAmount); tf.lockCN(coverNoteAmount, coverPeriod, cid, from); qd.addInTotalSumAssured(coverCurr, coverDetails[0]); qd.addInTotalSumAssuredSC(scAddress, coverCurr, coverDetails[0]); tf.pushStakerRewards(scAddress, coverDetails[2]); } /** * @dev Makes a vover. * @param from address of funder. * @param scAddress Smart Contract Address */ function _verifyCoverDetails( address payable from, address scAddress, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) internal { require(coverDetails[3] > now); require(!qd.timestampRepeated(coverDetails[4])); qd.setTimestampRepeated(coverDetails[4]); require(verifySign(coverDetails, coverPeriod, coverCurr, scAddress, _v, _r, _s)); _makeCover(from, scAddress, coverCurr, coverDetails, coverPeriod); } /** * @dev Updates the Sum Assured Amount of all the quotation. * @param _cid Cover id * @param _amount that will get subtracted Current Sum Assured * amount that comes under a quotation. */ function _removeSAFromCSA(uint _cid, uint _amount) internal checkPause { address _add; bytes4 coverCurr; (, , _add, coverCurr, , ) = qd.getCoverDetailsByCoverID1(_cid); qd.subFromTotalSumAssured(coverCurr, _amount); qd.subFromTotalSumAssuredSC(_add, coverCurr, _amount); } /** * @dev to trigger the kyc process * @param status is the kyc status * @param _add is the address of member */ function _kycTrigger(bool status, address _add) internal { uint holdedCoverLen = qd.getUserHoldedCoverLength(_add).sub(1); uint holdedCoverID = qd.getUserHoldedCoverByIndex(_add, holdedCoverLen); address payable userAdd; address scAddress; bytes4 coverCurr; uint16 coverPeriod; uint[] memory coverDetails = new uint[](4); IERC20 erc20; (, userAdd, coverDetails) = qd.getHoldedCoverDetailsByID2(holdedCoverID); (, scAddress, coverCurr, coverPeriod) = qd.getHoldedCoverDetailsByID1(holdedCoverID); require(qd.refundEligible(userAdd)); qd.setRefundEligible(userAdd, false); require(qd.holdedCoverIDStatus(holdedCoverID) == uint(QuotationData.HCIDStatus.kycPending)); uint joinFee = td.joiningFee(); if (status) { mr.payJoiningFee.value(joinFee)(userAdd); if (coverDetails[3] > now) { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPass)); address poolAdd = ms.getLatestAddress("P1"); if (coverCurr == "ETH") { p1.sendEther.value(coverDetails[1])(); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(poolAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "KYC Passed"); _makeCover(userAdd, scAddress, coverCurr, coverDetails, coverPeriod); } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycPassNoCover)); if (coverCurr == "ETH") { userAdd.transfer(coverDetails[1]); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } emit RefundEvent(userAdd, status, holdedCoverID, "Cover Failed"); } } else { qd.setHoldedCoverIDStatus(holdedCoverID, uint(QuotationData.HCIDStatus.kycFailedOrRefunded)); uint totalRefund = joinFee; if (coverCurr == "ETH") { totalRefund = coverDetails[1].add(joinFee); } else { erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //solhint-disable-line require(erc20.transfer(userAdd, coverDetails[1])); } userAdd.transfer(totalRefund); emit RefundEvent(userAdd, status, holdedCoverID, "KYC Failed"); } } } // File: nexusmutual-contracts/contracts/external/uniswap/solidity-interface.sol pragma solidity 0.5.7; contract Factory { function getExchange(address token) public view returns (address); function getToken(address exchange) public view returns (address); } contract Exchange { function getEthToTokenInputPrice(uint256 ethSold) public view returns(uint256); function getTokenToEthInputPrice(uint256 tokensSold) public view returns(uint256); function ethToTokenSwapInput(uint256 minTokens, uint256 deadline) public payable returns (uint256); function ethToTokenTransferInput(uint256 minTokens, uint256 deadline, address recipient) public payable returns (uint256); function tokenToEthSwapInput(uint256 tokensSold, uint256 minEth, uint256 deadline) public payable returns (uint256); function tokenToEthTransferInput(uint256 tokensSold, uint256 minEth, uint256 deadline, address recipient) public payable returns (uint256); function tokenToTokenSwapInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address tokenAddress ) public returns (uint256); function tokenToTokenTransferInput( uint256 tokensSold, uint256 minTokensBought, uint256 minEthBought, uint256 deadline, address recipient, address tokenAddress ) public returns (uint256); } // File: nexusmutual-contracts/contracts/Pool2.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool2 is Iupgradable { using SafeMath for uint; MCR internal m1; Pool1 internal p1; PoolData internal pd; Factory internal factory; address public uniswapFactoryAddress; uint internal constant DECIMAL1E18 = uint(10) ** 18; bool internal locked; constructor(address _uniswapFactoryAdd) public { uniswapFactoryAddress = _uniswapFactoryAdd; factory = Factory(_uniswapFactoryAdd); } function() external payable {} event Liquidity(bytes16 typeOf, bytes16 functionName); event Rebalancing(bytes4 iaCurr, uint tokenAmount); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } /** * @dev to change the uniswap factory address * @param newFactoryAddress is the new factory address in concern * @return the status of the concerned coverId */ function changeUniswapFactoryAddress(address newFactoryAddress) external onlyInternal { // require(ms.isOwner(msg.sender) || ms.checkIsAuthToGoverned(msg.sender)); uniswapFactoryAddress = newFactoryAddress; factory = Factory(uniswapFactoryAddress); } /** * @dev On upgrade transfer all investment assets and ether to new Investment Pool * @param newPoolAddress New Investment Assest Pool address */ function upgradeInvestmentPool(address payable newPoolAddress) external onlyInternal noReentrancy { uint len = pd.getInvestmentCurrencyLen(); for (uint64 i = 1; i < len; i++) { bytes4 iaName = pd.getInvestmentCurrencyByIndex(i); _upgradeInvestmentPool(iaName, newPoolAddress); } if (address(this).balance > 0) { Pool2 newP2 = Pool2(newPoolAddress); newP2.sendEther.value(address(this).balance)(); } } /** * @dev Internal Swap of assets between Capital * and Investment Sub pool for excess or insufficient * liquidity conditions of a given currency. */ function internalLiquiditySwap(bytes4 curr) external onlyInternal noReentrancy { uint caBalance; uint baseMin; uint varMin; (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { _internalExcessLiquiditySwap(curr, baseMin, varMin, caBalance); } else if (caBalance < uint(baseMin).add(varMin)) { _internalInsufficientLiquiditySwap(curr, baseMin, varMin, caBalance); } } /** * @dev Saves a given investment asset details. To be called daily. * @param curr array of Investment asset name. * @param rate array of investment asset exchange rate. * @param date current date in yyyymmdd. */ function saveIADetails(bytes4[] calldata curr, uint64[] calldata rate, uint64 date, bool bit) external checkPause noReentrancy { bytes4 maxCurr; bytes4 minCurr; uint64 maxRate; uint64 minRate; //ONLY NOTARZIE ADDRESS CAN POST require(pd.isnotarise(msg.sender)); (maxCurr, maxRate, minCurr, minRate) = _calculateIARank(curr, rate); pd.saveIARankDetails(maxCurr, maxRate, minCurr, minRate, date); pd.updatelastDate(date); uint len = curr.length; for (uint i = 0; i < len; i++) { pd.updateIAAvgRate(curr[i], rate[i]); } if (bit) //for testing purpose _rebalancingLiquidityTrading(maxCurr, maxRate); p1.saveIADetailsOracalise(pd.iaRatesTime()); } /** * @dev External Trade for excess or insufficient * liquidity conditions of a given currency. */ function externalLiquidityTrade() external onlyInternal { bool triggerTrade; bytes4 curr; bytes4 minIACurr; bytes4 maxIACurr; uint amount; uint minIARate; uint maxIARate; uint baseMin; uint varMin; uint caBalance; (maxIACurr, maxIARate, minIACurr, minIARate) = pd.getIARankDetailsByDate(pd.getLastDate()); uint len = pd.getAllCurrenciesLen(); for (uint64 i = 0; i < len; i++) { curr = pd.getCurrenciesByIndex(i); (, baseMin, varMin) = pd.getCurrencyAssetVarBase(curr); caBalance = _getCurrencyAssetsBalance(curr); if (caBalance > uint(baseMin).add(varMin).mul(2)) { //excess amount = caBalance.sub(((uint(baseMin).add(varMin)).mul(3)).div(2)); //*10**18; triggerTrade = _externalExcessLiquiditySwap(curr, minIACurr, amount); } else if (caBalance < uint(baseMin).add(varMin)) { // insufficient amount = (((uint(baseMin).add(varMin)).mul(3)).div(2)).sub(caBalance); triggerTrade = _externalInsufficientLiquiditySwap(curr, maxIACurr, amount); } if (triggerTrade) { p1.triggerExternalLiquidityTrade(); } } } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { m1 = MCR(ms.getLatestAddress("MC")); pd = PoolData(ms.getLatestAddress("PD")); p1 = Pool1(ms.getLatestAddress("P1")); } function sendEther() public payable { } /** * @dev Gets currency asset balance for a given currency name. */ function _getCurrencyAssetsBalance(bytes4 _curr) public view returns(uint caBalance) { if (_curr == "ETH") { caBalance = address(p1).balance; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); caBalance = erc20.balanceOf(address(p1)); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _transferInvestmentAsset( bytes4 _curr, address _transferTo, uint _amount ) internal { if (_curr == "ETH") { if (_amount > address(this).balance) _amount = address(this).balance; p1.sendEther.value(_amount)(); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (_amount > erc20.balanceOf(address(this))) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(_transferTo, _amount)); } } /** * @dev to perform rebalancing * @param iaCurr is the investment asset currency * @param iaRate is the investment asset rate */ function _rebalancingLiquidityTrading( bytes4 iaCurr, uint64 iaRate ) internal checkPause { uint amountToSell; uint totalRiskBal = pd.getLastVfull(); uint intermediaryEth; uint ethVol = pd.ethVolumeLimit(); totalRiskBal = (totalRiskBal.mul(100000)).div(DECIMAL1E18); Exchange exchange; if (totalRiskBal > 0) { amountToSell = ((totalRiskBal.mul(2).mul( iaRate)).mul(pd.variationPercX100())).div(100 * 100 * 100000); amountToSell = (amountToSell.mul( 10**uint(pd.getInvestmentAssetDecimals(iaCurr)))).div(100); // amount of asset to sell if (iaCurr != "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(iaCurr))); intermediaryEth = exchange.getTokenToEthInputPrice(amountToSell); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amountToSell = (exchange.getEthToTokenInputPrice(intermediaryEth).mul(995)).div(1000); } IERC20 erc20; erc20 = IERC20(pd.getCurrencyAssetAddress(iaCurr)); erc20.approve(address(exchange), amountToSell); exchange.tokenToEthSwapInput(amountToSell, (exchange.getTokenToEthInputPrice( amountToSell).mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else if (iaCurr == "ETH" && _checkTradeConditions(iaCurr, iaRate, totalRiskBal)) { _transferInvestmentAsset(iaCurr, ms.getLatestAddress("P1"), amountToSell); } emit Rebalancing(iaCurr, amountToSell); } } /** * @dev Checks whether trading is required for a * given investment asset at a given exchange rate. */ function _checkTradeConditions( bytes4 curr, uint64 iaRate, uint totalRiskBal ) internal view returns(bool check) { if (iaRate > 0) { uint iaBalance = _getInvestmentAssetBalance(curr).div(DECIMAL1E18); if (iaBalance > 0 && totalRiskBal > 0) { uint iaMax; uint iaMin; uint checkNumber; uint z; (iaMin, iaMax) = pd.getInvestmentAssetHoldingPerc(curr); z = pd.variationPercX100(); checkNumber = (iaBalance.mul(100 * 100000)).div(totalRiskBal.mul(iaRate)); if ((checkNumber > ((totalRiskBal.mul(iaMax.add(z))).mul(100000)).div(100)) || (checkNumber < ((totalRiskBal.mul(iaMin.sub(z))).mul(100000)).div(100))) check = true; //eligibleIA } } } /** * @dev Gets the investment asset rank. */ function _getIARank( bytes4 curr, uint64 rateX100, uint totalRiskPoolBalance ) internal view returns (int rhsh, int rhsl) //internal function { uint currentIAmaxHolding; uint currentIAminHolding; uint iaBalance = _getInvestmentAssetBalance(curr); (currentIAminHolding, currentIAmaxHolding) = pd.getInvestmentAssetHoldingPerc(curr); if (rateX100 > 0) { uint rhsf; rhsf = (iaBalance.mul(1000000)).div(totalRiskPoolBalance.mul(rateX100)); rhsh = int(rhsf - currentIAmaxHolding); rhsl = int(rhsf - currentIAminHolding); } } /** * @dev Calculates the investment asset rank. */ function _calculateIARank( bytes4[] memory curr, uint64[] memory rate ) internal view returns( bytes4 maxCurr, uint64 maxRate, bytes4 minCurr, uint64 minRate ) { int max = 0; int min = -1; int rhsh; int rhsl; uint totalRiskPoolBalance; (totalRiskPoolBalance, ) = m1.calVtpAndMCRtp(); uint len = curr.length; for (uint i = 0; i < len; i++) { rhsl = 0; rhsh = 0; if (pd.getInvestmentAssetStatus(curr[i])) { (rhsh, rhsl) = _getIARank(curr[i], rate[i], totalRiskPoolBalance); if (rhsh > max || i == 0) { max = rhsh; maxCurr = curr[i]; maxRate = rate[i]; } if (rhsl < min || rhsl == 0 || i == 0) { min = rhsl; minCurr = curr[i]; minRate = rate[i]; } } } } /** * @dev to get balance of an investment asset * @param _curr is the investment asset in concern * @return the balance */ function _getInvestmentAssetBalance(bytes4 _curr) internal view returns (uint balance) { if (_curr == "ETH") { balance = address(this).balance; } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); balance = erc20.balanceOf(address(this)); } } /** * @dev Creates Excess liquidity trading order for a given currency and a given balance. */ function _internalExcessLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { // require(ms.isInternal(msg.sender) || md.isnotarise(msg.sender)); bytes4 minIACurr; // uint amount; (, , minIACurr, ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == minIACurr) { // amount = _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2)); //*10**18; p1.transferCurrencyAsset(_curr, _caBalance.sub(((_baseMin.add(_varMin)).mul(3)).div(2))); } else { p1.triggerExternalLiquidityTrade(); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. */ function _internalInsufficientLiquiditySwap(bytes4 _curr, uint _baseMin, uint _varMin, uint _caBalance) internal { bytes4 maxIACurr; uint amount; (maxIACurr, , , ) = pd.getIARankDetailsByDate(pd.getLastDate()); if (_curr == maxIACurr) { amount = (((_baseMin.add(_varMin)).mul(3)).div(2)).sub(_caBalance); _transferInvestmentAsset(_curr, ms.getLatestAddress("P1"), amount); } else { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); if ((maxIACurr == "ETH" && address(this).balance > 0) || (maxIACurr != "ETH" && erc20.balanceOf(address(this)) > 0)) p1.triggerExternalLiquidityTrade(); } } /** * @dev Creates External excess liquidity trading * order for a given currency and a given balance. * @param curr Currency Asset to Sell * @param minIACurr Investment Asset to Buy * @param amount Amount of Currency Asset to Sell */ function _externalExcessLiquiditySwap( bytes4 curr, bytes4 minIACurr, uint256 amount ) internal returns (bool trigger) { uint intermediaryEth; Exchange exchange; IERC20 erc20; uint ethVol = pd.ethVolumeLimit(); if (curr == minIACurr) { p1.transferCurrencyAsset(curr, amount); } else if (curr == "ETH" && minIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(minIACurr))); if (amount > (address(exchange).balance.mul(ethVol)).div(100)) { // 4% ETH volume limit amount = (address(exchange).balance.mul(ethVol)).div(100); trigger = true; } p1.transferCurrencyAsset(curr, amount); exchange.ethToTokenSwapInput.value(amount) (exchange.getEthToTokenInputPrice(amount).mul(995).div(1000), pd.uniswapDeadline().add(now)); } else if (curr != "ETH" && minIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getTokenToEthInputPrice(amount); trigger = true; } p1.transferCurrencyAsset(curr, amount); // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), amount); exchange.tokenToEthSwapInput(amount, ( intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now)); } else { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(ethVol)).div(100)) { intermediaryEth = (address(exchange).balance.mul(ethVol)).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } Exchange tmp = Exchange(factory.getExchange( pd.getInvestmentAssetAddress(minIACurr))); // minIACurr exchange if (intermediaryEth > address(tmp).balance.mul(ethVol).div(100)) { intermediaryEth = address(tmp).balance.mul(ethVol).div(100); amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } p1.transferCurrencyAsset(curr, amount); erc20 = IERC20(pd.getCurrencyAssetAddress(curr)); erc20.approve(address(exchange), amount); exchange.tokenToTokenSwapInput(amount, (tmp.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), (intermediaryEth.mul(995)).div(1000), pd.uniswapDeadline().add(now), pd.getInvestmentAssetAddress(minIACurr)); } } /** * @dev insufficient liquidity swap * for a given currency and a given balance. * @param curr Currency Asset to buy * @param maxIACurr Investment Asset to sell * @param amount Amount of Investment Asset to sell */ function _externalInsufficientLiquiditySwap( bytes4 curr, bytes4 maxIACurr, uint256 amount ) internal returns (bool trigger) { Exchange exchange; IERC20 erc20; uint intermediaryEth; // uint ethVol = pd.ethVolumeLimit(); if (curr == maxIACurr) { _transferInvestmentAsset(curr, ms.getLatestAddress("P1"), amount); } else if (curr == "ETH" && maxIACurr != "ETH") { exchange = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); intermediaryEth = exchange.getEthToTokenInputPrice(amount); if (amount > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { amount = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); intermediaryEth = exchange.getEthToTokenInputPrice(amount); trigger = true; } erc20 = IERC20(pd.getCurrencyAssetAddress(maxIACurr)); if (intermediaryEth > erc20.balanceOf(address(this))) { intermediaryEth = erc20.balanceOf(address(this)); } // erc20.decreaseAllowance(address(exchange), erc20.allowance(address(this), address(exchange))); erc20.approve(address(exchange), intermediaryEth); exchange.tokenToEthTransferInput(intermediaryEth, ( exchange.getTokenToEthInputPrice(intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else if (curr != "ETH" && maxIACurr == "ETH") { exchange = Exchange(factory.getExchange(pd.getCurrencyAssetAddress(curr))); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > address(this).balance) intermediaryEth = address(this).balance; if (intermediaryEth > (address(exchange).balance.mul (pd.ethVolumeLimit())).div(100)) { // 4% ETH volume limit intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } exchange.ethToTokenTransferInput.value(intermediaryEth)((exchange.getEthToTokenInputPrice( intermediaryEth).mul(995)).div(1000), pd.uniswapDeadline().add(now), address(p1)); } else { address currAdd = pd.getCurrencyAssetAddress(curr); exchange = Exchange(factory.getExchange(currAdd)); intermediaryEth = exchange.getTokenToEthInputPrice(amount); if (intermediaryEth > (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100)) { intermediaryEth = (address(exchange).balance.mul(pd.ethVolumeLimit())).div(100); trigger = true; } Exchange tmp = Exchange(factory.getExchange(pd.getInvestmentAssetAddress(maxIACurr))); if (intermediaryEth > address(tmp).balance.mul(pd.ethVolumeLimit()).div(100)) { intermediaryEth = address(tmp).balance.mul(pd.ethVolumeLimit()).div(100); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); trigger = true; } uint maxIAToSell = tmp.getEthToTokenInputPrice(intermediaryEth); erc20 = IERC20(pd.getInvestmentAssetAddress(maxIACurr)); uint maxIABal = erc20.balanceOf(address(this)); if (maxIAToSell > maxIABal) { maxIAToSell = maxIABal; intermediaryEth = tmp.getTokenToEthInputPrice(maxIAToSell); // amount = exchange.getEthToTokenInputPrice(intermediaryEth); } amount = exchange.getEthToTokenInputPrice(intermediaryEth); erc20.approve(address(tmp), maxIAToSell); tmp.tokenToTokenTransferInput(maxIAToSell, ( amount.mul(995)).div(1000), ( intermediaryEth), pd.uniswapDeadline().add(now), address(p1), currAdd); } } /** * @dev Transfers ERC20 investment asset from this Pool to another Pool. */ function _upgradeInvestmentPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getInvestmentAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } } // File: nexusmutual-contracts/contracts/Pool1.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Pool1 is usingOraclize, Iupgradable { using SafeMath for uint; Quotation internal q2; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; Pool2 internal p2; PoolData internal pd; MCR internal m1; Claims public c1; TokenData internal td; bool internal locked; uint internal constant DECIMAL1E18 = uint(10) ** 18; // uint internal constant PRICE_STEP = uint(1000) * DECIMAL1E18; event Apiresult(address indexed sender, string msg, bytes32 myid); event Payout(address indexed to, uint coverId, uint tokens); modifier noReentrancy() { require(!locked, "Reentrant call."); locked = true; _; locked = false; } function () external payable {} //solhint-disable-line /** * @dev Pays out the sum assured in case a claim is accepted * @param coverid Cover Id. * @param claimid Claim Id. * @return succ true if payout is successful, false otherwise. */ function sendClaimPayout( uint coverid, uint claimid, uint sumAssured, address payable coverHolder, bytes4 coverCurr ) external onlyInternal noReentrancy returns(bool succ) { uint sa = sumAssured.div(DECIMAL1E18); bool check; IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); //Payout if (coverCurr == "ETH" && address(this).balance >= sumAssured) { // check = _transferCurrencyAsset(coverCurr, coverHolder, sumAssured); coverHolder.transfer(sumAssured); check = true; } else if (coverCurr == "DAI" && erc20.balanceOf(address(this)) >= sumAssured) { erc20.transfer(coverHolder, sumAssured); check = true; } if (check == true) { q2.removeSAFromCSA(coverid, sa); pd.changeCurrencyAssetVarMin(coverCurr, pd.getCurrencyAssetVarMin(coverCurr).sub(sumAssured)); emit Payout(coverHolder, coverid, sumAssured); succ = true; } else { c1.setClaimStatus(claimid, 12); } _triggerExternalLiquidityTrade(); // p2.internalLiquiditySwap(coverCurr); tf.burnStakerLockedToken(coverid, coverCurr, sumAssured); } /** * @dev to trigger external liquidity trade */ function triggerExternalLiquidityTrade() external onlyInternal { _triggerExternalLiquidityTrade(); } ///@dev Oraclize call to close emergency pause. function closeEmergencyPause(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 300000); _saveApiDetails(myid, "EP", 0); } /// @dev Calls the Oraclize Query to close a given Claim after a given period of time. /// @param id Claim Id to be closed /// @param time Time (in seconds) after which Claims assessment voting needs to be closed function closeClaimsOraclise(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 3000000); _saveApiDetails(myid, "CLA", id); } /// @dev Calls Oraclize Query to expire a given Cover after a given period of time. /// @param id Quote Id to be expired /// @param time Time (in seconds) after which the cover should be expired function closeCoverOraclise(uint id, uint64 time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", strConcat( "http://a1.nexusmutual.io/api/Claims/closeClaim_hash/", uint2str(id)), 1000000); _saveApiDetails(myid, "COV", id); } /// @dev Calls the Oraclize Query to initiate MCR calculation. /// @param time Time (in milliseconds) after which the next MCR calculation should be initiated function mcrOraclise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/postMCR/M1", 0); _saveApiDetails(myid, "MCR", 0); } /// @dev Calls the Oraclize Query in case MCR calculation fails. /// @param time Time (in seconds) after which the next MCR calculation should be initiated function mcrOracliseFail(uint id, uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(4, time, "URL", "", 1000000); _saveApiDetails(myid, "MCRF", id); } /// @dev Oraclize call to update investment asset rates. function saveIADetailsOracalise(uint time) external onlyInternal { bytes32 myid = _oraclizeQuery(3, time, "URL", "https://api.nexusmutual.io/saveIADetails/M1", 0); _saveApiDetails(myid, "IARB", 0); } /** * @dev Transfers all assest (i.e ETH balance, Currency Assest) from old Pool to new Pool * @param newPoolAddress Address of the new Pool */ function upgradeCapitalPool(address payable newPoolAddress) external noReentrancy onlyInternal { for (uint64 i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 caName = pd.getCurrenciesByIndex(i); _upgradeCapitalPool(caName, newPoolAddress); } if (address(this).balance > 0) { Pool1 newP1 = Pool1(newPoolAddress); newP1.sendEther.value(address(this).balance)(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { m1 = MCR(ms.getLatestAddress("MC")); tk = NXMToken(ms.tokenAddress()); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); pd = PoolData(ms.getLatestAddress("PD")); q2 = Quotation(ms.getLatestAddress("QT")); p2 = Pool2(ms.getLatestAddress("P2")); c1 = Claims(ms.getLatestAddress("CL")); td = TokenData(ms.getLatestAddress("TD")); } function sendEther() public payable { } /** * @dev transfers currency asset to an address * @param curr is the currency of currency asset to transfer * @param amount is amount of currency asset to transfer * @return boolean to represent success or failure */ function transferCurrencyAsset( bytes4 curr, uint amount ) public onlyInternal noReentrancy returns(bool) { return _transferCurrencyAsset(curr, amount); } /// @dev Handles callback of external oracle query. function __callback(bytes32 myid, string memory result) public { result; //silence compiler warning // owner will be removed from production build ms.delegateCallBack(myid); } /// @dev Enables user to purchase cover with funding in ETH. /// @param smartCAdd Smart Contract Address function makeCoverBegin( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause payable { require(msg.value == coverDetails[1]); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /** * @dev Enables user to purchase cover via currency asset eg DAI */ function makeCoverUsingCA( address smartCAdd, bytes4 coverCurr, uint[] memory coverDetails, uint16 coverPeriod, uint8 _v, bytes32 _r, bytes32 _s ) public isMember checkPause { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(coverCurr)); require(erc20.transferFrom(msg.sender, address(this), coverDetails[1]), "Transfer failed"); q2.verifyCoverDetails(msg.sender, smartCAdd, coverCurr, coverDetails, coverPeriod, _v, _r, _s); } /// @dev Enables user to purchase NXM at the current token price. function buyToken() public payable isMember checkPause returns(bool success) { require(msg.value > 0); uint tokenPurchased = _getToken(address(this).balance, msg.value); tc.mint(msg.sender, tokenPurchased); success = true; } /// @dev Sends a given amount of Ether to a given address. /// @param amount amount (in wei) to send. /// @param _add Receiver's address. /// @return succ True if transfer is a success, otherwise False. function transferEther(uint amount, address payable _add) public noReentrancy checkPause returns(bool succ) { require(ms.checkIsAuthToGoverned(msg.sender), "Not authorized to Govern"); succ = _add.send(amount); } /** * @dev Allows selling of NXM for ether. * Seller first needs to give this contract allowance to * transfer/burn tokens in the NXMToken contract * @param _amount Amount of NXM to sell * @return success returns true on successfull sale */ function sellNXMTokens(uint _amount) public isMember noReentrancy checkPause returns(bool success) { require(tk.balanceOf(msg.sender) >= _amount, "Not enough balance"); require(!tf.isLockedForMemberVote(msg.sender), "Member voted"); require(_amount <= m1.getMaxSellTokens(), "exceeds maximum token sell limit"); uint sellingPrice = _getWei(_amount); tc.burnFrom(msg.sender, _amount); msg.sender.transfer(sellingPrice); success = true; } /** * @dev gives the investment asset balance * @return investment asset balance */ function getInvestmentAssetBalance() public view returns (uint balance) { IERC20 erc20; uint currTokens; for (uint i = 1; i < pd.getInvestmentCurrencyLen(); i++) { bytes4 currency = pd.getInvestmentCurrencyByIndex(i); erc20 = IERC20(pd.getInvestmentAssetAddress(currency)); currTokens = erc20.balanceOf(address(p2)); if (pd.getIAAvgRate(currency) > 0) balance = balance.add((currTokens.mul(100)).div(pd.getIAAvgRate(currency))); } balance = balance.add(address(p2).balance); } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function getWei(uint amount) public view returns(uint weiToPay) { return _getWei(amount); } /** * @dev Returns the amount of token a buyer will get for corresponding wei * @param weiPaid Amount of wei * @return tokenToGet Amount of tokens the buyer will get */ function getToken(uint weiPaid) public view returns(uint tokenToGet) { return _getToken((address(this).balance).add(weiPaid), weiPaid); } /** * @dev to trigger external liquidity trade */ function _triggerExternalLiquidityTrade() internal { if (now > pd.lastLiquidityTradeTrigger().add(pd.liquidityTradeCallbackTime())) { pd.setLastLiquidityTradeTrigger(); bytes32 myid = _oraclizeQuery(4, pd.liquidityTradeCallbackTime(), "URL", "", 300000); _saveApiDetails(myid, "ULT", 0); } } /** * @dev Returns the amount of wei a seller will get for selling NXM * @param _amount Amount of NXM to sell * @return weiToPay Amount of wei the seller will get */ function _getWei(uint _amount) internal view returns(uint weiToPay) { uint tokenPrice; uint weiPaid; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calVtpAndMCRtp(); while (_amount > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tokenPrice = (tokenPrice.mul(975)).div(1000); //97.5% if (_amount <= td.priceStep().mul(DECIMAL1E18)) { weiToPay = weiToPay.add((tokenPrice.mul(_amount)).div(DECIMAL1E18)); break; } else { _amount = _amount.sub(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.sub(td.priceStep().mul(DECIMAL1E18)); weiPaid = (tokenPrice.mul(td.priceStep().mul(DECIMAL1E18))).div(DECIMAL1E18); vtp = vtp.sub(weiPaid); weiToPay = weiToPay.add(weiPaid); } } } /** * @dev gives the token * @param _poolBalance is the pool balance * @param _weiPaid is the amount paid in wei * @return the token to get */ function _getToken(uint _poolBalance, uint _weiPaid) internal view returns(uint tokenToGet) { uint tokenPrice; uint superWeiLeft = (_weiPaid).mul(DECIMAL1E18); uint tempTokens; uint superWeiSpent; uint tokenSupply = tk.totalSupply(); uint vtp; uint mcrFullperc; uint vFull; uint mcrtp; (mcrFullperc, , vFull, ) = pd.getLastMCR(); (vtp, ) = m1.calculateVtpAndMCRtp((_poolBalance).sub(_weiPaid)); require(m1.calculateTokenPrice("ETH") > 0, "Token price can not be zero"); while (superWeiLeft > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); tokenPrice = m1.calculateStepTokenPrice("ETH", mcrtp); tempTokens = superWeiLeft.div(tokenPrice); if (tempTokens <= td.priceStep().mul(DECIMAL1E18)) { tokenToGet = tokenToGet.add(tempTokens); break; } else { tokenToGet = tokenToGet.add(td.priceStep().mul(DECIMAL1E18)); tokenSupply = tokenSupply.add(td.priceStep().mul(DECIMAL1E18)); superWeiSpent = td.priceStep().mul(DECIMAL1E18).mul(tokenPrice); superWeiLeft = superWeiLeft.sub(superWeiSpent); vtp = vtp.add((td.priceStep().mul(DECIMAL1E18).mul(tokenPrice)).div(DECIMAL1E18)); } } } /** * @dev Save the details of the Oraclize API. * @param myid Id return by the oraclize query. * @param _typeof type of the query for which oraclize call is made. * @param id ID of the proposal, quote, cover etc. for which oraclize call is made. */ function _saveApiDetails(bytes32 myid, bytes4 _typeof, uint id) internal { pd.saveApiDetails(myid, _typeof, id); pd.addInAllApiCall(myid); } /** * @dev transfers currency asset * @param _curr is currency of asset to transfer * @param _amount is the amount to be transferred * @return boolean representing the success of transfer */ function _transferCurrencyAsset(bytes4 _curr, uint _amount) internal returns(bool succ) { if (_curr == "ETH") { if (address(this).balance < _amount) _amount = address(this).balance; p2.sendEther.value(_amount)(); succ = true; } else { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); //solhint-disable-line if (erc20.balanceOf(address(this)) < _amount) _amount = erc20.balanceOf(address(this)); require(erc20.transfer(address(p2), _amount)); succ = true; } } /** * @dev Transfers ERC20 Currency asset from this Pool to another Pool on upgrade. */ function _upgradeCapitalPool( bytes4 _curr, address _newPoolAddress ) internal { IERC20 erc20 = IERC20(pd.getCurrencyAssetAddress(_curr)); if (erc20.balanceOf(address(this)) > 0) require(erc20.transfer(_newPoolAddress, erc20.balanceOf(address(this)))); } /** * @dev oraclize query * @param paramCount is number of paramters passed * @param timestamp is the current timestamp * @param datasource in concern * @param arg in concern * @param gasLimit required for query * @return id of oraclize query */ function _oraclizeQuery( uint paramCount, uint timestamp, string memory datasource, string memory arg, uint gasLimit ) internal returns (bytes32 id) { if (paramCount == 4) { id = oraclize_query(timestamp, datasource, arg, gasLimit); } else if (paramCount == 3) { id = oraclize_query(timestamp, datasource, arg); } else { id = oraclize_query(datasource, arg); } } } // File: nexusmutual-contracts/contracts/MCR.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MCR is Iupgradable { using SafeMath for uint; Pool1 internal p1; PoolData internal pd; NXMToken internal tk; QuotationData internal qd; MemberRoles internal mr; TokenData internal td; ProposalCategory internal proposalCategory; uint private constant DECIMAL1E18 = uint(10) ** 18; uint private constant DECIMAL1E05 = uint(10) ** 5; uint private constant DECIMAL1E19 = uint(10) ** 19; uint private constant minCapFactor = uint(10) ** 21; uint public variableMincap; uint public dynamicMincapThresholdx100 = 13000; uint public dynamicMincapIncrementx100 = 100; event MCREvent( uint indexed date, uint blockNumber, bytes4[] allCurr, uint[] allCurrRates, uint mcrEtherx100, uint mcrPercx100, uint vFull ); /** * @dev Adds new MCR data. * @param mcrP Minimum Capital Requirement in percentage. * @param vF Pool1 fund value in Ether used in the last full daily calculation of the Capital model. * @param onlyDate Date(yyyymmdd) at which MCR details are getting added. */ function addMCRData( uint mcrP, uint mcrE, uint vF, bytes4[] calldata curr, uint[] calldata _threeDayAvg, uint64 onlyDate ) external checkPause { require(proposalCategory.constructorCheck()); require(pd.isnotarise(msg.sender)); if (mr.launched() && pd.capReached() != 1) { if (mcrP >= 10000) pd.setCapReached(1); } uint len = pd.getMCRDataLength(); _addMCRData(len, onlyDate, curr, mcrE, mcrP, vF, _threeDayAvg); } /** * @dev Adds MCR Data for last failed attempt. */ function addLastMCRData(uint64 date) external checkPause onlyInternal { uint64 lastdate = uint64(pd.getLastMCRDate()); uint64 failedDate = uint64(date); if (failedDate >= lastdate) { uint mcrP; uint mcrE; uint vF; (mcrP, mcrE, vF, ) = pd.getLastMCR(); uint len = pd.getAllCurrenciesLen(); pd.pushMCRData(mcrP, mcrE, vF, date); for (uint j = 0; j < len; j++) { bytes4 currName = pd.getCurrenciesByIndex(j); pd.updateCAAvgRate(currName, pd.getCAAvgRate(currName)); } emit MCREvent(date, block.number, new bytes4[](0), new uint[](0), mcrE, mcrP, vF); // Oraclize call for next MCR calculation _callOracliseForMCR(); } } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { qd = QuotationData(ms.getLatestAddress("QD")); p1 = Pool1(ms.getLatestAddress("P1")); pd = PoolData(ms.getLatestAddress("PD")); tk = NXMToken(ms.tokenAddress()); mr = MemberRoles(ms.getLatestAddress("MR")); td = TokenData(ms.getLatestAddress("TD")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Gets total sum assured(in ETH). * @return amount of sum assured */ function getAllSumAssurance() public view returns(uint amount) { uint len = pd.getAllCurrenciesLen(); for (uint i = 0; i < len; i++) { bytes4 currName = pd.getCurrenciesByIndex(i); if (currName == "ETH") { amount = amount.add(qd.getTotalSumAssured(currName)); } else { if (pd.getCAAvgRate(currName) > 0) amount = amount.add((qd.getTotalSumAssured(currName).mul(100)).div(pd.getCAAvgRate(currName))); } } } /** * @dev Calculates V(Tp) and MCR%(Tp), i.e, Pool Fund Value in Ether * and MCR% used in the Token Price Calculation. * @return vtp Pool Fund Value in Ether used for the Token Price Model * @return mcrtp MCR% used in the Token Price Model. */ function _calVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { vtp = 0; IERC20 erc20; uint currTokens = 0; uint i; for (i = 1; i < pd.getAllCurrenciesLen(); i++) { bytes4 currency = pd.getCurrenciesByIndex(i); erc20 = IERC20(pd.getCurrencyAssetAddress(currency)); currTokens = erc20.balanceOf(address(p1)); if (pd.getCAAvgRate(currency) > 0) vtp = vtp.add((currTokens.mul(100)).div(pd.getCAAvgRate(currency))); } vtp = vtp.add(poolBalance).add(p1.getInvestmentAssetBalance()); uint mcrFullperc; uint vFull; (mcrFullperc, , vFull, ) = pd.getLastMCR(); if (vFull > 0) { mcrtp = (mcrFullperc.mul(vtp)).div(vFull); } } /** * @dev Calculates the Token Price of NXM in a given currency. * @param curr Currency name. */ function calculateStepTokenPrice( bytes4 curr, uint mcrtp ) public view onlyInternal returns(uint tokenPrice) { return _calculateTokenPrice(curr, mcrtp); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param curr Currency name. */ function calculateTokenPrice (bytes4 curr) public view returns(uint tokenPrice) { uint mcrtp; (, mcrtp) = _calVtpAndMCRtp(address(p1).balance); return _calculateTokenPrice(curr, mcrtp); } function calVtpAndMCRtp() public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(address(p1).balance); } function calculateVtpAndMCRtp(uint poolBalance) public view returns(uint vtp, uint mcrtp) { return _calVtpAndMCRtp(poolBalance); } function getThresholdValues(uint vtp, uint vF, uint totalSA, uint minCap) public view returns(uint lowerThreshold, uint upperThreshold) { minCap = (minCap.mul(minCapFactor)).add(variableMincap); uint lower = 0; if (vtp >= vF) { upperThreshold = vtp.mul(120).mul(100).div((minCap)); //Max Threshold = [MAX(Vtp, Vfull) x 120] / mcrMinCap } else { upperThreshold = vF.mul(120).mul(100).div((minCap)); } if (vtp > 0) { lower = totalSA.mul(DECIMAL1E18).mul(pd.shockParameter()).div(100); if(lower < minCap.mul(11).div(10)) lower = minCap.mul(11).div(10); } if (lower > 0) { //Min Threshold = [Vtp / MAX(TotalActiveSA x ShockParameter, mcrMinCap x 1.1)] x 100 lowerThreshold = vtp.mul(100).mul(100).div(lower); } } /** * @dev Gets max numbers of tokens that can be sold at the moment. */ function getMaxSellTokens() public view returns(uint maxTokens) { uint baseMin = pd.getCurrencyAssetBaseMin("ETH"); uint maxTokensAccPoolBal; if (address(p1).balance > baseMin.mul(50).div(100)) { maxTokensAccPoolBal = address(p1).balance.sub( (baseMin.mul(50)).div(100)); } maxTokensAccPoolBal = (maxTokensAccPoolBal.mul(DECIMAL1E18)).div( (calculateTokenPrice("ETH").mul(975)).div(1000)); uint lastMCRPerc = pd.getLastMCRPerc(); if (lastMCRPerc > 10000) maxTokens = (((uint(lastMCRPerc).sub(10000)).mul(2000)).mul(DECIMAL1E18)).div(10000); if (maxTokens > maxTokensAccPoolBal) maxTokens = maxTokensAccPoolBal; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "DMCT") { val = dynamicMincapThresholdx100; } else if (code == "DMCI") { val = dynamicMincapIncrementx100; } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "DMCT") { dynamicMincapThresholdx100 = val; } else if (code == "DMCI") { dynamicMincapIncrementx100 = val; } else { revert("Invalid param code"); } } /** * @dev Calls oraclize query to calculate MCR details after 24 hours. */ function _callOracliseForMCR() internal { p1.mcrOraclise(pd.mcrTime()); } /** * @dev Calculates the Token Price of NXM in a given currency * with provided token supply for dynamic token price calculation * @param _curr Currency name. * @return tokenPrice Token price. */ function _calculateTokenPrice( bytes4 _curr, uint mcrtp ) internal view returns(uint tokenPrice) { uint getA; uint getC; uint getCAAvgRate; uint tokenExponentValue = td.tokenExponent(); // uint max = (mcrtp.mul(mcrtp).mul(mcrtp).mul(mcrtp)); uint max = mcrtp ** tokenExponentValue; uint dividingFactor = tokenExponentValue.mul(4); (getA, getC, getCAAvgRate) = pd.getTokenPriceDetails(_curr); uint mcrEth = pd.getLastMCREther(); getC = getC.mul(DECIMAL1E18); tokenPrice = (mcrEth.mul(DECIMAL1E18).mul(max).div(getC)).div(10 ** dividingFactor); tokenPrice = tokenPrice.add(getA.mul(DECIMAL1E18).div(DECIMAL1E05)); tokenPrice = tokenPrice.mul(getCAAvgRate * 10); tokenPrice = (tokenPrice).div(10**3); } /** * @dev Adds MCR Data. Checks if MCR is within valid * thresholds in order to rule out any incorrect calculations */ function _addMCRData( uint len, uint64 newMCRDate, bytes4[] memory curr, uint mcrE, uint mcrP, uint vF, uint[] memory _threeDayAvg ) internal { uint vtp = 0; uint lowerThreshold = 0; uint upperThreshold = 0; if (len > 1) { (vtp, ) = _calVtpAndMCRtp(address(p1).balance); (lowerThreshold, upperThreshold) = getThresholdValues(vtp, vF, getAllSumAssurance(), pd.minCap()); } if(mcrP > dynamicMincapThresholdx100) variableMincap = (variableMincap.mul(dynamicMincapIncrementx100.add(10000)).add(minCapFactor.mul(pd.minCap().mul(dynamicMincapIncrementx100)))).div(10000); // Explanation for above formula :- // actual formula -> variableMinCap = variableMinCap + (variableMinCap+minCap)*dynamicMincapIncrement/100 // Implemented formula is simplified form of actual formula. // Let consider above formula as b = b + (a+b)*c/100 // here, dynamicMincapIncrement is in x100 format. // so b+(a+b)*cx100/10000 can be written as => (10000.b + b.cx100 + a.cx100)/10000. // It can further simplify to (b.(10000+cx100) + a.cx100)/10000. if (len == 1 || (mcrP) >= lowerThreshold && (mcrP) <= upperThreshold) { vtp = pd.getLastMCRDate(); // due to stack to deep error,we are reusing already declared variable pd.pushMCRData(mcrP, mcrE, vF, newMCRDate); for (uint i = 0; i < curr.length; i++) { pd.updateCAAvgRate(curr[i], _threeDayAvg[i]); } emit MCREvent(newMCRDate, block.number, curr, _threeDayAvg, mcrE, mcrP, vF); // Oraclize call for next MCR calculation if (vtp < newMCRDate) { _callOracliseForMCR(); } } else { p1.mcrOracliseFail(newMCRDate, pd.mcrFailTime()); } } } // File: nexusmutual-contracts/contracts/Claims.sol /* Copyright (C) 2017 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Claims is Iupgradable { using SafeMath for uint; TokenFunctions internal tf; NXMToken internal tk; TokenController internal tc; ClaimsReward internal cr; Pool1 internal p1; ClaimsData internal cd; TokenData internal td; PoolData internal pd; Pool2 internal p2; QuotationData internal qd; MCR internal m1; uint private constant DECIMAL1E18 = uint(10) ** 18; /** * @dev Sets the status of claim using claim id. * @param claimId claim id. * @param stat status to be set. */ function setClaimStatus(uint claimId, uint stat) external onlyInternal { _setClaimStatus(claimId, stat); } /** * @dev Gets claim details of claim id = pending claim start + given index */ function getClaimFromNewStart( uint index ) external view returns ( uint coverId, uint claimId, int8 voteCA, int8 voteMV, uint statusnumber ) { (coverId, claimId, voteCA, voteMV, statusnumber) = cd.getClaimFromNewStart(index, msg.sender); // status = rewardStatus[statusnumber].claimStatusDesc; } /** * @dev Gets details of a claim submitted by the calling user, at a given index */ function getUserClaimByIndex( uint index ) external view returns( uint status, uint coverId, uint claimId ) { uint statusno; (statusno, coverId, claimId) = cd.getUserClaimByIndex(index, msg.sender); status = statusno; } /** * @dev Gets details of a given claim id. * @param _claimId Claim Id. * @return status Current status of claim id * @return finalVerdict Decision made on the claim, 1 -> acceptance, -1 -> denial * @return claimOwner Address through which claim is submitted * @return coverId Coverid associated with the claim id */ function getClaimbyIndex(uint _claimId) external view returns ( uint claimId, uint status, int8 finalVerdict, address claimOwner, uint coverId ) { uint stat; claimId = _claimId; (, coverId, finalVerdict, stat, , ) = cd.getClaim(_claimId); claimOwner = qd.getCoverMemberAddress(coverId); status = stat; } /** * @dev Calculates total amount that has been used to assess a claim. * Computaion:Adds acceptCA(tokens used for voting in favor of a claim) * denyCA(tokens used for voting against a claim) * current token price. * @param claimId Claim Id. * @param member Member type 0 -> Claim Assessors, else members. * @return tokens Total Amount used in Claims assessment. */ function getCATokens(uint claimId, uint member) external view returns(uint tokens) { uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; if (member == 0) { (, accept, deny) = cd.getClaimsTokenCA(claimId); } else { (, accept, deny) = cd.getClaimsTokenMV(claimId); } tokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); // amount (not in tokens) } /** * Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public onlyInternal { tk = NXMToken(ms.tokenAddress()); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); tc = TokenController(ms.getLatestAddress("TC")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); cr = ClaimsReward(ms.getLatestAddress("CR")); cd = ClaimsData(ms.getLatestAddress("CD")); qd = QuotationData(ms.getLatestAddress("QD")); m1 = MCR(ms.getLatestAddress("MC")); } /** * @dev Updates the pending claim start variable, * the lowest claim id with a pending decision/payout. */ function changePendingClaimStart() public onlyInternal { uint origstat; uint state12Count; uint pendingClaimStart = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = pendingClaimStart; i < actualClaimLength; i++) { (, , , origstat, , state12Count) = cd.getClaim(i); if (origstat > 5 && ((origstat != 12) || (origstat == 12 && state12Count >= 60))) cd.setpendingClaimStart(i); else break; } } /** * @dev Submits a claim for a given cover note. * Adds claim to queue incase of emergency pause else directly submits the claim. * @param coverId Cover Id. */ function submitClaim(uint coverId) public { address qadd = qd.getCoverMemberAddress(coverId); require(qadd == msg.sender); uint8 cStatus; (, cStatus, , , ) = qd.getCoverDetailsByCoverID2(coverId); require(cStatus != uint8(QuotationData.CoverStatus.ClaimSubmitted), "Claim already submitted"); require(cStatus != uint8(QuotationData.CoverStatus.CoverExpired), "Cover already expired"); if (ms.isPause() == false) { _addClaim(coverId, now, qadd); } else { cd.setClaimAtEmergencyPause(coverId, now, false); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.Requested)); } } /** * @dev Submits the Claims queued once the emergency pause is switched off. */ function submitClaimAfterEPOff() public onlyInternal { uint lengthOfClaimSubmittedAtEP = cd.getLengthOfClaimSubmittedAtEP(); uint firstClaimIndexToSubmitAfterEP = cd.getFirstClaimIndexToSubmitAfterEP(); uint coverId; uint dateUpd; bool submit; address qadd; for (uint i = firstClaimIndexToSubmitAfterEP; i < lengthOfClaimSubmittedAtEP; i++) { (coverId, dateUpd, submit) = cd.getClaimOfEmergencyPauseByIndex(i); require(submit == false); qadd = qd.getCoverMemberAddress(coverId); _addClaim(coverId, dateUpd, qadd); cd.setClaimSubmittedAtEPTrue(i, true); } cd.setFirstClaimIndexToSubmitAfterEP(lengthOfClaimSubmittedAtEP); } /** * @dev Castes vote for members who have tokens locked under Claims Assessment * @param claimId claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitCAVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); require(cd.userClaimVotePausedOn(msg.sender).add(cd.pauseDaysCA()) < now); uint tokens = tc.tokensLockedAtTime(msg.sender, "CLA", now.add(cd.claimDepositTime())); require(tokens > 0); uint stat; (, stat) = cd.getClaimStatusNumber(claimId); require(stat == 0); require(cd.getUserClaimVoteCA(msg.sender, claimId) == 0); td.bookCATokens(msg.sender); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "CAV", tokens, now, verdict); uint voteLength = cd.getAllVoteLength(); cd.addClaimVoteCA(claimId, voteLength); cd.setUserClaimVoteCA(msg.sender, claimId, voteLength); cd.setClaimTokensCA(claimId, verdict, tokens); tc.extendLockOf(msg.sender, "CLA", td.lockCADays()); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Submits a member vote for assessing a claim. * Tokens other than those locked under Claims * Assessment can be used to cast a vote for a given claim id. * @param claimId Selected claim id. * @param verdict 1 for Accept,-1 for Deny. */ function submitMemberVote(uint claimId, int8 verdict) public isMemberAndcheckPause { require(checkVoteClosing(claimId) != 1); uint stat; uint tokens = tc.totalBalanceOf(msg.sender); (, stat) = cd.getClaimStatusNumber(claimId); require(stat >= 1 && stat <= 5); require(cd.getUserClaimVoteMember(msg.sender, claimId) == 0); cd.addVote(msg.sender, tokens, claimId, verdict); cd.callVoteEvent(msg.sender, claimId, "MV", tokens, now, verdict); tc.lockForMemberVote(msg.sender, td.lockMVDays()); uint voteLength = cd.getAllVoteLength(); cd.addClaimVotemember(claimId, voteLength); cd.setUserClaimVoteMember(msg.sender, claimId, voteLength); cd.setClaimTokensMV(claimId, verdict, tokens); int close = checkVoteClosing(claimId); if (close == 1) { cr.changeClaimStatus(claimId); } } /** * @dev Pause Voting of All Pending Claims when Emergency Pause Start. */ function pauseAllPendingClaimsVoting() public onlyInternal { uint firstIndex = cd.pendingClaimStart(); uint actualClaimLength = cd.actualClaimLength(); for (uint i = firstIndex; i < actualClaimLength; i++) { if (checkVoteClosing(i) == 0) { uint dateUpd = cd.getClaimDateUpd(i); cd.setPendingClaimDetails(i, (dateUpd.add(cd.maxVotingTime())).sub(now), false); } } } /** * @dev Resume the voting phase of all Claims paused due to an emergency pause. */ function startAllPendingClaimsVoting() public onlyInternal { uint firstIndx = cd.getFirstClaimIndexToStartVotingAfterEP(); uint i; uint lengthOfClaimVotingPause = cd.getLengthOfClaimVotingPause(); for (i = firstIndx; i < lengthOfClaimVotingPause; i++) { uint pendingTime; uint claimID; (claimID, pendingTime, ) = cd.getPendingClaimDetailsByIndex(i); uint pTime = (now.sub(cd.maxVotingTime())).add(pendingTime); cd.setClaimdateUpd(claimID, pTime); cd.setPendingClaimVoteStatus(i, true); uint coverid; (, coverid) = cd.getClaimCoverId(claimID); address qadd = qd.getCoverMemberAddress(coverid); tf.extendCNEPOff(qadd, coverid, pendingTime.add(cd.claimDepositTime())); p1.closeClaimsOraclise(claimID, uint64(pTime)); } cd.setFirstClaimIndexToStartVotingAfterEP(i); } /** * @dev Checks if voting of a claim should be closed or not. * @param claimId Claim Id. * @return close 1 -> voting should be closed, 0 -> if voting should not be closed, * -1 -> voting has already been closed. */ function checkVoteClosing(uint claimId) public view returns(int8 close) { close = 0; uint status; (, status) = cd.getClaimStatusNumber(claimId); uint dateUpd = cd.getClaimDateUpd(claimId); if (status == 12 && dateUpd.add(cd.payoutRetryTime()) < now) { if (cd.getClaimState12Count(claimId) < 60) close = 1; } if (status > 5 && status != 12) { close = -1; } else if (status != 12 && dateUpd.add(cd.maxVotingTime()) <= now) { close = 1; } else if (status != 12 && dateUpd.add(cd.minVotingTime()) >= now) { close = 0; } else if (status == 0 || (status >= 1 && status <= 5)) { close = _checkVoteClosingFinal(claimId, status); } } /** * @dev Checks if voting of a claim should be closed or not. * Internally called by checkVoteClosing method * for Claims whose status number is 0 or status number lie between 2 and 6. * @param claimId Claim Id. * @param status Current status of claim. * @return close 1 if voting should be closed,0 in case voting should not be closed, * -1 if voting has already been closed. */ function _checkVoteClosingFinal(uint claimId, uint status) internal view returns(int8 close) { close = 0; uint coverId; (, coverId) = cd.getClaimCoverId(claimId); bytes4 curr = qd.getCurrencyOfCover(coverId); uint tokenx1e18 = m1.calculateTokenPrice(curr); uint accept; uint deny; (, accept, deny) = cd.getClaimsTokenCA(claimId); uint caTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); (, accept, deny) = cd.getClaimsTokenMV(claimId); uint mvTokens = ((accept.add(deny)).mul(tokenx1e18)).div(DECIMAL1E18); uint sumassured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); if (status == 0 && caTokens >= sumassured.mul(10)) { close = 1; } else if (status >= 1 && status <= 5 && mvTokens >= sumassured.mul(10)) { close = 1; } } /** * @dev Changes the status of an existing claim id, based on current * status and current conditions of the system * @param claimId Claim Id. * @param stat status number. */ function _setClaimStatus(uint claimId, uint stat) internal { uint origstat; uint state12Count; uint dateUpd; uint coverId; (, coverId, , origstat, dateUpd, state12Count) = cd.getClaim(claimId); (, origstat) = cd.getClaimStatusNumber(claimId); if (stat == 12 && origstat == 12) { cd.updateState12Count(claimId, 1); } cd.setClaimStatus(claimId, stat); if (state12Count >= 60 && stat == 12) { cd.setClaimStatus(claimId, 13); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimDenied)); } uint time = now; cd.setClaimdateUpd(claimId, time); if (stat >= 2 && stat <= 5) { p1.closeClaimsOraclise(claimId, cd.maxVotingTime()); } if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) <= now) && (state12Count < 60)) { p1.closeClaimsOraclise(claimId, cd.payoutRetryTime()); } else if (stat == 12 && (dateUpd.add(cd.payoutRetryTime()) > now) && (state12Count < 60)) { uint64 timeLeft = uint64((dateUpd.add(cd.payoutRetryTime())).sub(now)); p1.closeClaimsOraclise(claimId, timeLeft); } } /** * @dev Submits a claim for a given cover note. * Set deposits flag against cover. */ function _addClaim(uint coverId, uint time, address add) internal { tf.depositCN(coverId); uint len = cd.actualClaimLength(); cd.addClaim(len, coverId, add, now); cd.callClaimEvent(coverId, add, len, time); qd.changeCoverStatusNo(coverId, uint8(QuotationData.CoverStatus.ClaimSubmitted)); bytes4 curr = qd.getCurrencyOfCover(coverId); uint sumAssured = qd.getCoverSumAssured(coverId).mul(DECIMAL1E18); pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).add(sumAssured)); p2.internalLiquiditySwap(curr); p1.closeClaimsOraclise(len, cd.maxVotingTime()); } } // File: nexusmutual-contracts/contracts/ClaimsReward.sol /* Copyright (C) 2020 NexusMutual.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ //Claims Reward Contract contains the functions for calculating number of tokens // that will get rewarded, unlocked or burned depending upon the status of claim. pragma solidity 0.5.7; contract ClaimsReward is Iupgradable { using SafeMath for uint; NXMToken internal tk; TokenController internal tc; TokenFunctions internal tf; TokenData internal td; QuotationData internal qd; Claims internal c1; ClaimsData internal cd; Pool1 internal p1; Pool2 internal p2; PoolData internal pd; Governance internal gv; IPooledStaking internal pooledStaking; uint private constant DECIMAL1E18 = uint(10) ** 18; function changeDependentContractAddress() public onlyInternal { c1 = Claims(ms.getLatestAddress("CL")); cd = ClaimsData(ms.getLatestAddress("CD")); tk = NXMToken(ms.tokenAddress()); tc = TokenController(ms.getLatestAddress("TC")); td = TokenData(ms.getLatestAddress("TD")); tf = TokenFunctions(ms.getLatestAddress("TF")); p1 = Pool1(ms.getLatestAddress("P1")); p2 = Pool2(ms.getLatestAddress("P2")); pd = PoolData(ms.getLatestAddress("PD")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); pooledStaking = IPooledStaking(ms.getLatestAddress("PS")); } /// @dev Decides the next course of action for a given claim. function changeClaimStatus(uint claimid) public checkPause onlyInternal { uint coverid; (, coverid) = cd.getClaimCoverId(claimid); uint status; (, status) = cd.getClaimStatusNumber(claimid); // when current status is "Pending-Claim Assessor Vote" if (status == 0) { _changeClaimStatusCA(claimid, coverid, status); } else if (status >= 1 && status <= 5) { _changeClaimStatusMV(claimid, coverid, status); } else if (status == 12) { // when current status is "Claim Accepted Payout Pending" uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); address payable coverHolder = qd.getCoverMemberAddress(coverid); bytes4 coverCurrency = qd.getCurrencyOfCover(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, coverHolder, coverCurrency); if (success) { tf.burnStakedTokens(coverid, coverCurrency, sumAssured); c1.setClaimStatus(claimid, 14); } } c1.changePendingClaimStart(); } /// @dev Amount of tokens to be rewarded to a user for a particular vote id. /// @param check 1 -> CA vote, else member vote /// @param voteid vote id for which reward has to be Calculated /// @param flag if 1 calculate even if claimed,else don't calculate if already claimed /// @return tokenCalculated reward to be given for vote id /// @return lastClaimedCheck true if final verdict is still pending for that voteid /// @return tokens number of tokens locked under that voteid /// @return perc percentage of reward to be given. function getRewardToBeGiven( uint check, uint voteid, uint flag ) public view returns ( uint tokenCalculated, bool lastClaimedCheck, uint tokens, uint perc ) { uint claimId; int8 verdict; bool claimed; uint tokensToBeDist; uint totalTokens; (tokens, claimId, verdict, claimed) = cd.getVoteDetails(voteid); lastClaimedCheck = false; int8 claimVerdict = cd.getFinalVerdict(claimId); if (claimVerdict == 0) { lastClaimedCheck = true; } if (claimVerdict == verdict && (claimed == false || flag == 1)) { if (check == 1) { (perc, , tokensToBeDist) = cd.getClaimRewardDetail(claimId); } else { (, perc, tokensToBeDist) = cd.getClaimRewardDetail(claimId); } if (perc > 0) { if (check == 1) { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenCA(claimId); } else { (, , totalTokens) = cd.getClaimsTokenCA(claimId); } } else { if (verdict == 1) { (, totalTokens, ) = cd.getClaimsTokenMV(claimId); }else { (, , totalTokens) = cd.getClaimsTokenMV(claimId); } } tokenCalculated = (perc.mul(tokens).mul(tokensToBeDist)).div(totalTokens.mul(100)); } } } /// @dev Transfers all tokens held by contract to a new contract in case of upgrade. function upgrade(address _newAdd) public onlyInternal { uint amount = tk.balanceOf(address(this)); if (amount > 0) { require(tk.transfer(_newAdd, amount)); } } /// @dev Total reward in token due for claim by a user. /// @return total total number of tokens function getRewardToBeDistributedByUser(address _add) public view returns(uint total) { uint lengthVote = cd.getVoteAddressCALength(_add); uint lastIndexCA; uint lastIndexMV; uint tokenForVoteId; uint voteId; (lastIndexCA, lastIndexMV) = cd.getRewardDistributedIndex(_add); for (uint i = lastIndexCA; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(_add, i); (tokenForVoteId, , , ) = getRewardToBeGiven(1, voteId, 0); total = total.add(tokenForVoteId); } lengthVote = cd.getVoteAddressMemberLength(_add); for (uint j = lastIndexMV; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(_add, j); (tokenForVoteId, , , ) = getRewardToBeGiven(0, voteId, 0); total = total.add(tokenForVoteId); } return (total); } /// @dev Gets reward amount and claiming status for a given claim id. /// @return reward amount of tokens to user. /// @return claimed true if already claimed false if yet to be claimed. function getRewardAndClaimedStatus(uint check, uint claimId) public view returns(uint reward, bool claimed) { uint voteId; uint claimid; uint lengthVote; if (check == 1) { lengthVote = cd.getVoteAddressCALength(msg.sender); for (uint i = 0; i < lengthVote; i++) { voteId = cd.getVoteAddressCA(msg.sender, i); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } else { lengthVote = cd.getVoteAddressMemberLength(msg.sender); for (uint j = 0; j < lengthVote; j++) { voteId = cd.getVoteAddressMember(msg.sender, j); (, claimid, , claimed) = cd.getVoteDetails(voteId); if (claimid == claimId) { break; } } } (reward, , , ) = getRewardToBeGiven(check, voteId, 1); } /** * @dev Function used to claim all pending rewards : Claims Assessment + Risk Assessment + Governance * Claim assesment, Risk assesment, Governance rewards */ function claimAllPendingReward(uint records) public isMemberAndcheckPause { _claimRewardToBeDistributed(records); pooledStaking.withdrawReward(msg.sender); uint governanceRewards = gv.claimReward(msg.sender, records); if (governanceRewards > 0) { require(tk.transfer(msg.sender, governanceRewards)); } } /** * @dev Function used to get pending rewards of a particular user address. * @param _add user address. * @return total reward amount of the user */ function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); } /// @dev Rewards/Punishes users who participated in Claims assessment. // Unlocking and burning of the tokens will also depend upon the status of claim. /// @param claimid Claim Id. function _rewardAgainstClaim(uint claimid, uint coverid, uint sumAssured, uint status) internal { uint premiumNXM = qd.getCoverPremiumNXM(coverid); bytes4 curr = qd.getCurrencyOfCover(coverid); uint distributableTokens = premiumNXM.mul(cd.claimRewardPerc()).div(100);// 20% of premium uint percCA; uint percMV; (percCA, percMV) = cd.getRewardStatus(status); cd.setClaimRewardDetail(claimid, percCA, percMV, distributableTokens); if (percCA > 0 || percMV > 0) { tc.mint(address(this), distributableTokens); } if (status == 6 || status == 9 || status == 11) { cd.changeFinalVerdict(claimid, -1); td.setDepositCN(coverid, false); // Unset flag tf.burnDepositCN(coverid); // burn Deposited CN pd.changeCurrencyAssetVarMin(curr, pd.getCurrencyAssetVarMin(curr).sub(sumAssured)); p2.internalLiquiditySwap(curr); } else if (status == 7 || status == 8 || status == 10) { cd.changeFinalVerdict(claimid, 1); td.setDepositCN(coverid, false); // Unset flag tf.unlockCN(coverid); bool success = p1.sendClaimPayout(coverid, claimid, sumAssured, qd.getCoverMemberAddress(coverid), curr); if (success) { tf.burnStakedTokens(coverid, curr, sumAssured); } } } /// @dev Computes the result of Claim Assessors Voting for a given claim id. function _changeClaimStatusCA(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint caTokens = c1.getCATokens(claimid, 0); // converted in cover currency. uint accept; uint deny; uint acceptAndDeny; bool rewardOrPunish; uint sumAssured; (, accept) = cd.getClaimVote(claimid, 1); (, deny) = cd.getClaimVote(claimid, -1); acceptAndDeny = accept.add(deny); accept = accept.mul(100); deny = deny.mul(100); if (caTokens == 0) { status = 3; } else { sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); // Min threshold reached tokens used for voting > 5* sum assured if (caTokens > sumAssured.mul(5)) { if (accept.div(acceptAndDeny) > 70) { status = 7; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimAccepted)); rewardOrPunish = true; } else if (deny.div(acceptAndDeny) > 70) { status = 6; qd.changeCoverStatusNo(coverid, uint8(QuotationData.CoverStatus.ClaimDenied)); rewardOrPunish = true; } else if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 4; } else { status = 5; } } else { if (accept.div(acceptAndDeny) > deny.div(acceptAndDeny)) { status = 2; } else { status = 3; } } } c1.setClaimStatus(claimid, status); if (rewardOrPunish) { _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } } /// @dev Computes the result of Member Voting for a given claim id. function _changeClaimStatusMV(uint claimid, uint coverid, uint status) internal { // Check if voting should be closed or not if (c1.checkVoteClosing(claimid) == 1) { uint8 coverStatus; uint statusOrig = status; uint mvTokens = c1.getCATokens(claimid, 1); // converted in cover currency. // If tokens used for acceptance >50%, claim is accepted uint sumAssured = qd.getCoverSumAssured(coverid).mul(DECIMAL1E18); uint thresholdUnreached = 0; // Minimum threshold for member voting is reached only when // value of tokens used for voting > 5* sum assured of claim id if (mvTokens < sumAssured.mul(5)) { thresholdUnreached = 1; } uint accept; (, accept) = cd.getClaimMVote(claimid, 1); uint deny; (, deny) = cd.getClaimMVote(claimid, -1); if (accept.add(deny) > 0) { if (accept.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 8; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (deny.mul(100).div(accept.add(deny)) >= 50 && statusOrig > 1 && statusOrig <= 5 && thresholdUnreached == 0) { status = 9; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } } if (thresholdUnreached == 1 && (statusOrig == 2 || statusOrig == 4)) { status = 10; coverStatus = uint8(QuotationData.CoverStatus.ClaimAccepted); } else if (thresholdUnreached == 1 && (statusOrig == 5 || statusOrig == 3 || statusOrig == 1)) { status = 11; coverStatus = uint8(QuotationData.CoverStatus.ClaimDenied); } c1.setClaimStatus(claimid, status); qd.changeCoverStatusNo(coverid, uint8(coverStatus)); // Reward/Punish Claim Assessors and Members who participated in Claims assessment _rewardAgainstClaim(claimid, coverid, sumAssured, status); } } /// @dev Allows a user to claim all pending Claims assessment rewards. function _claimRewardToBeDistributed(uint _records) internal { uint lengthVote = cd.getVoteAddressCALength(msg.sender); uint voteid; uint lastIndex; (lastIndex, ) = cd.getRewardDistributedIndex(msg.sender); uint total = 0; uint tokenForVoteId = 0; bool lastClaimedCheck; uint _days = td.lockCADays(); bool claimed; uint counter = 0; uint claimId; uint perc; uint i; uint lastClaimed = lengthVote; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressCA(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , perc) = getRewardToBeGiven(1, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (perc > 0 && !claimed) { counter++; cd.setRewardClaimed(voteid, true); } else if (perc == 0 && cd.getFinalVerdict(claimId) != 0 && !claimed) { (perc, , ) = cd.getClaimRewardDetail(claimId); if (perc == 0) { counter++; } cd.setRewardClaimed(voteid, true); } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexCA(msg.sender, i); } else { cd.setRewardDistributedIndexCA(msg.sender, lastClaimed); } lengthVote = cd.getVoteAddressMemberLength(msg.sender); lastClaimed = lengthVote; _days = _days.mul(counter); if (tc.tokensLockedAtTime(msg.sender, "CLA", now) > 0) { tc.reduceLock(msg.sender, "CLA", _days); } (, lastIndex) = cd.getRewardDistributedIndex(msg.sender); lastClaimed = lengthVote; counter = 0; for (i = lastIndex; i < lengthVote && counter < _records; i++) { voteid = cd.getVoteAddressMember(msg.sender, i); (tokenForVoteId, lastClaimedCheck, , ) = getRewardToBeGiven(0, voteid, 0); if (lastClaimed == lengthVote && lastClaimedCheck == true) { lastClaimed = i; } (, claimId, , claimed) = cd.getVoteDetails(voteid); if (claimed == false && cd.getFinalVerdict(claimId) != 0) { cd.setRewardClaimed(voteid, true); counter++; } if (tokenForVoteId > 0) { total = tokenForVoteId.add(total); } } if (total > 0) { require(tk.transfer(msg.sender, total)); } if (lastClaimed == lengthVote) { cd.setRewardDistributedIndexMV(msg.sender, i); } else { cd.setRewardDistributedIndexMV(msg.sender, lastClaimed); } } /** * @dev Function used to claim the commission earned by the staker. */ function _claimStakeCommission(uint _records, address _user) external onlyInternal { uint total=0; uint len = td.getStakerStakedContractLength(_user); uint lastCompletedStakeCommission = td.lastCompletedStakeCommission(_user); uint commissionEarned; uint commissionRedeemed; uint maxCommission; uint lastCommisionRedeemed = len; uint counter; uint i; for (i = lastCompletedStakeCommission; i < len && counter < _records; i++) { commissionRedeemed = td.getStakerRedeemedStakeCommission(_user, i); commissionEarned = td.getStakerEarnedStakeCommission(_user, i); maxCommission = td.getStakerInitialStakedAmountOnContract( _user, i).mul(td.stakerMaxCommissionPer()).div(100); if (lastCommisionRedeemed == len && maxCommission != commissionEarned) lastCommisionRedeemed = i; td.pushRedeemedStakeCommissions(_user, i, commissionEarned.sub(commissionRedeemed)); total = total.add(commissionEarned.sub(commissionRedeemed)); counter++; } if (lastCommisionRedeemed == len) { td.setLastCompletedStakeCommissionIndex(_user, i); } else { td.setLastCompletedStakeCommissionIndex(_user, lastCommisionRedeemed); } if (total > 0) require(tk.transfer(_user, total)); //solhint-disable-line } } // File: nexusmutual-contracts/contracts/MemberRoles.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract MemberRoles is IMemberRoles, Governed, Iupgradable { TokenController public dAppToken; TokenData internal td; QuotationData internal qd; ClaimsReward internal cr; Governance internal gv; TokenFunctions internal tf; NXMToken public tk; struct MemberRoleDetails { uint memberCounter; mapping(address => bool) memberActive; address[] memberAddress; address authorized; } enum Role {UnAssigned, AdvisoryBoard, Member, Owner} event switchedMembership(address indexed previousMember, address indexed newMember, uint timeStamp); MemberRoleDetails[] internal memberRoleData; bool internal constructorCheck; uint public maxABCount; bool public launched; uint public launchedOn; modifier checkRoleAuthority(uint _memberRoleId) { if (memberRoleData[_memberRoleId].authorized != address(0)) require(msg.sender == memberRoleData[_memberRoleId].authorized); else require(isAuthorizedToGovern(msg.sender), "Not Authorized"); _; } /** * @dev to swap advisory board member * @param _newABAddress is address of new AB member * @param _removeAB is advisory board member to be removed */ function swapABMember ( address _newABAddress, address _removeAB ) external checkRoleAuthority(uint(Role.AdvisoryBoard)) { _updateRole(_newABAddress, uint(Role.AdvisoryBoard), true); _updateRole(_removeAB, uint(Role.AdvisoryBoard), false); } /** * @dev to swap the owner address * @param _newOwnerAddress is the new owner address */ function swapOwner ( address _newOwnerAddress ) external { require(msg.sender == address(ms)); _updateRole(ms.owner(), uint(Role.Owner), false); _updateRole(_newOwnerAddress, uint(Role.Owner), true); } /** * @dev is used to add initital advisory board members * @param abArray is the list of initial advisory board members */ function addInitialABMembers(address[] calldata abArray) external onlyOwner { //Ensure that NXMaster has initialized. require(ms.masterInitialized()); require(maxABCount >= SafeMath.add(numberOfMembers(uint(Role.AdvisoryBoard)), abArray.length) ); //AB count can't exceed maxABCount for (uint i = 0; i < abArray.length; i++) { require(checkRole(abArray[i], uint(MemberRoles.Role.Member))); _updateRole(abArray[i], uint(Role.AdvisoryBoard), true); } } /** * @dev to change max number of AB members allowed * @param _val is the new value to be set */ function changeMaxABCount(uint _val) external onlyInternal { maxABCount = _val; } /** * @dev Iupgradable Interface to update dependent contract address */ function changeDependentContractAddress() public { td = TokenData(ms.getLatestAddress("TD")); cr = ClaimsReward(ms.getLatestAddress("CR")); qd = QuotationData(ms.getLatestAddress("QD")); gv = Governance(ms.getLatestAddress("GV")); tf = TokenFunctions(ms.getLatestAddress("TF")); tk = NXMToken(ms.tokenAddress()); dAppToken = TokenController(ms.getLatestAddress("TC")); } /** * @dev to change the master address * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev to initiate the member roles * @param _firstAB is the address of the first AB member * @param memberAuthority is the authority (role) of the member */ function memberRolesInitiate (address _firstAB, address memberAuthority) public { require(!constructorCheck); _addInitialMemberRoles(_firstAB, memberAuthority); constructorCheck = true; } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function addRole( //solhint-disable-line bytes32 _roleName, string memory _roleDescription, address _authorized ) public onlyAuthorizedToGovern { _addRole(_roleName, _roleDescription, _authorized); } /// @dev Assign or Delete a member from specific role. /// @param _memberAddress Address of Member /// @param _roleId RoleId to update /// @param _active active is set to be True if we want to assign this role to member, False otherwise! function updateRole( //solhint-disable-line address _memberAddress, uint _roleId, bool _active ) public checkRoleAuthority(_roleId) { _updateRole(_memberAddress, _roleId, _active); } /** * @dev to add members before launch * @param userArray is list of addresses of members * @param tokens is list of tokens minted for each array element */ function addMembersBeforeLaunch(address[] memory userArray, uint[] memory tokens) public onlyOwner { require(!launched); for (uint i=0; i < userArray.length; i++) { require(!ms.isMember(userArray[i])); dAppToken.addToWhitelist(userArray[i]); _updateRole(userArray[i], uint(Role.Member), true); dAppToken.mint(userArray[i], tokens[i]); } launched = true; launchedOn = now; } /** * @dev Called by user to pay joining membership fee */ function payJoiningFee(address _userAddress) public payable { require(_userAddress != address(0)); require(!ms.isPause(), "Emergency Pause Applied"); if (msg.sender == address(ms.getLatestAddress("QT"))) { require(td.walletAddress() != address(0), "No walletAddress present"); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(msg.value); } else { require(!qd.refundEligible(_userAddress)); require(!ms.isMember(_userAddress)); require(msg.value == td.joiningFee()); qd.setRefundEligible(_userAddress, true); } } /** * @dev to perform kyc verdict * @param _userAddress whose kyc is being performed * @param verdict of kyc process */ function kycVerdict(address payable _userAddress, bool verdict) public { require(msg.sender == qd.kycAuthAddress()); require(!ms.isPause()); require(_userAddress != address(0)); require(!ms.isMember(_userAddress)); require(qd.refundEligible(_userAddress)); if (verdict) { qd.setRefundEligible(_userAddress, false); uint fee = td.joiningFee(); dAppToken.addToWhitelist(_userAddress); _updateRole(_userAddress, uint(Role.Member), true); td.walletAddress().transfer(fee); //solhint-disable-line } else { qd.setRefundEligible(_userAddress, false); _userAddress.transfer(td.joiningFee()); //solhint-disable-line } } /** * @dev Called by existed member if wish to Withdraw membership. */ function withdrawMembership() public { require(!ms.isPause() && ms.isMember(msg.sender)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.burnFrom(msg.sender, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); // need clarification on whitelist } /** * @dev Called by existed member if wish to switch membership to other address. * @param _add address of user to forward membership. */ function switchMembership(address _add) external { require(!ms.isPause() && ms.isMember(msg.sender) && !ms.isMember(_add)); require(dAppToken.totalLockedBalance(msg.sender, now) == 0); //solhint-disable-line require(!tf.isLockedForMemberVote(msg.sender)); // No locked tokens for Member/Governance voting require(cr.getAllPendingRewardOfUser(msg.sender) == 0); // No pending reward to be claimed(claim assesment). require(dAppToken.tokensUnlockable(msg.sender, "CLA") == 0, "Member should have no CLA unlockable tokens"); gv.removeDelegation(msg.sender); dAppToken.addToWhitelist(_add); _updateRole(_add, uint(Role.Member), true); tk.transferFrom(msg.sender, _add, tk.balanceOf(msg.sender)); _updateRole(msg.sender, uint(Role.Member), false); dAppToken.removeFromWhitelist(msg.sender); emit switchedMembership(msg.sender, _add, now); } /// @dev Return number of member roles function totalRoles() public view returns(uint256) { //solhint-disable-line return memberRoleData.length; } /// @dev Change Member Address who holds the authority to Add/Delete any member from specific role. /// @param _roleId roleId to update its Authorized Address /// @param _newAuthorized New authorized address against role id function changeAuthorized(uint _roleId, address _newAuthorized) public checkRoleAuthority(_roleId) { //solhint-disable-line memberRoleData[_roleId].authorized = _newAuthorized; } /// @dev Gets the member addresses assigned by a specific role /// @param _memberRoleId Member role id /// @return roleId Role id /// @return allMemberAddress Member addresses of specified role id function members(uint _memberRoleId) public view returns(uint, address[] memory memberArray) { //solhint-disable-line uint length = memberRoleData[_memberRoleId].memberAddress.length; uint i; uint j = 0; memberArray = new address[](memberRoleData[_memberRoleId].memberCounter); for (i = 0; i < length; i++) { address member = memberRoleData[_memberRoleId].memberAddress[i]; if (memberRoleData[_memberRoleId].memberActive[member] && !_checkMemberInArray(member, memberArray)) { //solhint-disable-line memberArray[j] = member; j++; } } return (_memberRoleId, memberArray); } /// @dev Gets all members' length /// @param _memberRoleId Member role id /// @return memberRoleData[_memberRoleId].memberCounter Member length function numberOfMembers(uint _memberRoleId) public view returns(uint) { //solhint-disable-line return memberRoleData[_memberRoleId].memberCounter; } /// @dev Return member address who holds the right to add/remove any member from specific role. function authorized(uint _memberRoleId) public view returns(address) { //solhint-disable-line return memberRoleData[_memberRoleId].authorized; } /// @dev Get All role ids array that has been assigned to a member so far. function roles(address _memberAddress) public view returns(uint[] memory) { //solhint-disable-line uint length = memberRoleData.length; uint[] memory assignedRoles = new uint[](length); uint counter = 0; for (uint i = 1; i < length; i++) { if (memberRoleData[i].memberActive[_memberAddress]) { assignedRoles[counter] = i; counter++; } } return assignedRoles; } /// @dev Returns true if the given role id is assigned to a member. /// @param _memberAddress Address of member /// @param _roleId Checks member's authenticity with the roleId. /// i.e. Returns true if this roleId is assigned to member function checkRole(address _memberAddress, uint _roleId) public view returns(bool) { //solhint-disable-line if (_roleId == uint(Role.UnAssigned)) return true; else if (memberRoleData[_roleId].memberActive[_memberAddress]) //solhint-disable-line return true; else return false; } /// @dev Return total number of members assigned against each role id. /// @return totalMembers Total members in particular role id function getMemberLengthForAllRoles() public view returns(uint[] memory totalMembers) { //solhint-disable-line totalMembers = new uint[](memberRoleData.length); for (uint i = 0; i < memberRoleData.length; i++) { totalMembers[i] = numberOfMembers(i); } } /** * @dev to update the member roles * @param _memberAddress in concern * @param _roleId the id of role * @param _active if active is true, add the member, else remove it */ function _updateRole(address _memberAddress, uint _roleId, bool _active) internal { // require(_roleId != uint(Role.TokenHolder), "Membership to Token holder is detected automatically"); if (_active) { require(!memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.add(memberRoleData[_roleId].memberCounter, 1); memberRoleData[_roleId].memberActive[_memberAddress] = true; memberRoleData[_roleId].memberAddress.push(_memberAddress); } else { require(memberRoleData[_roleId].memberActive[_memberAddress]); memberRoleData[_roleId].memberCounter = SafeMath.sub(memberRoleData[_roleId].memberCounter, 1); delete memberRoleData[_roleId].memberActive[_memberAddress]; } } /// @dev Adds new member role /// @param _roleName New role name /// @param _roleDescription New description hash /// @param _authorized Authorized member against every role id function _addRole( bytes32 _roleName, string memory _roleDescription, address _authorized ) internal { emit MemberRole(memberRoleData.length, _roleName, _roleDescription); memberRoleData.push(MemberRoleDetails(0, new address[](0), _authorized)); } /** * @dev to check if member is in the given member array * @param _memberAddress in concern * @param memberArray in concern * @return boolean to represent the presence */ function _checkMemberInArray( address _memberAddress, address[] memory memberArray ) internal pure returns(bool memberExists) { uint i; for (i = 0; i < memberArray.length; i++) { if (memberArray[i] == _memberAddress) { memberExists = true; break; } } } /** * @dev to add initial member roles * @param _firstAB is the member address to be added * @param memberAuthority is the member authority(role) to be added for */ function _addInitialMemberRoles(address _firstAB, address memberAuthority) internal { maxABCount = 5; _addRole("Unassigned", "Unassigned", address(0)); _addRole( "Advisory Board", "Selected few members that are deeply entrusted by the dApp. An ideal advisory board should be a mix of skills of domain, governance, research, technology, consulting etc to improve the performance of the dApp.", //solhint-disable-line address(0) ); _addRole( "Member", "Represents all users of Mutual.", //solhint-disable-line memberAuthority ); _addRole( "Owner", "Represents Owner of Mutual.", //solhint-disable-line address(0) ); // _updateRole(_firstAB, uint(Role.AdvisoryBoard), true); _updateRole(_firstAB, uint(Role.Owner), true); // _updateRole(_firstAB, uint(Role.Member), true); launchedOn = 0; } function memberAtIndex(uint _memberRoleId, uint index) external view returns (address, bool) { address memberAddress = memberRoleData[_memberRoleId].memberAddress[index]; return (memberAddress, memberRoleData[_memberRoleId].memberActive[memberAddress]); } function membersLength(uint _memberRoleId) external view returns (uint) { return memberRoleData[_memberRoleId].memberAddress.length; } } // File: nexusmutual-contracts/contracts/ProposalCategory.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract ProposalCategory is Governed, IProposalCategory, Iupgradable { bool public constructorCheck; MemberRoles internal mr; struct CategoryStruct { uint memberRoleToVote; uint majorityVotePerc; uint quorumPerc; uint[] allowedToCreateProposal; uint closingTime; uint minStake; } struct CategoryAction { uint defaultIncentive; address contractAddress; bytes2 contractName; } CategoryStruct[] internal allCategory; mapping (uint => CategoryAction) internal categoryActionData; mapping (uint => uint) public categoryABReq; mapping (uint => uint) public isSpecialResolution; mapping (uint => bytes) public categoryActionHashes; bool public categoryActionHashUpdated; /** * @dev Restricts calls to deprecated functions */ modifier deprecated() { revert("Function deprecated"); _; } /** * @dev Adds new category (Discontinued, moved functionality to newCategory) * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function addCategory( string calldata _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] calldata _allowedToCreateProposal, uint _closingTime, string calldata _actionHash, address _contractAddress, bytes2 _contractName, uint[] calldata _incentives ) external deprecated { } /** * @dev Initiates Default settings for Proposal Category contract (Adding default categories) */ function proposalCategoryInitiate() external deprecated { //solhint-disable-line } /** * @dev Initiates Default action function hashes for existing categories * To be called after the contract has been upgraded by governance */ function updateCategoryActionHashes() external onlyOwner { require(!categoryActionHashUpdated, "Category action hashes already updated"); categoryActionHashUpdated = true; categoryActionHashes[1] = abi.encodeWithSignature("addRole(bytes32,string,address)"); categoryActionHashes[2] = abi.encodeWithSignature("updateRole(address,uint256,bool)"); categoryActionHashes[3] = abi.encodeWithSignature("newCategory(string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[4] = abi.encodeWithSignature("editCategory(uint256,string,uint256,uint256,uint256,uint256[],uint256,string,address,bytes2,uint256[],string)");//solhint-disable-line categoryActionHashes[5] = abi.encodeWithSignature("upgradeContractImplementation(bytes2,address)"); categoryActionHashes[6] = abi.encodeWithSignature("startEmergencyPause()"); categoryActionHashes[7] = abi.encodeWithSignature("addEmergencyPause(bool,bytes4)"); categoryActionHashes[8] = abi.encodeWithSignature("burnCAToken(uint256,uint256,address)"); categoryActionHashes[9] = abi.encodeWithSignature("setUserClaimVotePausedOn(address)"); categoryActionHashes[12] = abi.encodeWithSignature("transferEther(uint256,address)"); categoryActionHashes[13] = abi.encodeWithSignature("addInvestmentAssetCurrency(bytes4,address,bool,uint64,uint64,uint8)");//solhint-disable-line categoryActionHashes[14] = abi.encodeWithSignature("changeInvestmentAssetHoldingPerc(bytes4,uint64,uint64)"); categoryActionHashes[15] = abi.encodeWithSignature("changeInvestmentAssetStatus(bytes4,bool)"); categoryActionHashes[16] = abi.encodeWithSignature("swapABMember(address,address)"); categoryActionHashes[17] = abi.encodeWithSignature("addCurrencyAssetCurrency(bytes4,address,uint256)"); categoryActionHashes[20] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[21] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[22] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[23] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[24] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[25] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[26] = abi.encodeWithSignature("updateUintParameters(bytes8,uint256)"); categoryActionHashes[27] = abi.encodeWithSignature("updateAddressParameters(bytes8,address)"); categoryActionHashes[28] = abi.encodeWithSignature("updateOwnerParameters(bytes8,address)"); categoryActionHashes[29] = abi.encodeWithSignature("upgradeContract(bytes2,address)"); categoryActionHashes[30] = abi.encodeWithSignature("changeCurrencyAssetAddress(bytes4,address)"); categoryActionHashes[31] = abi.encodeWithSignature("changeCurrencyAssetBaseMin(bytes4,uint256)"); categoryActionHashes[32] = abi.encodeWithSignature("changeInvestmentAssetAddressAndDecimal(bytes4,address,uint8)");//solhint-disable-line categoryActionHashes[33] = abi.encodeWithSignature("externalLiquidityTrade()"); } /** * @dev Gets Total number of categories added till now */ function totalCategories() external view returns(uint) { return allCategory.length; } /** * @dev Gets category details */ function category(uint _categoryId) external view returns(uint, uint, uint, uint, uint[] memory, uint, uint) { return( _categoryId, allCategory[_categoryId].memberRoleToVote, allCategory[_categoryId].majorityVotePerc, allCategory[_categoryId].quorumPerc, allCategory[_categoryId].allowedToCreateProposal, allCategory[_categoryId].closingTime, allCategory[_categoryId].minStake ); } /** * @dev Gets category ab required and isSpecialResolution * @return the category id * @return if AB voting is required * @return is category a special resolution */ function categoryExtendedData(uint _categoryId) external view returns(uint, uint, uint) { return( _categoryId, categoryABReq[_categoryId], isSpecialResolution[_categoryId] ); } /** * @dev Gets the category acion details * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive */ function categoryAction(uint _categoryId) external view returns(uint, address, bytes2, uint) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive ); } /** * @dev Gets the category acion details of a category id * @param _categoryId is the category id in concern * @return the category id * @return the contract address * @return the contract name * @return the default incentive * @return action function hash */ function categoryActionDetails(uint _categoryId) external view returns(uint, address, bytes2, uint, bytes memory) { return( _categoryId, categoryActionData[_categoryId].contractAddress, categoryActionData[_categoryId].contractName, categoryActionData[_categoryId].defaultIncentive, categoryActionHashes[_categoryId] ); } /** * @dev Updates dependant contract addresses */ function changeDependentContractAddress() public { mr = MemberRoles(ms.getLatestAddress("MR")); } /** * @dev Adds new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function newCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } _addCategory( _name, _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _actionHash, _contractAddress, _contractName, _incentives ); if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[allCategory.length - 1] = abi.encodeWithSignature(_functionHash); } } /** * @dev Changes the master address and update it's instance * @param _masterAddress is the new master address */ function changeMasterAddress(address _masterAddress) public { if (masterAddress != address(0)) require(masterAddress == msg.sender); masterAddress = _masterAddress; ms = INXMMaster(_masterAddress); nxMasterAddress = _masterAddress; } /** * @dev Updates category details (Discontinued, moved functionality to editCategory) * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function updateCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) public deprecated { } /** * @dev Updates category details * @param _categoryId Category id that needs to be updated * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted * @param _functionHash function signature to be executed */ function editCategory( uint _categoryId, string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives, string memory _functionHash ) public onlyAuthorizedToGovern { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); require(_quorumPerc <= 100 && _majorityVotePerc <= 100, "Invalid percentage"); require((_contractName == "EX" && _contractAddress == address(0)) || bytes(_functionHash).length > 0); require(_incentives[3] <= 1, "Invalid special resolution flag"); //If category is special resolution role authorized should be member if (_incentives[3] == 1) { require(_memberRoleToVote == uint(MemberRoles.Role.Member)); _majorityVotePerc = 0; _quorumPerc = 0; } delete categoryActionHashes[_categoryId]; if (bytes(_functionHash).length > 0 && abi.encodeWithSignature(_functionHash).length == 4) { categoryActionHashes[_categoryId] = abi.encodeWithSignature(_functionHash); } allCategory[_categoryId].memberRoleToVote = _memberRoleToVote; allCategory[_categoryId].majorityVotePerc = _majorityVotePerc; allCategory[_categoryId].closingTime = _closingTime; allCategory[_categoryId].allowedToCreateProposal = _allowedToCreateProposal; allCategory[_categoryId].minStake = _incentives[0]; allCategory[_categoryId].quorumPerc = _quorumPerc; categoryActionData[_categoryId].defaultIncentive = _incentives[1]; categoryActionData[_categoryId].contractName = _contractName; categoryActionData[_categoryId].contractAddress = _contractAddress; categoryABReq[_categoryId] = _incentives[2]; isSpecialResolution[_categoryId] = _incentives[3]; emit Category(_categoryId, _name, _actionHash); } /** * @dev Internal call to add new category * @param _name Category name * @param _memberRoleToVote Voting Layer sequence in which the voting has to be performed. * @param _majorityVotePerc Majority Vote threshold for Each voting layer * @param _quorumPerc minimum threshold percentage required in voting to calculate result * @param _allowedToCreateProposal Member roles allowed to create the proposal * @param _closingTime Vote closing time for Each voting layer * @param _actionHash hash of details containing the action that has to be performed after proposal is accepted * @param _contractAddress address of contract to call after proposal is accepted * @param _contractName name of contract to be called after proposal is accepted * @param _incentives rewards to distributed after proposal is accepted */ function _addCategory( string memory _name, uint _memberRoleToVote, uint _majorityVotePerc, uint _quorumPerc, uint[] memory _allowedToCreateProposal, uint _closingTime, string memory _actionHash, address _contractAddress, bytes2 _contractName, uint[] memory _incentives ) internal { require(_verifyMemberRoles(_memberRoleToVote, _allowedToCreateProposal) == 1, "Invalid Role"); allCategory.push( CategoryStruct( _memberRoleToVote, _majorityVotePerc, _quorumPerc, _allowedToCreateProposal, _closingTime, _incentives[0] ) ); uint categoryId = allCategory.length - 1; categoryActionData[categoryId] = CategoryAction(_incentives[1], _contractAddress, _contractName); categoryABReq[categoryId] = _incentives[2]; isSpecialResolution[categoryId] = _incentives[3]; emit Category(categoryId, _name, _actionHash); } /** * @dev Internal call to check if given roles are valid or not */ function _verifyMemberRoles(uint _memberRoleToVote, uint[] memory _allowedToCreateProposal) internal view returns(uint) { uint totalRoles = mr.totalRoles(); if (_memberRoleToVote >= totalRoles) { return 0; } for (uint i = 0; i < _allowedToCreateProposal.length; i++) { if (_allowedToCreateProposal[i] >= totalRoles) { return 0; } } return 1; } } // File: nexusmutual-contracts/contracts/external/govblocks-protocol/interfaces/IGovernance.sol /* Copyright (C) 2017 GovBlocks.io This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract IGovernance { event Proposal( address indexed proposalOwner, uint256 indexed proposalId, uint256 dateAdd, string proposalTitle, string proposalSD, string proposalDescHash ); event Solution( uint256 indexed proposalId, address indexed solutionOwner, uint256 indexed solutionId, string solutionDescHash, uint256 dateAdd ); event Vote( address indexed from, uint256 indexed proposalId, uint256 indexed voteId, uint256 dateAdd, uint256 solutionChosen ); event RewardClaimed( address indexed member, uint gbtReward ); /// @dev VoteCast event is called whenever a vote is cast that can potentially close the proposal. event VoteCast (uint256 proposalId); /// @dev ProposalAccepted event is called when a proposal is accepted so that a server can listen that can /// call any offchain actions event ProposalAccepted (uint256 proposalId); /// @dev CloseProposalOnTime event is called whenever a proposal is created or updated to close it on time. event CloseProposalOnTime ( uint256 indexed proposalId, uint256 time ); /// @dev ActionSuccess event is called whenever an onchain action is executed. event ActionSuccess ( uint256 proposalId ); /// @dev Creates a new proposal /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external; /// @dev Edits the details of an existing proposal and creates new version /// @param _proposalId Proposal id that details needs to be updated /// @param _proposalDescHash Proposal description hash having long and short description of proposal. function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external; /// @dev Categorizes proposal to proceed further. Categories shows the proposal objective. function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentives ) external; /// @dev Initiates add solution /// @param _solutionHash Solution hash having required data against adding solution function addSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Opens proposal for voting function openProposalForVoting(uint _proposalId) external; /// @dev Submit proposal with solution /// @param _proposalId Proposal id /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Creates a new proposal with solution and votes for the solution /// @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal /// @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective /// @param _solutionHash Solution hash contains parameters, values and description needed according to proposal function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external; /// @dev Casts vote /// @param _proposalId Proposal id /// @param _solutionChosen solution chosen while voting. _solutionChosen[0] is the chosen solution function submitVote(uint _proposalId, uint _solutionChosen) external; function closeProposal(uint _proposalId) external; function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward); function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalReward ); function canCloseProposal(uint _proposalId) public view returns(uint closeValue); function pauseProposal(uint _proposalId) public; function resumeProposal(uint _proposalId) public; function allowedToCatgorize() public view returns(uint roleId); } // File: nexusmutual-contracts/contracts/Governance.sol // /* Copyright (C) 2017 GovBlocks.io // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/ */ pragma solidity 0.5.7; contract Governance is IGovernance, Iupgradable { using SafeMath for uint; enum ProposalStatus { Draft, AwaitingSolution, VotingStarted, Accepted, Rejected, Majority_Not_Reached_But_Accepted, Denied } struct ProposalData { uint propStatus; uint finalVerdict; uint category; uint commonIncentive; uint dateUpd; address owner; } struct ProposalVote { address voter; uint proposalId; uint dateAdd; } struct VoteTally { mapping(uint=>uint) memberVoteValue; mapping(uint=>uint) abVoteValue; uint voters; } struct DelegateVote { address follower; address leader; uint lastUpd; } ProposalVote[] internal allVotes; DelegateVote[] public allDelegation; mapping(uint => ProposalData) internal allProposalData; mapping(uint => bytes[]) internal allProposalSolutions; mapping(address => uint[]) internal allVotesByMember; mapping(uint => mapping(address => bool)) public rewardClaimed; mapping (address => mapping(uint => uint)) public memberProposalVote; mapping (address => uint) public followerDelegation; mapping (address => uint) internal followerCount; mapping (address => uint[]) internal leaderDelegation; mapping (uint => VoteTally) public proposalVoteTally; mapping (address => bool) public isOpenForDelegation; mapping (address => uint) public lastRewardClaimed; bool internal constructorCheck; uint public tokenHoldingTime; uint internal roleIdAllowedToCatgorize; uint internal maxVoteWeigthPer; uint internal specialResolutionMajPerc; uint internal maxFollowers; uint internal totalProposals; uint internal maxDraftTime; MemberRoles internal memberRole; ProposalCategory internal proposalCategory; TokenController internal tokenInstance; mapping(uint => uint) public proposalActionStatus; mapping(uint => uint) internal proposalExecutionTime; mapping(uint => mapping(address => bool)) public proposalRejectedByAB; mapping(uint => uint) internal actionRejectedCount; bool internal actionParamsInitialised; uint internal actionWaitingTime; uint constant internal AB_MAJ_TO_REJECT_ACTION = 3; enum ActionStatus { Pending, Accepted, Rejected, Executed, NoAction } /** * @dev Called whenever an action execution is failed. */ event ActionFailed ( uint256 proposalId ); /** * @dev Called whenever an AB member rejects the action execution. */ event ActionRejected ( uint256 indexed proposalId, address rejectedBy ); /** * @dev Checks if msg.sender is proposal owner */ modifier onlyProposalOwner(uint _proposalId) { require(msg.sender == allProposalData[_proposalId].owner, "Not allowed"); _; } /** * @dev Checks if proposal is opened for voting */ modifier voteNotStarted(uint _proposalId) { require(allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)); _; } /** * @dev Checks if msg.sender is allowed to create proposal under given category */ modifier isAllowed(uint _categoryId) { require(allowedToCreateProposal(_categoryId), "Not allowed"); _; } /** * @dev Checks if msg.sender is allowed categorize proposal under given category */ modifier isAllowedToCategorize() { require(memberRole.checkRole(msg.sender, roleIdAllowedToCatgorize), "Not allowed"); _; } /** * @dev Checks if msg.sender had any pending rewards to be claimed */ modifier checkPendingRewards { require(getPendingReward(msg.sender) == 0, "Claim reward"); _; } /** * @dev Event emitted whenever a proposal is categorized */ event ProposalCategorized( uint indexed proposalId, address indexed categorizedBy, uint categoryId ); /** * @dev Removes delegation of an address. * @param _add address to undelegate. */ function removeDelegation(address _add) external onlyInternal { _unDelegate(_add); } /** * @dev Creates a new proposal * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective */ function createProposal( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId ) external isAllowed(_categoryId) { require(ms.isMember(msg.sender), "Not Member"); _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); } /** * @dev Edits the details of an existing proposal * @param _proposalId Proposal id that details needs to be updated * @param _proposalDescHash Proposal description hash having long and short description of proposal. */ function updateProposal( uint _proposalId, string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash ) external onlyProposalOwner(_proposalId) { require( allProposalSolutions[_proposalId].length < 2, "Not allowed" ); allProposalData[_proposalId].propStatus = uint(ProposalStatus.Draft); allProposalData[_proposalId].category = 0; allProposalData[_proposalId].commonIncentive = 0; emit Proposal( allProposalData[_proposalId].owner, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); } /** * @dev Categorizes proposal to proceed further. Categories shows the proposal objective. */ function categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) external voteNotStarted(_proposalId) isAllowedToCategorize { _categorizeProposal(_proposalId, _categoryId, _incentive); } /** * @dev Initiates add solution * To implement the governance interface */ function addSolution(uint, string calldata, bytes calldata) external { } /** * @dev Opens proposal for voting * To implement the governance interface */ function openProposalForVoting(uint) external { } /** * @dev Submit proposal with solution * @param _proposalId Proposal id * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function submitProposalWithSolution( uint _proposalId, string calldata _solutionHash, bytes calldata _action ) external onlyProposalOwner(_proposalId) { require(allProposalData[_proposalId].propStatus == uint(ProposalStatus.AwaitingSolution)); _proposalSubmission(_proposalId, _solutionHash, _action); } /** * @dev Creates a new proposal with solution * @param _proposalDescHash Proposal description hash through IPFS having Short and long description of proposal * @param _categoryId This id tells under which the proposal is categorized i.e. Proposal's Objective * @param _solutionHash Solution hash contains parameters, values and description needed according to proposal */ function createProposalwithSolution( string calldata _proposalTitle, string calldata _proposalSD, string calldata _proposalDescHash, uint _categoryId, string calldata _solutionHash, bytes calldata _action ) external isAllowed(_categoryId) { uint proposalId = totalProposals; _createProposal(_proposalTitle, _proposalSD, _proposalDescHash, _categoryId); require(_categoryId > 0); _proposalSubmission( proposalId, _solutionHash, _action ); } /** * @dev Submit a vote on the proposal. * @param _proposalId to vote upon. * @param _solutionChosen is the chosen vote. */ function submitVote(uint _proposalId, uint _solutionChosen) external { require(allProposalData[_proposalId].propStatus == uint(Governance.ProposalStatus.VotingStarted), "Not allowed"); require(_solutionChosen < allProposalSolutions[_proposalId].length); _submitVote(_proposalId, _solutionChosen); } /** * @dev Closes the proposal. * @param _proposalId of proposal to be closed. */ function closeProposal(uint _proposalId) external { uint category = allProposalData[_proposalId].category; uint _memberRole; if (allProposalData[_proposalId].dateUpd.add(maxDraftTime) <= now && allProposalData[_proposalId].propStatus < uint(ProposalStatus.VotingStarted)) { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } else { require(canCloseProposal(_proposalId) == 1); (, _memberRole, , , , , ) = proposalCategory.category(allProposalData[_proposalId].category); if (_memberRole == uint(MemberRoles.Role.AdvisoryBoard)) { _closeAdvisoryBoardVote(_proposalId, category); } else { _closeMemberVote(_proposalId, category); } } } /** * @dev Claims reward for member. * @param _memberAddress to claim reward of. * @param _maxRecords maximum number of records to claim reward for. _proposals list of proposals of which reward will be claimed. * @return amount of pending reward. */ function claimReward(address _memberAddress, uint _maxRecords) external returns(uint pendingDAppReward) { uint voteId; address leader; uint lastUpd; require(msg.sender == ms.getLatestAddress("CR")); uint delegationId = followerDelegation[_memberAddress]; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; uint totalVotes = allVotesByMember[leader].length; uint lastClaimed = totalVotes; uint j; uint i; for (i = lastRewardClaimed[_memberAddress]; i < totalVotes && j < _maxRecords; i++) { voteId = allVotesByMember[leader][i]; proposalId = allVotes[voteId].proposalId; if (proposalVoteTally[proposalId].voters > 0 && (allVotes[voteId].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress)) { if (allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { if (!rewardClaimed[voteId][_memberAddress]) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); rewardClaimed[voteId][_memberAddress] = true; j++; } } else { if (lastClaimed == totalVotes) { lastClaimed = i; } } } } if (lastClaimed == totalVotes) { lastRewardClaimed[_memberAddress] = i; } else { lastRewardClaimed[_memberAddress] = lastClaimed; } if (j > 0) { emit RewardClaimed( _memberAddress, pendingDAppReward ); } } /** * @dev Sets delegation acceptance status of individual user * @param _status delegation acceptance status */ function setDelegationStatus(bool _status) external isMemberAndcheckPause checkPendingRewards { isOpenForDelegation[msg.sender] = _status; } /** * @dev Delegates vote to an address. * @param _add is the address to delegate vote to. */ function delegateVote(address _add) external isMemberAndcheckPause checkPendingRewards { require(ms.masterInitialized()); require(allDelegation[followerDelegation[_add]].leader == address(0)); if (followerDelegation[msg.sender] > 0) { require((allDelegation[followerDelegation[msg.sender]].lastUpd).add(tokenHoldingTime) < now); } require(!alreadyDelegated(msg.sender)); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.Owner))); require(!memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard))); require(followerCount[_add] < maxFollowers); if (allVotesByMember[msg.sender].length > 0) { require((allVotes[allVotesByMember[msg.sender][allVotesByMember[msg.sender].length - 1]].dateAdd).add(tokenHoldingTime) < now); } require(ms.isMember(_add)); require(isOpenForDelegation[_add]); allDelegation.push(DelegateVote(msg.sender, _add, now)); followerDelegation[msg.sender] = allDelegation.length - 1; leaderDelegation[_add].push(allDelegation.length - 1); followerCount[_add]++; lastRewardClaimed[msg.sender] = allVotesByMember[_add].length; } /** * @dev Undelegates the sender */ function unDelegate() external isMemberAndcheckPause checkPendingRewards { _unDelegate(msg.sender); } /** * @dev Triggers action of accepted proposal after waiting time is finished */ function triggerAction(uint _proposalId) external { require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted) && proposalExecutionTime[_proposalId] <= now, "Cannot trigger"); _triggerAction(_proposalId, allProposalData[_proposalId].category); } /** * @dev Provides option to Advisory board member to reject proposal action execution within actionWaitingTime, if found suspicious */ function rejectAction(uint _proposalId) external { require(memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && proposalExecutionTime[_proposalId] > now); require(proposalActionStatus[_proposalId] == uint(ActionStatus.Accepted)); require(!proposalRejectedByAB[_proposalId][msg.sender]); require( keccak256(proposalCategory.categoryActionHashes(allProposalData[_proposalId].category)) != keccak256(abi.encodeWithSignature("swapABMember(address,address)")) ); proposalRejectedByAB[_proposalId][msg.sender] = true; actionRejectedCount[_proposalId]++; emit ActionRejected(_proposalId, msg.sender); if (actionRejectedCount[_proposalId] == AB_MAJ_TO_REJECT_ACTION) { proposalActionStatus[_proposalId] = uint(ActionStatus.Rejected); } } /** * @dev Sets intial actionWaitingTime value * To be called after governance implementation has been updated */ function setInitialActionParameters() external onlyOwner { require(!actionParamsInitialised); actionParamsInitialised = true; actionWaitingTime = 24 * 1 hours; } /** * @dev Gets Uint Parameters of a code * @param code whose details we want * @return string value of the code * @return associated amount (time or perc or value) to the code */ function getUintParameters(bytes8 code) external view returns(bytes8 codeVal, uint val) { codeVal = code; if (code == "GOVHOLD") { val = tokenHoldingTime / (1 days); } else if (code == "MAXFOL") { val = maxFollowers; } else if (code == "MAXDRFT") { val = maxDraftTime / (1 days); } else if (code == "EPTIME") { val = ms.pauseTime() / (1 days); } else if (code == "ACWT") { val = actionWaitingTime / (1 hours); } } /** * @dev Gets all details of a propsal * @param _proposalId whose details we want * @return proposalId * @return category * @return status * @return finalVerdict * @return totalReward */ function proposal(uint _proposalId) external view returns( uint proposalId, uint category, uint status, uint finalVerdict, uint totalRewar ) { return( _proposalId, allProposalData[_proposalId].category, allProposalData[_proposalId].propStatus, allProposalData[_proposalId].finalVerdict, allProposalData[_proposalId].commonIncentive ); } /** * @dev Gets some details of a propsal * @param _proposalId whose details we want * @return proposalId * @return number of all proposal solutions * @return amount of votes */ function proposalDetails(uint _proposalId) external view returns(uint, uint, uint) { return( _proposalId, allProposalSolutions[_proposalId].length, proposalVoteTally[_proposalId].voters ); } /** * @dev Gets solution action on a proposal * @param _proposalId whose details we want * @param _solution whose details we want * @return action of a solution on a proposal */ function getSolutionAction(uint _proposalId, uint _solution) external view returns(uint, bytes memory) { return ( _solution, allProposalSolutions[_proposalId][_solution] ); } /** * @dev Gets length of propsal * @return length of propsal */ function getProposalLength() external view returns(uint) { return totalProposals; } /** * @dev Get followers of an address * @return get followers of an address */ function getFollowers(address _add) external view returns(uint[] memory) { return leaderDelegation[_add]; } /** * @dev Gets pending rewards of a member * @param _memberAddress in concern * @return amount of pending reward */ function getPendingReward(address _memberAddress) public view returns(uint pendingDAppReward) { uint delegationId = followerDelegation[_memberAddress]; address leader; uint lastUpd; DelegateVote memory delegationData = allDelegation[delegationId]; if (delegationId > 0 && delegationData.leader != address(0)) { leader = delegationData.leader; lastUpd = delegationData.lastUpd; } else leader = _memberAddress; uint proposalId; for (uint i = lastRewardClaimed[_memberAddress]; i < allVotesByMember[leader].length; i++) { if (allVotes[allVotesByMember[leader][i]].dateAdd > ( lastUpd.add(tokenHoldingTime)) || leader == _memberAddress) { if (!rewardClaimed[allVotesByMember[leader][i]][_memberAddress]) { proposalId = allVotes[allVotesByMember[leader][i]].proposalId; if (proposalVoteTally[proposalId].voters > 0 && allProposalData[proposalId].propStatus > uint(ProposalStatus.VotingStarted)) { pendingDAppReward = pendingDAppReward.add( allProposalData[proposalId].commonIncentive.div( proposalVoteTally[proposalId].voters ) ); } } } } } /** * @dev Updates Uint Parameters of a code * @param code whose details we want to update * @param val value to set */ function updateUintParameters(bytes8 code, uint val) public { require(ms.checkIsAuthToGoverned(msg.sender)); if (code == "GOVHOLD") { tokenHoldingTime = val * 1 days; } else if (code == "MAXFOL") { maxFollowers = val; } else if (code == "MAXDRFT") { maxDraftTime = val * 1 days; } else if (code == "EPTIME") { ms.updatePauseTime(val * 1 days); } else if (code == "ACWT") { actionWaitingTime = val * 1 hours; } else { revert("Invalid code"); } } /** * @dev Updates all dependency addresses to latest ones from Master */ function changeDependentContractAddress() public { tokenInstance = TokenController(ms.dAppLocker()); memberRole = MemberRoles(ms.getLatestAddress("MR")); proposalCategory = ProposalCategory(ms.getLatestAddress("PC")); } /** * @dev Checks if msg.sender is allowed to create a proposal under given category */ function allowedToCreateProposal(uint category) public view returns(bool check) { if (category == 0) return true; uint[] memory mrAllowed; (, , , , mrAllowed, , ) = proposalCategory.category(category); for (uint i = 0; i < mrAllowed.length; i++) { if (mrAllowed[i] == 0 || memberRole.checkRole(msg.sender, mrAllowed[i])) return true; } } /** * @dev Checks if an address is already delegated * @param _add in concern * @return bool value if the address is delegated or not */ function alreadyDelegated(address _add) public view returns(bool delegated) { for (uint i=0; i < leaderDelegation[_add].length; i++) { if (allDelegation[leaderDelegation[_add][i]].leader == _add) { return true; } } } /** * @dev Pauses a proposal * To implement govblocks interface */ function pauseProposal(uint) public { } /** * @dev Resumes a proposal * To implement govblocks interface */ function resumeProposal(uint) public { } /** * @dev Checks If the proposal voting time is up and it's ready to close * i.e. Closevalue is 1 if proposal is ready to be closed, 2 if already closed, 0 otherwise! * @param _proposalId Proposal id to which closing value is being checked */ function canCloseProposal(uint _proposalId) public view returns(uint) { uint dateUpdate; uint pStatus; uint _closingTime; uint _roleId; uint majority; pStatus = allProposalData[_proposalId].propStatus; dateUpdate = allProposalData[_proposalId].dateUpd; (, _roleId, majority, , , _closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); if ( pStatus == uint(ProposalStatus.VotingStarted) ) { uint numberOfMembers = memberRole.numberOfMembers(_roleId); if (_roleId == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0]) == numberOfMembers || dateUpdate.add(_closingTime) <= now) { return 1; } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters || dateUpdate.add(_closingTime) <= now) return 1; } } else if (pStatus > uint(ProposalStatus.VotingStarted)) { return 2; } else { return 0; } } /** * @dev Gets Id of member role allowed to categorize the proposal * @return roleId allowed to categorize the proposal */ function allowedToCatgorize() public view returns(uint roleId) { return roleIdAllowedToCatgorize; } /** * @dev Gets vote tally data * @param _proposalId in concern * @param _solution of a proposal id * @return member vote value * @return advisory board vote value * @return amount of votes */ function voteTallyData(uint _proposalId, uint _solution) public view returns(uint, uint, uint) { return (proposalVoteTally[_proposalId].memberVoteValue[_solution], proposalVoteTally[_proposalId].abVoteValue[_solution], proposalVoteTally[_proposalId].voters); } /** * @dev Internal call to create proposal * @param _proposalTitle of proposal * @param _proposalSD is short description of proposal * @param _proposalDescHash IPFS hash value of propsal * @param _categoryId of proposal */ function _createProposal( string memory _proposalTitle, string memory _proposalSD, string memory _proposalDescHash, uint _categoryId ) internal { require(proposalCategory.categoryABReq(_categoryId) == 0 || _categoryId == 0); uint _proposalId = totalProposals; allProposalData[_proposalId].owner = msg.sender; allProposalData[_proposalId].dateUpd = now; allProposalSolutions[_proposalId].push(""); totalProposals++; emit Proposal( msg.sender, _proposalId, now, _proposalTitle, _proposalSD, _proposalDescHash ); if (_categoryId > 0) _categorizeProposal(_proposalId, _categoryId, 0); } /** * @dev Internal call to categorize a proposal * @param _proposalId of proposal * @param _categoryId of proposal * @param _incentive is commonIncentive */ function _categorizeProposal( uint _proposalId, uint _categoryId, uint _incentive ) internal { require( _categoryId > 0 && _categoryId < proposalCategory.totalCategories(), "Invalid category" ); allProposalData[_proposalId].category = _categoryId; allProposalData[_proposalId].commonIncentive = _incentive; allProposalData[_proposalId].propStatus = uint(ProposalStatus.AwaitingSolution); emit ProposalCategorized(_proposalId, msg.sender, _categoryId); } /** * @dev Internal call to add solution to a proposal * @param _proposalId in concern * @param _action on that solution * @param _solutionHash string value */ function _addSolution(uint _proposalId, bytes memory _action, string memory _solutionHash) internal { allProposalSolutions[_proposalId].push(_action); emit Solution(_proposalId, msg.sender, allProposalSolutions[_proposalId].length - 1, _solutionHash, now); } /** * @dev Internal call to add solution and open proposal for voting */ function _proposalSubmission( uint _proposalId, string memory _solutionHash, bytes memory _action ) internal { uint _categoryId = allProposalData[_proposalId].category; if (proposalCategory.categoryActionHashes(_categoryId).length == 0) { require(keccak256(_action) == keccak256("")); proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } _addSolution( _proposalId, _action, _solutionHash ); _updateProposalStatus(_proposalId, uint(ProposalStatus.VotingStarted)); (, , , , , uint closingTime, ) = proposalCategory.category(_categoryId); emit CloseProposalOnTime(_proposalId, closingTime.add(now)); } /** * @dev Internal call to submit vote * @param _proposalId of proposal in concern * @param _solution for that proposal */ function _submitVote(uint _proposalId, uint _solution) internal { uint delegationId = followerDelegation[msg.sender]; uint mrSequence; uint majority; uint closingTime; (, mrSequence, majority, , , closingTime, ) = proposalCategory.category(allProposalData[_proposalId].category); require(allProposalData[_proposalId].dateUpd.add(closingTime) > now, "Closed"); require(memberProposalVote[msg.sender][_proposalId] == 0, "Not allowed"); require((delegationId == 0) || (delegationId > 0 && allDelegation[delegationId].leader == address(0) && _checkLastUpd(allDelegation[delegationId].lastUpd))); require(memberRole.checkRole(msg.sender, mrSequence), "Not Authorized"); uint totalVotes = allVotes.length; allVotesByMember[msg.sender].push(totalVotes); memberProposalVote[msg.sender][_proposalId] = totalVotes; allVotes.push(ProposalVote(msg.sender, _proposalId, now)); emit Vote(msg.sender, _proposalId, totalVotes, now, _solution); if (mrSequence == uint(MemberRoles.Role.Owner)) { if (_solution == 1) _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), allProposalData[_proposalId].category, 1, MemberRoles.Role.Owner); else _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } else { uint numberOfMembers = memberRole.numberOfMembers(mrSequence); _setVoteTally(_proposalId, _solution, mrSequence); if (mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100).div(numberOfMembers) >= majority || (proposalVoteTally[_proposalId].abVoteValue[1].add(proposalVoteTally[_proposalId].abVoteValue[0])) == numberOfMembers) { emit VoteCast(_proposalId); } } else { if (numberOfMembers == proposalVoteTally[_proposalId].voters) emit VoteCast(_proposalId); } } } /** * @dev Internal call to set vote tally of a proposal * @param _proposalId of proposal in concern * @param _solution of proposal in concern * @param mrSequence number of members for a role */ function _setVoteTally(uint _proposalId, uint _solution, uint mrSequence) internal { uint categoryABReq; uint isSpecialResolution; (, categoryABReq, isSpecialResolution) = proposalCategory.categoryExtendedData(allProposalData[_proposalId].category); if (memberRole.checkRole(msg.sender, uint(MemberRoles.Role.AdvisoryBoard)) && (categoryABReq > 0) || mrSequence == uint(MemberRoles.Role.AdvisoryBoard)) { proposalVoteTally[_proposalId].abVoteValue[_solution]++; } tokenInstance.lockForMemberVote(msg.sender, tokenHoldingTime); if (mrSequence != uint(MemberRoles.Role.AdvisoryBoard)) { uint voteWeight; uint voters = 1; uint tokenBalance = tokenInstance.totalBalanceOf(msg.sender); uint totalSupply = tokenInstance.totalSupply(); if (isSpecialResolution == 1) { voteWeight = tokenBalance.add(10**18); } else { voteWeight = (_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18); } DelegateVote memory delegationData; for (uint i = 0; i < leaderDelegation[msg.sender].length; i++) { delegationData = allDelegation[leaderDelegation[msg.sender][i]]; if (delegationData.leader == msg.sender && _checkLastUpd(delegationData.lastUpd)) { if (memberRole.checkRole(delegationData.follower, mrSequence)) { tokenBalance = tokenInstance.totalBalanceOf(delegationData.follower); tokenInstance.lockForMemberVote(delegationData.follower, tokenHoldingTime); voters++; if (isSpecialResolution == 1) { voteWeight = voteWeight.add(tokenBalance.add(10**18)); } else { voteWeight = voteWeight.add((_minOf(tokenBalance, maxVoteWeigthPer.mul(totalSupply).div(100))).add(10**18)); } } } } proposalVoteTally[_proposalId].memberVoteValue[_solution] = proposalVoteTally[_proposalId].memberVoteValue[_solution].add(voteWeight); proposalVoteTally[_proposalId].voters = proposalVoteTally[_proposalId].voters + voters; } } /** * @dev Gets minimum of two numbers * @param a one of the two numbers * @param b one of the two numbers * @return minimum number out of the two */ function _minOf(uint a, uint b) internal pure returns(uint res) { res = a; if (res > b) res = b; } /** * @dev Check the time since last update has exceeded token holding time or not * @param _lastUpd is last update time * @return the bool which tells if the time since last update has exceeded token holding time or not */ function _checkLastUpd(uint _lastUpd) internal view returns(bool) { return (now - _lastUpd) > tokenHoldingTime; } /** * @dev Checks if the vote count against any solution passes the threshold value or not. */ function _checkForThreshold(uint _proposalId, uint _category) internal view returns(bool check) { uint categoryQuorumPerc; uint roleAuthorized; (, roleAuthorized, , categoryQuorumPerc, , , ) = proposalCategory.category(_category); check = ((proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1])) .mul(100)) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(roleAuthorized).mul(10 ** 18) ) ) >= categoryQuorumPerc; } /** * @dev Called when vote majority is reached * @param _proposalId of proposal in concern * @param _status of proposal in concern * @param category of proposal in concern * @param max vote value of proposal in concern */ function _callIfMajReached(uint _proposalId, uint _status, uint category, uint max, MemberRoles.Role role) internal { allProposalData[_proposalId].finalVerdict = max; _updateProposalStatus(_proposalId, _status); emit ProposalAccepted(_proposalId); if (proposalActionStatus[_proposalId] != uint(ActionStatus.NoAction)) { if (role == MemberRoles.Role.AdvisoryBoard) { _triggerAction(_proposalId, category); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); proposalExecutionTime[_proposalId] = actionWaitingTime.add(now); } } } /** * @dev Internal function to trigger action of accepted proposal */ function _triggerAction(uint _proposalId, uint _categoryId) internal { proposalActionStatus[_proposalId] = uint(ActionStatus.Executed); bytes2 contractName; address actionAddress; bytes memory _functionHash; (, actionAddress, contractName, , _functionHash) = proposalCategory.categoryActionDetails(_categoryId); if (contractName == "MS") { actionAddress = address(ms); } else if (contractName != "EX") { actionAddress = ms.getLatestAddress(contractName); } (bool actionStatus, ) = actionAddress.call(abi.encodePacked(_functionHash, allProposalSolutions[_proposalId][1])); if (actionStatus) { emit ActionSuccess(_proposalId); } else { proposalActionStatus[_proposalId] = uint(ActionStatus.Accepted); emit ActionFailed(_proposalId); } } /** * @dev Internal call to update proposal status * @param _proposalId of proposal in concern * @param _status of proposal to set */ function _updateProposalStatus(uint _proposalId, uint _status) internal { if (_status == uint(ProposalStatus.Rejected) || _status == uint(ProposalStatus.Denied)) { proposalActionStatus[_proposalId] = uint(ActionStatus.NoAction); } allProposalData[_proposalId].dateUpd = now; allProposalData[_proposalId].propStatus = _status; } /** * @dev Internal call to undelegate a follower * @param _follower is address of follower to undelegate */ function _unDelegate(address _follower) internal { uint followerId = followerDelegation[_follower]; if (followerId > 0) { followerCount[allDelegation[followerId].leader] = followerCount[allDelegation[followerId].leader].sub(1); allDelegation[followerId].leader = address(0); allDelegation[followerId].lastUpd = now; lastRewardClaimed[_follower] = allVotesByMember[_follower].length; } } /** * @dev Internal call to close member voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeMemberVote(uint _proposalId, uint category) internal { uint isSpecialResolution; uint abMaj; (, abMaj, isSpecialResolution) = proposalCategory.categoryExtendedData(category); if (isSpecialResolution == 1) { uint acceptedVotePerc = proposalVoteTally[_proposalId].memberVoteValue[1].mul(100) .div( tokenInstance.totalSupply().add( memberRole.numberOfMembers(uint(MemberRoles.Role.Member)).mul(10**18) )); if (acceptedVotePerc >= specialResolutionMajPerc) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } else { if (_checkForThreshold(_proposalId, category)) { uint majorityVote; (, , majorityVote, , , , ) = proposalCategory.category(category); if ( ((proposalVoteTally[_proposalId].memberVoteValue[1].mul(100)) .div(proposalVoteTally[_proposalId].memberVoteValue[0] .add(proposalVoteTally[_proposalId].memberVoteValue[1]) )) >= majorityVote ) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Rejected)); } } else { if (abMaj > 0 && proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(MemberRoles.Role.AdvisoryBoard))) >= abMaj) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, MemberRoles.Role.Member); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } } if (proposalVoteTally[_proposalId].voters > 0) { tokenInstance.mint(ms.getLatestAddress("CR"), allProposalData[_proposalId].commonIncentive); } } /** * @dev Internal call to close advisory board voting * @param _proposalId of proposal in concern * @param category of proposal in concern */ function _closeAdvisoryBoardVote(uint _proposalId, uint category) internal { uint _majorityVote; MemberRoles.Role _roleId = MemberRoles.Role.AdvisoryBoard; (, , _majorityVote, , , , ) = proposalCategory.category(category); if (proposalVoteTally[_proposalId].abVoteValue[1].mul(100) .div(memberRole.numberOfMembers(uint(_roleId))) >= _majorityVote) { _callIfMajReached(_proposalId, uint(ProposalStatus.Accepted), category, 1, _roleId); } else { _updateProposalStatus(_proposalId, uint(ProposalStatus.Denied)); } } }
* @dev Function used to get pending rewards of a particular user address. @param _add user address. @return total reward amount of the user/
function getAllPendingRewardOfUser(address _add) public view returns(uint) { uint caReward = getRewardToBeDistributedByUser(_add); uint pooledStakingReward = pooledStaking.stakerReward(_add); uint governanceReward = gv.getPendingReward(_add); return caReward.add(pooledStakingReward).add(governanceReward); }
7,287,307
[ 1, 2083, 1399, 358, 336, 4634, 283, 6397, 434, 279, 6826, 729, 1758, 18, 225, 389, 1289, 729, 1758, 18, 327, 2078, 19890, 3844, 434, 326, 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 ]
[ 1, 1, 1, 1, 1, 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, 5514, 8579, 17631, 1060, 951, 1299, 12, 2867, 389, 1289, 13, 1071, 1476, 1135, 12, 11890, 13, 288, 203, 3639, 2254, 3474, 17631, 1060, 273, 4170, 359, 1060, 15360, 1669, 11050, 25895, 24899, 1289, 1769, 203, 3639, 2254, 25007, 510, 6159, 17631, 1060, 273, 25007, 510, 6159, 18, 334, 6388, 17631, 1060, 24899, 1289, 1769, 203, 3639, 2254, 314, 1643, 82, 1359, 17631, 1060, 273, 11404, 18, 588, 8579, 17631, 1060, 24899, 1289, 1769, 203, 3639, 327, 3474, 17631, 1060, 18, 1289, 12, 1631, 20212, 510, 6159, 17631, 1060, 2934, 1289, 12, 75, 1643, 82, 1359, 17631, 1060, 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 ]
./partial_match/1/0xEc6084462E330387cED0864677095B00e92Ca3FC/sources/Vault.sol
* This function allows liquidity to be moved, after a 14 days lockup -preventing abuse./
function startLiquidityMigration(address recipient) external { require(msg.sender == owner); migrationLock = now + 14 days; migrationRecipient = recipient; emit liquidityMigrationStarted(recipient, migrationLock); }
3,969,428
[ 1, 2503, 445, 5360, 4501, 372, 24237, 358, 506, 10456, 16, 1839, 279, 5045, 4681, 2176, 416, 300, 29150, 310, 1223, 1202, 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, 445, 787, 48, 18988, 24237, 10224, 12, 2867, 8027, 13, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 1769, 203, 3639, 6333, 2531, 273, 2037, 397, 5045, 4681, 31, 203, 3639, 6333, 18241, 273, 8027, 31, 203, 3639, 3626, 4501, 372, 24237, 10224, 9217, 12, 20367, 16, 6333, 2531, 1769, 203, 565, 289, 203, 377, 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 ]
./partial_match/56/0xEdc87D90891162CF21F408403f55420C3aCFf735/sources/MasterChef.sol
withdraw fee variables
uint256 stablebscpools_w_fee = 2;
11,103,335
[ 1, 1918, 9446, 14036, 3152, 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, 2254, 5034, 14114, 70, 1017, 27663, 67, 91, 67, 21386, 273, 576, 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 ]
// SPDX-License-Identifier: AGPL-3.0 // ©2022 Ponderware Ltd pragma solidity ^0.8.12; import "./openzeppelin/contracts/utils/introspection/IERC165.sol"; import "./openzeppelin/contracts/token/ERC721/IERC721.sol"; import "./openzeppelin/contracts/token/ERC721/IERC721Receiver.sol"; import "./openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol"; import "./openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol"; interface IReverseResolver { function claim(address owner) external returns (bytes32); } interface IERC20 { function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); } interface IQuest3Data { function getDeath (uint256 seed, uint256 prevLevel, bytes[8] memory stats) external view returns (bytes memory death, string memory ending); function getFail (uint256 seed, uint256 level, bytes[8] memory stats) external view returns (bytes memory happening); function getAdvance (uint256 seed, uint256 level, bytes[8] memory stats) external view returns (bytes memory happening, bytes memory stat); function getMetadata (uint256 tokenId, uint256 level, uint8 journeyLength, bytes[15] memory storySegments, bytes[8] memory stats, uint16 heroStatus) external pure returns (string memory); function generateCompletionImage (uint tokenId, uint level, bytes memory lastWords, uint heroStatus) external pure returns (bytes memory); function generateProgressImage (uint tokenId, uint level) external pure returns (bytes memory); } /** * @title Quest3 * @author Ponderware Ltd (a.k.a. Pondertech Digital Solutions) * @notice ERC-721 Quest Tokens (where will your journey lead?) * @dev ERC-721 Enumerable Token with fully-on-chain ERC721 Metadata */ contract Quest3 is IERC721Enumerable, IERC721Metadata { string public name = "Quest-3"; string public symbol = unicode"⛰"; uint256 public maxSupply = 25600; uint256 public totalSupply = 0; address public contractOwner; address[25600] internal Owners; // Maps tokenIds to owning addresses. mapping (address => uint256[]) internal TokensByOwner; // Mapping from address to owned tokens. uint16[25600] internal OwnerTokenIndex; // Maps the a tokenId to its index in the `TokensByOwner[address]` array. mapping(uint256 => address) internal TokenApprovals; // Mapping from token ID to approved address. mapping(address => mapping(address => bool)) internal OperatorApprovals; // Mapping from owner to operator approvals. bool paused = true; // Pausing stops all user interactions. bool frozen = false; // Freezing stops minting and actions. uint256 public MintPriceWei = 0.01994206980085 ether; /** * @dev Contains the journey information for the token. Idx 0 is the journey length, Idx [1..14] contains the reveal seed at level of the token at that journey position, and Idx 15 is a flag to indicate if an action is in the `ActionQueue`. */ mapping (uint256 => uint16[16]) TokenHistory; /** * @dev The number of items a token must reveal to increase their hero status. */ uint256 public HeroThreshold = 10; /** * @dev If a token reveals more than HeroThreshold actions, the number of reveals is added to that token's hero status. */ uint16[25600] public HeroStatus; /** * @dev Reference to the metadata assembly contract. */ IQuest3Data Data; // Owner Functions constructor (address quest3DataContract) { contractOwner = msg.sender; Data = IQuest3Data(quest3DataContract); IReverseResolver(0x084b1c3C81545d370f3634392De611CaaBFf8148).claim(msg.sender); } /** * @dev Change the owner of the contract. */ function transferOwnership (address newOwner) public onlyOwner { contractOwner = newOwner; } function pause () public onlyOwner { paused = true; } function unpause () public onlyOwner { paused = false; } function ownerWithdraw () public { payable(contractOwner).transfer(address(this).balance); } function clearPendingStatus (uint256 tokenId) public onlyOwner { TokenHistory[tokenId][IS_PENDING_INDEX] = 0; } function setHeroThreshold (uint256 threshold) public onlyOwner { HeroThreshold = threshold; } /** * @dev Set `maxSupply` to `totalSupply` to end minting. */ function permanentlyCloseMint() public onlyOwner { maxSupply = totalSupply; } /** * @dev When frozen action (and mint) calls will throw. */ function setFrozen (bool state) public onlyOwner { frozen = state; } // Modifiers modifier onlyOwner() { require(msg.sender == contractOwner, "Not Owner"); _; } modifier whenNotPaused() { require(paused == false || msg.sender == contractOwner, "Paused"); _; } // Action Queue /** * @dev Actions are placed into the FIFO `ActionQueue` ring and revealed on future blocks. */ Action[256] public ActionQueue; uint constant public MAX_QUEUE = 256; /** * @dev Actions are queued. The `revealBlock` is the block at which this action becomes eligible for reveal. */ struct Action { uint128 revealBlock; uint128 tokenId; } /** * @dev `count` is the current length of the queue. `index` is the offset to the first queue item. */ struct QueueCursor { uint16 index; uint16 count; } QueueCursor public Cursor = QueueCursor(0,0); function getQueueLength () public view returns (uint256) { return Cursor.count; } /** * @dev Assembles the `ActionQueue` into an array of actions in order (deconstructs the "ring"). */ function getQueue () public view returns (Action[] memory) { uint count = Cursor.count; uint index = Cursor.index; Action[] memory queue = new Action[](count); for (uint i = 0; i < queue.length; i++) { queue[i] = ActionQueue[index]; index++; if(index == MAX_QUEUE) index = 0; } return queue; } // Quest Actions / Progress Handling /** * @dev Indexes into `TokenHistory` arrays. The seed/level data is stored in indexes [1..14]. */ uint256 constant JOURNEY_LENGTH_INDEX = 0; uint256 constant IS_PENDING_INDEX = 15; /** * @dev Reveals the most recent pending action on a token. Packs the result into [seed (12 bits), level (4 bits)]. */ function updateTokenHistory (uint256 tokenId) internal { uint16[16] storage history = TokenHistory[tokenId]; uint journeyLength = history[JOURNEY_LENGTH_INDEX]; uint level = history[journeyLength] & 15; uint prevLevel = 0; if (journeyLength == 0) { level = 1; // starting level } else if (journeyLength == 1) { prevLevel = 1; // starting level is always 1 } else { prevLevel = history[journeyLength - 1] & 15; // prevLevel is penultimate level in pendingHistory } uint nextSeed = uint256(keccak256(abi.encodePacked(tokenId, blockhash(block.number-1)))); uint resolution = nextSeed & 255; uint deathThreshold = 5 + level * 9; uint failThreshold = 90 + level * 22; if (level == 1) { deathThreshold = 2; } // low chance to die on level 1 if (prevLevel == level) { failThreshold = 0; } // must die or advance if (resolution < deathThreshold) { level = 0; // died } else if (resolution >= failThreshold) { level = level + 1; // advanced } history[JOURNEY_LENGTH_INDEX] = uint16(journeyLength + 1); history[journeyLength + 1] = uint16((nextSeed << 4) + level); history[IS_PENDING_INDEX] = 0; } /** * @dev Reveals up to `maxReveals` pending `Action`s in the Action Queue, then enqueues the supplied `tokenId` if eligible. */ function handleAction (uint256 tokenId, uint256 maxReveals) private whenNotPaused { require(frozen == false, "Frozen"); uint count = Cursor.count; uint index = Cursor.index; if (maxReveals < 3) { maxReveals = 3; } uint revealCount = 0; for (uint i = 0; i < maxReveals; i++) { if (count == 0) break; Action storage action = ActionQueue[index]; if (block.number <= action.revealBlock) break; updateTokenHistory(action.tokenId); delete ActionQueue[index]; count--; index++; revealCount++; if(index == MAX_QUEUE) index = 0; } if (revealCount >= HeroThreshold) { HeroStatus[tokenId] += uint16(revealCount); } uint16[16] storage history = TokenHistory[tokenId]; uint tokenJourneyLength = history[JOURNEY_LENGTH_INDEX]; uint tokenLevel = history[tokenJourneyLength] & 15; if (((tokenLevel > 0 && tokenLevel < 8) || tokenJourneyLength == 0) && count < MAX_QUEUE && history[IS_PENDING_INDEX] == 0) { uint tokenQueueIndex = count + index; count++; if (MAX_QUEUE <= tokenQueueIndex) { tokenQueueIndex -= MAX_QUEUE; } ActionQueue[tokenQueueIndex] = Action(uint128(block.number + 1), uint128(tokenId)); history[IS_PENDING_INDEX] = 1; } Cursor.count = uint16(count); Cursor.index = uint16(index); } /** * @notice Like `doSomething` but set a max number of reveals to perform (must be >= HeroThreshold). If it reveals enough, the number of reveals will be added to the tokens HeroScore. Can be called even if your quest is complete. * @dev Cannot be called by a smart contract. */ function doSomethingHeroic (uint256 tokenId, uint256 maxAssists) public { require(msg.sender == Owners[tokenId] && msg.sender == tx.origin, "Not Owner"); require(maxAssists >= HeroThreshold, "A true hero must assist many others"); handleAction(tokenId, maxAssists); } /** * @notice Places the token into the `ActionQueue` where it will be revealed by actions in future blocks. Reveals up to 3 pending actions. * @dev Cannot be called by a smart contract. */ function doSomething (uint256 tokenId) public { require(msg.sender == Owners[tokenId] && msg.sender == tx.origin, "Not Owner"); handleAction(tokenId, 3); } /** * @notice Like `doSomething` but allows multiple tokenIds to be put in the ActionQueue. * @dev Cannot be called by a smart contract. */ function doSomething (uint256[] memory tokenIds) public { require(msg.sender == tx.origin); for (uint i = 0; i < tokenIds.length; i++) { uint256 tokenId = tokenIds[i]; require(msg.sender == Owners[tokenId], "Not Owner"); handleAction(tokenId, 3); } } // Minting /** * @dev Bookkeeping for minting. Note: minting does not guarantee entry into the `ActionQueue`. */ function mintHelper (address recipient) private { uint256 tokenId = totalSupply; TokensByOwner[recipient].push(tokenId); OwnerTokenIndex[tokenId] = uint16(TokensByOwner[recipient].length); Owners[tokenId] = recipient; totalSupply++; handleAction(tokenId, 3); emit Transfer(address(0), recipient, tokenId); } /** * @notice Mint tokens to the provided recipient address, quantity per call is limited to 10. */ function mint (address recipient, uint256 quantity) public payable whenNotPaused { require (quantity <= 10, "Quantity Limit Exceeded"); require (totalSupply + quantity <= maxSupply, "Max Supply Exceeded"); uint256 cost = quantity * MintPriceWei; require(msg.value >= cost, "Insufficent Funds"); for (uint i = 0; i < quantity; i++) { mintHelper(recipient); } } /** * @notice Mint tokens to msg.sender, quantity per call is limited to 10. */ function mint (uint256 quantity) public payable { mint(msg.sender, quantity); } /** * @notice Mint tokens to an array of recipient addresses, array length must be <= 10. */ function mint (address[] memory recipients) public payable whenNotPaused { uint quantity = recipients.length; require (quantity <= 10 || msg.sender == contractOwner, "Quantity Limit Exceeded"); require (totalSupply + quantity <= maxSupply, "Max Supply Exceeded"); uint256 cost = quantity * MintPriceWei; require(msg.value >= cost, "Insufficent Funds"); for (uint i = 0; i < quantity; i++) { mintHelper(recipients[i]); } } // Quest Info /** * @notice Shows where the token is in the `Action Queue`. * @dev `pending` indicates the token is in the queue. `position` is the number of preceding Actions. `revealBlock` is the block at which the action becomes eligible for reveal. */ function isPending (uint256 tokenId) public view returns (bool pending, uint position, uint revealBlock) { pending = TokenHistory[tokenId][IS_PENDING_INDEX] == 1; if (pending) { uint count = Cursor.count; uint index = Cursor.index; for (uint i = 0; i < count; i++) { Action storage action = ActionQueue[index]; if (action.tokenId == tokenId) { position = i; revealBlock = action.revealBlock; break; } index++; if(index == MAX_QUEUE) index = 0; } } } /** * @notice Fetches details used to generate token metadata. `level` => indicates numeric stage of the quest. `journeyLength` => number of revealed actions. `storySegments` => text corresponding to each reveled action. `stats` => attributes collected on the quest. `heroStatus` => number of tokens revealed through `doSomethingHeroic`. * @dev `level` will be in range [0(ngmi)..8(gmi)]. `storySegments` will have `journeyLength` entries unless `level` == 0 in which case it will have one additional element. `stats` indexes correspond to levels - 1. */ function getDetails (uint256 tokenId) public view returns (uint256 level, uint8 journeyLength, bytes[15] memory storySegments, bytes[8] memory stats, uint16 heroStatus) { require(tokenId < totalSupply, "Doesn't Exist"); uint16[16] storage tokenHistory = TokenHistory[tokenId]; journeyLength = uint8(tokenHistory[JOURNEY_LENGTH_INDEX]); level = 1; // if quest has just begun, level will be 1 uint prevLevel = 1; for (uint i = 1; i <= journeyLength; i++) { uint256 seed = uint256(keccak256(abi.encodePacked(tokenHistory[i], tokenId))); level = tokenHistory[i] & 15; if (level == 0) { (bytes memory storySegment, string memory ending) = Data.getDeath(seed, prevLevel, stats); stats[7] = storySegment; storySegments[i-1] = storySegment; storySegments[i] = bytes(ending); } else if (prevLevel == level) { storySegments[i-1] = Data.getFail(seed, level, stats); } else { (bytes memory storySegment, bytes memory stat) = Data.getAdvance(seed, level, stats); stats[level - 1] = stat; storySegments[i-1] = storySegment; } prevLevel = level; } heroStatus = HeroStatus[tokenId]; if (tokenHistory[IS_PENDING_INDEX] == 1) { stats[0] = "Pending"; } else if (level == 0) { stats[0] = "NGMI"; } else if (level == 8) { stats[0] = "GMI"; } else { stats[0] = "Questing"; } } /** * @notice Fetches the current stage of the journey in numeric terms. 0 => NGMI. 8 => GMI. * @dev `level` is always in the range [0..8]. */ function getLevel (uint256 tokenId) public view returns (uint256 level) { require(tokenId < totalSupply, "Doesn't Exist"); uint16[16] storage tokenHistory = TokenHistory[tokenId]; uint16 journeyLength = tokenHistory[JOURNEY_LENGTH_INDEX]; if (journeyLength == 0) { return 1; } else { return (tokenHistory[journeyLength] & 15); } } function getSym(int seed) internal pure returns (uint8) { if (seed & 1 == 0) return 0; if ((seed >> 1) & 1 == 0) { return 1; } return 2; } /** * @dev `cartouche` is an array of chevron positions and orientations. 0 => None, 1 => Right, 2 => Left. Data is only valid if `level` == 8. */ function getMysteriousCartouche (uint256 tokenId) public view returns (uint8 level, uint8[6] memory cartouche) { (uint256 currentLevel,uint8 journeyLength,, bytes[8] memory stats,) = getDetails(tokenId); if (currentLevel == 8) { int seed = int(uint256(keccak256(abi.encodePacked(tokenId, stats[7]))) >> 141); cartouche[0] = getSym(seed); cartouche[1] = getSym(seed >> 2); cartouche[2] = getSym(seed >> 4); cartouche[3] = getSym(seed >> 6); cartouche[4] = getSym(seed >> 8); cartouche[5] = getSym(seed >> 10); } if (journeyLength > 0) { level = uint8(currentLevel); } else { level = 1; } } // ERC-721 Metadata /** * @notice Assembles and returns the Base64 encoded token URI containing the JSON token's metadata. Assembled entirely on-chain. */ function tokenURI (uint256 tokenId) public view returns (string memory) { (uint256 level, uint8 journeyLength, bytes[15] memory storySegments, bytes[8] memory stats, uint16 heroStatus) = getDetails(tokenId); return Data.getMetadata(tokenId, level, journeyLength, storySegments, stats, heroStatus); } /** * @notice Assembles and returns the token's SVG image. Assembled entirely on-chain. */ function tokenSVG (uint256 tokenId) public view returns (string memory svg) { (uint256 level, uint8 journeyLength,, bytes[8] memory stats, uint16 heroStatus) = getDetails(tokenId); if (journeyLength > 0 && (level == 0 || level == 8)) { svg = string(Data.generateCompletionImage(tokenId, level, stats[7], heroStatus)); } else { svg = string(Data.generateProgressImage(tokenId, level)); } } // ERC-721 Base function tokenExists(uint256 tokenId) public view returns (bool) { return (tokenId < totalSupply); } function ownerOf(uint256 tokenId) public view returns (address) { require(tokenExists(tokenId), "ERC721: Nonexistent token"); return Owners[tokenId]; } function balanceOf(address owner) public view returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return TokensByOwner[owner].length; } function supportsInterface(bytes4 interfaceId) public pure returns (bool) { return interfaceId == type(IERC165).interfaceId || interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || interfaceId == type(IERC721Enumerable).interfaceId; } function _approve(address to, uint256 tokenId) internal { TokenApprovals[tokenId] = to; emit Approval(ownerOf(tokenId), to, tokenId); } 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" ); _approve(to, tokenId); } function getApproved(uint256 tokenId) public view returns (address) { require(tokenId < totalSupply, "ERC721: approved query for nonexistent token"); return TokenApprovals[tokenId]; } function isApprovedForAll(address owner, address operator) public view returns (bool) { return OperatorApprovals[owner][operator]; } function setApprovalForAll( address operator, bool approved ) external virtual { require(msg.sender != operator, "ERC721: approve to caller"); OperatorApprovals[msg.sender][operator] = approved; emit ApprovalForAll(msg.sender, operator, approved); } function isContract(address account) internal view returns (bool) { uint256 size; assembly { size := extcodesize(account) } return size > 0; } function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (isContract(to)) { try IERC721Receiver(to).onERC721Received(msg.sender, 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; } } function _transfer( address from, address to, uint256 tokenId ) private whenNotPaused { require(ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _approve(address(0), tokenId); uint16 valueIndex = OwnerTokenIndex[tokenId]; uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = TokensByOwner[from].length - 1; if (lastIndex != toDeleteIndex) { uint256 lastTokenId = TokensByOwner[from][lastIndex]; TokensByOwner[from][toDeleteIndex] = lastTokenId; OwnerTokenIndex[lastTokenId] = valueIndex; } TokensByOwner[from].pop(); TokensByOwner[to].push(tokenId); OwnerTokenIndex[tokenId] = uint16(TokensByOwner[to].length); Owners[tokenId] = to; emit Transfer(from, to, tokenId); } function _isApprovedOrOwner(address spender, uint256 tokenId) internal view returns (bool) { require(tokenId < totalSupply, "ERC721: operator query for nonexistent token"); address owner = ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } function transferFrom( address from, address to, uint256 tokenId ) public { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } function safeTransferFrom( address from, address to, uint256 tokenId ) public { safeTransferFrom(from, to, tokenId, ""); } function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public { require(_isApprovedOrOwner(msg.sender, tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) private { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } // Enumerable function tokenByIndex(uint256 tokenId) public view returns (uint256) { require(tokenExists(tokenId), "Nonexistent Token"); return tokenId; } function tokenOfOwnerByIndex(address owner, uint256 index) public view returns (uint256) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); return TokensByOwner[owner][index]; } // Rescuers /** * @dev Rescue ERC20 assets sent directly to this contract. */ function withdrawForeignERC20(address tokenContract) public onlyOwner { IERC20 token = IERC20(tokenContract); token.transfer(contractOwner, token.balanceOf(address(this))); } /** * @dev Rescue ERC721 assets sent directly to this contract. */ function withdrawForeignERC721(address tokenContract, uint256 tokenId) public onlyOwner { IERC721(tokenContract).safeTransferFrom(address(this), contractOwner, tokenId); } } // 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 // 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 (last updated v4.5.0) (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); /** * @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); }
* @dev `count` is the current length of the queue. `index` is the offset to the first queue item./
struct QueueCursor { uint16 index; uint16 count; } QueueCursor public Cursor = QueueCursor(0,0);
10,334,655
[ 1, 68, 1883, 68, 353, 326, 783, 769, 434, 326, 2389, 18, 1375, 1615, 68, 353, 326, 1384, 358, 326, 1122, 2389, 761, 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 ]
[ 1, 1, 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 ]
[ 1, 565, 1958, 7530, 6688, 288, 203, 3639, 2254, 2313, 770, 31, 203, 3639, 2254, 2313, 1056, 31, 203, 565, 289, 203, 203, 565, 7530, 6688, 1071, 13949, 273, 7530, 6688, 12, 20, 16, 20, 1769, 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 ]
./partial_match/1/0x0B9E0baEaE6A65209dBEd214cc23A9a2789F837A/sources/Tetraguard.sol
1e4 is required to scale WBTC, since it uses a fewer decimals than Eth.
PriceOfBaseWBTC = 1e4 * msg.value / WBTCtoETH;
11,008,281
[ 1, 21, 73, 24, 353, 1931, 358, 3159, 678, 38, 15988, 16, 3241, 518, 4692, 279, 27886, 15105, 2353, 512, 451, 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 ]
[ 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, 0 ]
[ 1, 3639, 20137, 951, 2171, 59, 38, 15988, 273, 404, 73, 24, 380, 1234, 18, 1132, 342, 678, 38, 15988, 869, 1584, 44, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "./openzeppelin/token/ERC721/extensions/ERC721EnumerableUpgradeable.sol"; import "./openzeppelin/access/OwnableUpgradeable.sol"; import "./openzeppelin/security/PausableUpgradeable.sol"; import "./abstract/Generator.sol"; import "./abstract/Whitelist.sol"; import "./interface/ISerum.sol"; import "./interface/IMetadata.sol"; import "./interface/IBlueprint.sol"; error NotWhitelisted(address _account); error InvalidMintAmount(uint256 _amount); error LimitExceeded(address _account); error SoldOut(); error GenerationLimit(uint256 _generation); error NotEnoughEther(uint256 _given, uint256 _expected); error InvalidBurnLength(uint256 _given, uint256 _expected); error BurnNotOwned(address _sender, uint256 _tokenId); error InvalidBurnGeneration(uint256 _given, uint256 _expected); error BlueprintNotReady(); error EarlyMintIsEnabled(); error EarlyMintNotEnabled(); // LabGame V2.0 contract LabGame is ERC721EnumerableUpgradeable, OwnableUpgradeable, PausableUpgradeable, Generator, Whitelist { uint256 constant GEN0_PRICE = 0 ether; // @since V2.0 Free mint uint256 constant GEN1_PRICE = 5_000 ether; uint256 constant GEN2_PRICE = 12_500 ether; uint256 constant GEN3_PRICE = 45_000 ether; uint256 constant GEN0_MAX = 1_111; uint256 constant GEN1_MAX = 2_222; uint256 constant GEN2_MAX = 3_333; uint256 constant GEN3_MAX = 4_444; uint256 constant WHITELIST_MINT_LIMIT = 2; uint256 constant PUBLIC_MINT_LIMIT = 5; uint256 constant EXTRA_MINT_LIMIT = 20; uint256 constant MAX_TRAITS = 16; uint256 constant TYPE_OFFSET = 9; mapping(uint256 => uint256) tokens; mapping(address => uint256) whitelistMints; mapping(address => uint256) publicMints; uint256 tokenOffset; ISerum public serum; IMetadata public metadata; IBlueprint public blueprint; uint8[][MAX_TRAITS] rarities; uint8[][MAX_TRAITS] aliases; bool public earlyMintEnabled; // @since V2.0 mapping(address => bool) public extraMintAccounts; /** * LabGame constructor * @param _name ERC721 name * @param _symbol ERC721 symbol * @param _serum Serum contract address * @param _metadata Metadata contract address * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function initialize( string memory _name, string memory _symbol, address _serum, address _metadata, address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) public initializer { __ERC721_init(_name, _symbol); __Ownable_init(); __Pausable_init(); __Generator_init(_vrfCoordinator, _keyHash, _subscriptionId, _callbackGasLimit); __Whitelist_init(); serum = ISerum(_serum); metadata = IMetadata(_metadata); // Setup rarity and alias tables for token traits rarities[0] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[0] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[1] = [89, 236, 255, 44, 179, 249, 134]; aliases[1] = [2, 2, 0, 1, 5, 2, 5]; rarities[2] = [50, 73, 96, 119, 142, 164, 187, 210, 233, 255, 28]; aliases[2] = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0]; rarities[3] = [255, 128, 255, 192, 128, 192, 255, 255, 255, 64, 255, 255, 64, 255, 128, 255, 128, 128, 255, 128, 255, 255, 128, 255, 255]; aliases[3] = [0, 6, 0, 24, 7, 24, 0, 0, 0, 3, 0, 0, 5, 0, 8, 0, 11, 15, 0, 18, 0, 0, 20, 0, 0]; rarities[4] = [199, 209, 133, 255, 209, 209, 255, 133, 255, 133, 199, 255, 199, 66, 66, 199, 255, 133, 255, 255, 66, 255, 255, 66, 250, 240]; aliases[4] = [22, 24, 8, 0, 24, 25, 0, 11, 0, 16, 24, 0, 25, 25, 1, 22, 0, 19, 0, 0, 4, 0, 0, 5, 8, 22]; rarities[5] = [255, 204, 255, 204, 40, 235, 204, 204, 235, 204, 204, 40, 204, 204, 204, 204]; aliases[5] = [0, 5, 0, 8, 0, 0, 5, 8, 2, 5, 8, 2, 5, 8, 5, 8]; rarities[6] = [158, 254, 220, 220, 158, 158, 220, 220, 220, 220, 158, 158, 238, 79, 158, 238, 79, 220, 220, 238, 158, 220, 245, 245, 245, 253, 158, 255, 253, 158, 253]; aliases[6] = [2, 27, 22, 23, 3, 6, 24, 25, 28, 30, 7, 8, 25, 1, 9, 28, 27, 22, 23, 30, 17, 24, 25, 28, 30, 1, 18, 0, 27, 21, 1]; rarities[7] = [255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255]; aliases[7] = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]; rarities[8] = [112, 112, 160, 160, 208, 64, 64, 208, 255, 255]; aliases[8] = [2, 3, 4, 7, 8, 0, 1, 9, 0, 0]; rarities[9] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[9] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[10] = [235, 250, 46, 30, 255, 76]; aliases[10] = [4, 4, 1, 0, 0, 4]; rarities[11] = [153, 204, 255, 102]; aliases[11] = [1, 2, 0, 0]; rarities[12] = [81, 138, 133, 30, 184, 189, 189, 138, 235, 240, 240, 255]; aliases[12] = [2, 5, 4, 0, 8, 9, 10, 6, 11, 11, 11, 0]; rarities[13] = [255, 255, 255, 255, 255, 255, 255, 255]; aliases[13] = [0, 0, 0, 0, 0, 0, 0, 0]; rarities[14] = [76, 192, 255]; aliases[14] = [2, 2, 0]; rarities[15] = [236, 236, 224, 224, 249, 249, 255]; aliases[15] = [4, 5, 0, 1, 6, 6, 0]; } // -- EXTERNAL -- // @since V2.0 - Whitelist mint no longer needed /** * Mint scientists & mutants * @param _amount Number of tokens to mint * @param _burnIds Token Ids to burn as payment (for gen 1 & 2) */ function mint(uint256 _amount, uint256[] calldata _burnIds) external payable whenNotPaused { if (earlyMintEnabled) revert EarlyMintIsEnabled(); uint256 publicMintCount = publicMints[_msgSender()]; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > PUBLIC_MINT_LIMIT) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); if (id >= GEN3_MAX) revert SoldOut(); uint256 max = id + _amount; uint256 generation; // Generation 0 if (id < GEN0_MAX) { if (max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); uint256 whitelistMintCount = whitelistMints[_msgSender()]; if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > PUBLIC_MINT_LIMIT) || (publicMintCount + _amount > PUBLIC_MINT_LIMIT) ) revert LimitExceeded(_msgSender()); // Generation 1 } else if (id < GEN1_MAX) { if (max > GEN1_MAX) revert GenerationLimit(1); serum.burn(_msgSender(), _amount * GEN1_PRICE); generation = 1; // Generation 2 } else if (id < GEN2_MAX) { if (max > GEN2_MAX) revert GenerationLimit(2); serum.burn(_msgSender(), _amount * GEN2_PRICE); generation = 2; // Generation 3 } else if (id < GEN3_MAX) { if (address(blueprint) == address(0)) revert BlueprintNotReady(); if (max > GEN3_MAX) revert GenerationLimit(3); serum.burn(_msgSender(), _amount * GEN3_PRICE); generation = 3; } // Burn tokens to mint gen 1, 2, and 3 uint256 burnLength = _burnIds.length; if (generation != 0) { if (burnLength != _amount) revert InvalidBurnLength(burnLength, _amount); for (uint256 i; i < burnLength; i++) { // Verify token to be burned if (_msgSender() != ownerOf(_burnIds[i])) revert BurnNotOwned(_msgSender(), _burnIds[i]); if (tokens[_burnIds[i]] & 3 != generation - 1) revert InvalidBurnGeneration(tokens[_burnIds[i]] & 3, generation - 1); _burn(_burnIds[i]); } // Add burned tokens to id offset tokenOffset += burnLength; // Generation 0 no burn needed } else { if (burnLength != 0) revert InvalidBurnLength(burnLength, 0); } publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { uint256 seed = _random(i); _revealToken(i, seed); } } function earlyMint(uint256 _amount) external whenNotPaused { if (!earlyMintEnabled) revert EarlyMintNotEnabled(); // Only when early mint enabled uint256 whitelistMintCount = whitelistMints[_msgSender()]; uint256 publicMintCount = publicMints[_msgSender()]; bool hasExtraMints = extraMintAccounts[_msgSender()]; if (whitelistMintCount == 0 && publicMintCount == 0 && hasExtraMints == false) revert EarlyMintIsEnabled(); uint256 limit = hasExtraMints ? EXTRA_MINT_LIMIT : PUBLIC_MINT_LIMIT; // Verify amount // @since V2.0 Transaction limit of 10, account limit of 20 if (_amount == 0 || _amount > limit) revert InvalidMintAmount(_amount); // Verify generation and price uint256 id = totalMinted(); uint256 max = id + _amount; if (id >= GEN0_MAX || max > GEN0_MAX) revert GenerationLimit(0); // @since V2.0 - No ether required to mint // Account limit of PUBLIC_MINT_LIMIT not including whitelist mints // @since V2.0 - Fix underflow bug uint256 currentBalance = balanceOf(_msgSender()); if ( (currentBalance >= whitelistMintCount && currentBalance - whitelistMintCount + _amount > limit) || (publicMintCount + _amount > limit) ) revert LimitExceeded(_msgSender()); publicMints[_msgSender()] = publicMintCount + _amount; // Request token mint // @since V2.0 - Single transaction mint // Token id to mint in [id + 1, id + _amount] max++; for (uint i = id + 1; i < max; i++) { _revealToken(i, _random(i)); } } /** * Reveal pending mints */ function reveal() external whenNotPaused { (, uint256 count) = pendingOf(_msgSender()); _reveal(_msgSender()); // Tokens minted, update offset tokenOffset -= count; } /** * Get the metadata uri for a token * @param _tokenId Token ID to query * @return Token metadata json URI */ function tokenURI(uint256 _tokenId) public view override returns (string memory) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return metadata.tokenURI(_tokenId); } /** * Get the total number of minted tokens * @return Total number of minted tokens */ function totalMinted() public view returns (uint256) { return totalSupply() + tokenOffset; } /** * Get the data of a token * @param _tokenId Token ID to query * @return Token structure */ function getToken(uint256 _tokenId) external view returns (uint256) { if (!_exists(_tokenId)) revert ERC721_QueryForNonexistentToken(_tokenId); return tokens[_tokenId]; } // -- INTERNAL -- function _beforeTokenTransfer(address _from, address _to, uint256 _tokenId) internal override { super._beforeTokenTransfer(_from, _to, _tokenId); // Update serum claim on transfer and burn if (_from != address(0)) serum.updateClaim(_from, _tokenId); } /** * Generate and mint pending token using random seed * @param _tokenId Token ID to reveal * @param _seed Random seed */ function _revealToken(uint256 _tokenId, uint256 _seed) internal override { // Calculate generation of token uint256 token; if (_tokenId <= GEN0_MAX) {} else if (_tokenId <= GEN1_MAX) token = 1; else if (_tokenId <= GEN2_MAX) token = 2; else if (_tokenId <= GEN3_MAX) token = 3; // Select scientist or mutant // @since V2.0 Mint mutants at 2% token |= (((_seed & 0xFFFF) % 100) < 2) ? 128 : 0; // Loop over tokens traits (9 scientist, 8 mutant) (uint256 start, uint256 count) = (token & 128 != 0) ? (TYPE_OFFSET, MAX_TRAITS - TYPE_OFFSET) : (0, TYPE_OFFSET); for (uint256 i; i < count; i++) { _seed >>= 16; token |= _selectTrait(_seed, start + i) << (8 * i + 8); } // Save traits tokens[_tokenId] = token; // Mint token _safeMint(_msgSender(), _tokenId); // Setup serum claim for token serum.initializeClaim(_tokenId); // Mint blueprint to gen3 tokens if (token & 3 == 3) blueprint.mint(_msgSender(), _seed >> 16); } /** * Select a trait from the alias tables using a random seed (16 bit) * @param _seed Random seed * @param _trait Trait to select * @return Index of the selected trait */ function _selectTrait(uint256 _seed, uint256 _trait) internal view returns (uint256) { uint256 i = (_seed & 0xFF) % rarities[_trait].length; return (((_seed >> 8) & 0xFF) < rarities[_trait][i]) ? i : aliases[_trait][i]; } /** * Generate a psuedo-random number * @param _seed Seed for the RNG * @return Random 256 bit number */ function _random(uint256 _seed) internal view returns (uint256) { return uint256(keccak256(abi.encodePacked( tx.origin, blockhash(block.number - 1), block.timestamp, _seed ))); } // -- OWNER -- /** * Enable/disable holder only early mint */ function setEarlyMintEnabled(bool _earlyMintEnabled) external onlyOwner { earlyMintEnabled = _earlyMintEnabled; } /** * Add account to the early mint * @param _accounts Account to add */ function addEarlyMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) whitelistMints[_accounts[i]]++; } /** * Add account to the extra mint list * @param _accounts Account to add */ function addExtraMintAccounts(address[] calldata _accounts) external onlyOwner { for (uint256 i; i < _accounts.length; i++) extraMintAccounts[_accounts[i]] = true; } /** * Pause the contract */ function pause() external onlyOwner { _pause(); } /** * Unpause the contract */ function unpause() external onlyOwner { _unpause(); } /** * Set blueprint contract * @param _blueprint Address of the blueprint contract */ function setBlueprint(address _blueprint) external onlyOwner { blueprint = IBlueprint(_blueprint); } /** * Withdraw funds to owner */ function withdraw() external onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "../ERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721EnumerableUpgradeable.sol"; import "../../../proxy/utils/Initializable.sol"; /** * @dev This implements an optional extension of {ERC721} defined in the EIP that adds * enumerability of all the token ids in the contract as well as all token ids owned by each * account. */ error ERC721Enumerable_IndexOutOfBounds(uint256 index, uint256 max); abstract contract ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { if (index >= ERC721Upgradeable.balanceOf(owner)) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721Upgradeable.balanceOf(owner)); return _ownedTokens[owner][index]; } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _allTokens.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { if (index >= ERC721EnumerableUpgradeable.totalSupply()) revert ERC721Enumerable_IndexOutOfBounds(index, ERC721EnumerableUpgradeable.totalSupply()); return _allTokens[index]; } /** * @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` cannot be the zero address. * - `to` cannot be the zero address. * * 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 override { super._beforeTokenTransfer(from, to, tokenId); 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); } } /** * @dev Private function to add a token to this extension's ownership-tracking data structures. * @param to address representing the new owner of the given token ID * @param tokenId uint256 ID of the token to be added to the tokens list of the given address */ function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ 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 = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary 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 } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ 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 - 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 delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @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[46] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; 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. */ error Ownable_CallerNotOwner(address caller, address owner); error Ownable_NewOwnerZeroAddress(); 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() { if (owner() != _msgSender()) revert Ownable_CallerNotOwner(_msgSender(), 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 { if (newOwner == address(0)) revert Ownable_NewOwnerZeroAddress(); _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) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; 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. */ error Pausable_Paused(); error Pausable_NotPaused(); 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() { if (paused()) revert Pausable_Paused(); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { if (!paused()) revert Pausable_NotPaused(); _; } /** * @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 pragma solidity ^0.8.13; import "./VRFConsumerBaseV2Upgradable.sol"; import "@chainlink/contracts/src/v0.8/interfaces/VRFCoordinatorV2Interface.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error AccountHasPendingMint(address _account); error AcountHasNoPendingMint(address _account); error InvalidAccount(); error InvalidRequestBase(); error InvalidRequestCount(); error RevealNotReady(); abstract contract Generator is VRFConsumerBaseV2Upgradable { VRFCoordinatorV2Interface internal vrfCoordinator; bytes32 internal keyHash; uint64 internal subscriptionId; uint32 internal callbackGasLimit; struct Mint { uint64 base; uint32 count; uint256[] random; } mapping(uint256 => address) internal mintRequests; mapping(address => Mint) internal pendingMints; event Requested(address indexed _account, uint256 _baseId, uint256 _count); event Pending(address indexed _account, uint256 _baseId, uint256 _count); event Revealed(address indexed _account, uint256 _tokenId); /** * Constructor to initialize VRF * @param _vrfCoordinator VRF Coordinator address * @param _keyHash Gas lane key hash * @param _subscriptionId VRF subscription id * @param _callbackGasLimit VRF callback gas limit */ function __Generator_init( address _vrfCoordinator, bytes32 _keyHash, uint64 _subscriptionId, uint32 _callbackGasLimit ) internal onlyInitializing { __VRFConsumerBaseV2_init(_vrfCoordinator); vrfCoordinator = VRFCoordinatorV2Interface(_vrfCoordinator); keyHash = _keyHash; subscriptionId = _subscriptionId; callbackGasLimit = _callbackGasLimit; } // -- PUBLIC -- modifier zeroPending(address _account) { if (pendingMints[_account].base != 0) revert AccountHasPendingMint(_account); _; } /** * Get the current pending mints of a user account * @param _account Address of account to query * @return Pending token base ID, amount of pending tokens */ function pendingOf(address _account) public view returns (uint256, uint256) { return (pendingMints[_account].base, pendingMints[_account].random.length); } // -- INTERNAL -- /** * Update pending mint with response from VRF * @param _requestId Request ID that was fulfilled * @param _randomWords Received random numbers */ function fulfillRandomWords(uint256 _requestId, uint256[] memory _randomWords) internal virtual override { // Pop request address account = mintRequests[_requestId]; delete mintRequests[_requestId]; // Update pending mints with received random numbers pendingMints[account].random = _randomWords; // Ready to reveal emit Pending(account, pendingMints[account].base, _randomWords.length); } /** * Setup a pending mint and request numbers from VRF * @param _account Account to request for * @param _base Base token ID * @param _count Number of tokens */ function _request(address _account, uint256 _base, uint256 _count) internal zeroPending(_account) { if (_account == address(0)) revert InvalidAccount(); if (_base == 0) revert InvalidRequestBase(); if (_count == 0) revert InvalidRequestCount(); // Request random numbers for tokens, save request id to account uint256 requestId = vrfCoordinator.requestRandomWords( keyHash, subscriptionId, 3, callbackGasLimit, uint32(_count) ); mintRequests[requestId] = _account; // Initialize mint request with id and count pendingMints[_account].base = uint64(_base); pendingMints[_account].count = uint32(_count); // Mint requested emit Requested(_account, _base, _count); } /** * Reveal pending tokens with received random numbers * @param _account Account to reveal for */ function _reveal(address _account) internal { if (_account == address(0)) revert InvalidAccount(); Mint memory mint = pendingMints[_account]; if (mint.base == 0) revert AcountHasNoPendingMint(_account); if (mint.random.length == 0) revert RevealNotReady(); delete pendingMints[_account]; // Generate all tokens for (uint256 i; i < mint.count; i++) { _revealToken(mint.base + i, mint.random[i]); emit Revealed(_account, mint.base + i); } } /** * Abstract function called on each token when revealing * @param _tokenId Token ID to reveal * @param _seed Random number from VRF for the token */ function _revealToken(uint256 _tokenId, uint256 _seed) internal virtual; /** * Set the VRF key hash * @param _keyHash New keyHash */ function _setKeyHash(bytes32 _keyHash) internal { keyHash = _keyHash; } /** * Set the VRF subscription ID * @param _subscriptionId New subscriptionId */ function _setSubscriptionId(uint64 _subscriptionId) internal { subscriptionId = _subscriptionId; } /** * Set the VRF callback gas limit * @param _callbackGasLimit New callbackGasLimit */ function _setCallbackGasLimit(uint32 _callbackGasLimit) internal { callbackGasLimit = _callbackGasLimit; } /** * @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[45] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/utils/cryptography/MerkleProofUpgradeable.sol"; import "../openzeppelin/proxy/utils/Initializable.sol"; error WhitelistIsEnabled(); error WhitelistNotEnabled(); abstract contract Whitelist is Initializable { bytes32 internal merkleRoot; event WhitelistEnabled(); event WhitelistDisabled(); /** Whitelist contstructor (empty) */ function __Whitelist_init() internal onlyInitializing {} function whitelisted() public view returns (bool) { return merkleRoot != bytes32(0); } modifier whenWhitelisted { if (!whitelisted()) revert WhitelistNotEnabled(); _; } modifier whenNotWhitelisted { if (whitelisted()) revert WhitelistIsEnabled(); _; } /** * Checks if an account is whitelisted using the given proof * @param _account Account to verify * @param _merkleProof Proof to verify the account is in the merkle tree */ function _whitelisted(address _account, bytes32[] calldata _merkleProof) internal view returns (bool) { return MerkleProofUpgradeable.verify(_merkleProof, merkleRoot, keccak256(abi.encodePacked(_account))); } /** * Enable the whitelist and set the merkle tree root * @param _merkleRoot Whitelist merkle tree root hash */ function _enableWhitelist(bytes32 _merkleRoot) internal { if (whitelisted()) revert WhitelistIsEnabled(); merkleRoot = _merkleRoot; emit WhitelistEnabled(); } /** * Disable the whitelist and clear the root hash */ function _disableWhitelist() internal { if (!whitelisted()) revert WhitelistNotEnabled(); delete merkleRoot; emit WhitelistDisabled(); } /** * @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 pragma solidity ^0.8.13; import "./IClaimable.sol"; interface ISerum is IClaimable { function mint(address _to, uint256 _amount) external; function burn(address _from, uint256 _amount) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IMetadata { function tokenURI(uint256 _tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; interface IBlueprint { function mint(address _account, uint256 _seed) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721ReceiverUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/extensions/IERC721MetadataUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/StringsUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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}. */ error ERC721_QueryOnZeroAddress(); error ERC721_QueryForNonexistentToken(uint256 tokenId); error ERC721Metadata_QueryForNonexistentToken(uint256 tokenId); error ERC721_ApprovalToCurrentOwner(address owner); error ERC721_CallerNotOwnerOrApproved(address caller); error ERC721_TransferToNonReceiverImplementer(address to, uint256 tokenId); error ERC721_MintToZeroAddress(uint256 tokenId); error ERC721_TokenAlreadyMinted(uint256 tokenId); error ERC721_TransferFromIncorrectOwner(address from, address expected); error ERC721_TransferToZeroAddress(uint256 tokenId); error ERC721_ApprovalToCaller(address caller); contract ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable 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. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { if (owner == address(0)) revert ERC721_QueryOnZeroAddress(); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; if (owner == address(0)) revert ERC721_QueryForNonexistentToken(tokenId); 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) { if (!_exists(tokenId)) revert ERC721Metadata_QueryForNonexistentToken(tokenId); 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 = ERC721Upgradeable.ownerOf(tokenId); if (to == owner) revert ERC721_ApprovalToCurrentOwner(to); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); 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 if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _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 { if (!_isApprovedOrOwner(_msgSender(), tokenId)) revert ERC721_CallerNotOwnerOrApproved(_msgSender()); _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); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @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) { if (!_exists(tokenId)) revert ERC721_QueryForNonexistentToken(tokenId); address owner = ERC721Upgradeable.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); if (!_checkOnERC721Received(address(0), to, tokenId, _data)) revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } /** * @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 { if (to == address(0)) revert ERC721_MintToZeroAddress(tokenId); if (_exists(tokenId)) revert ERC721_TokenAlreadyMinted(tokenId); _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 = ERC721Upgradeable.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 { if (ERC721Upgradeable.ownerOf(tokenId) != from) revert ERC721_TransferFromIncorrectOwner(from, ERC721Upgradeable.ownerOf(tokenId)); if (to == address(0)) revert ERC721_TransferToZeroAddress(tokenId); _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(ERC721Upgradeable.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 { if (owner == operator) revert ERC721_ApprovalToCaller(owner); _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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert ERC721_TransferToNonReceiverImplementer(to, tokenId); } 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 {} /** * @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[44] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @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); /** * @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 (last updated v4.5.0) (proxy/utils/Initializable.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; 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 {} * ``` * ==== */ error Initializable_AlreadyInitialized(); error Initializable_NotInitializing(); 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. if(_initializing ? !_isConstructor() : _initialized) revert Initializable_AlreadyInitialized(); 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() { if (!_initializing) revert Initializable_NotInitializing(); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // 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 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 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721Upgradeable.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @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) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; /** * @dev Collection of functions related to the address type */ error Address_InsufficientBalance(uint256 balance, uint256 amount); error Address_UnableToSendValue(address recipient, uint256 amount); error Address_CallToNonContract(address target); error Address_StaticCallToNonContract(address target); 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 { if (address(this).balance < amount) revert Address_InsufficientBalance(address(this).balance, amount); (bool success, ) = recipient.call{value: amount}(""); if (!success) revert Address_UnableToSendValue(recipient, amount); } /** * @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) { if (address(this).balance < value) revert Address_InsufficientBalance(address(this).balance, value); if (!isContract(target)) revert Address_CallToNonContract(target); (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) { if (!isContract(target)) revert Address_StaticCallToNonContract(target); (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/Context.sol) // Modified to use custom errors instead of require strings pragma solidity ^0.8.13; 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 v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { 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) // Modified to use custom errors instead of require strings pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/utils/introspection/IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @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 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 pragma solidity ^0.8.13; import "../openzeppelin/proxy/utils/Initializable.sol"; // Modified to use OpenZeppelin upgradeables /** **************************************************************************** * @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. It ensures 2 things: * @dev 1. The fulfillment came from the VRFCoordinator * @dev 2. The consumer contract implements fulfillRandomWords. * ***************************************************************************** * @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 constructor(<other arguments>, address _vrfCoordinator, address _link) * @dev VRFConsumerBase(_vrfCoordinator) 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). Create subscription, fund it * @dev and your consumer contract as a consumer of it (see VRFCoordinatorInterface * @dev subscription management functions). * @dev Call requestRandomWords(keyHash, subId, minimumRequestConfirmations, * @dev callbackGasLimit, numWords), * @dev see (VRFCoordinatorInterface for a description of the arguments). * * @dev Once the VRFCoordinator has received and validated the oracle's response * @dev to your request, it will call your contract's fulfillRandomWords method. * * @dev The randomness argument to fulfillRandomWords is a set of random words * @dev generated from your requestId and the blockHash of the request. * * @dev If your contract could have concurrent requests open, you can use the * @dev requestId returned from requestRandomWords to track which response is associated * @dev with which randomness request. * @dev 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. * * ***************************************************************************** * @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 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. It is for this reason that * @dev that you can signal to an oracle you'd like them to wait longer before * @dev responding to the request (however this is not enforced in the contract * @dev and so remains effective only in the case of unmodified oracle software). */ abstract contract VRFConsumerBaseV2Upgradable is Initializable { error OnlyCoordinatorCanFulfill(address have, address want); address private vrfCoordinator; /** * @param _vrfCoordinator address of VRFCoordinator contract */ function __VRFConsumerBaseV2_init(address _vrfCoordinator) internal onlyInitializing { vrfCoordinator = _vrfCoordinator; } /** * @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 VRFConsumerBaseV2 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 randomWords the VRF output expanded to the requested number of words */ function fulfillRandomWords(uint256 requestId, uint256[] memory randomWords) internal virtual; // rawFulfillRandomness is called by VRFCoordinator when it receives a valid VRF // proof. rawFulfillRandomness then calls fulfillRandomness, after validating // the origin of the call function rawFulfillRandomWords(uint256 requestId, uint256[] memory randomWords) external { if (msg.sender != vrfCoordinator) { revert OnlyCoordinatorCanFulfill(msg.sender, vrfCoordinator); } fulfillRandomWords(requestId, randomWords); } /** * @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 pragma solidity ^0.8.0; interface VRFCoordinatorV2Interface { /** * @notice Get configuration relevant for making requests * @return minimumRequestConfirmations global min for request confirmations * @return maxGasLimit global max for request gas limit * @return s_provingKeyHashes list of registered key hashes */ function getRequestConfig() external view returns ( uint16, uint32, bytes32[] memory ); /** * @notice Request a set of random words. * @param keyHash - Corresponds to a particular oracle job which uses * that key for generating the VRF proof. Different keyHash's have different gas price * ceilings, so you can select a specific one to bound your maximum per request cost. * @param subId - The ID of the VRF subscription. Must be funded * with the minimum subscription balance required for the selected keyHash. * @param minimumRequestConfirmations - How many blocks you'd like the * oracle to wait before responding to the request. See SECURITY CONSIDERATIONS * for why you may want to request more. The acceptable range is * [minimumRequestBlockConfirmations, 200]. * @param callbackGasLimit - How much gas you'd like to receive in your * fulfillRandomWords callback. Note that gasleft() inside fulfillRandomWords * may be slightly less than this amount because of gas used calling the function * (argument decoding etc.), so you may need to request slightly more than you expect * to have inside fulfillRandomWords. The acceptable range is * [0, maxGasLimit] * @param numWords - The number of uint256 random values you'd like to receive * in your fulfillRandomWords callback. Note these numbers are expanded in a * secure way by the VRFCoordinator from a single random value supplied by the oracle. * @return requestId - A unique identifier of the request. Can be used to match * a request to a response in fulfillRandomWords. */ function requestRandomWords( bytes32 keyHash, uint64 subId, uint16 minimumRequestConfirmations, uint32 callbackGasLimit, uint32 numWords ) external returns (uint256 requestId); /** * @notice Create a VRF subscription. * @return subId - A unique subscription id. * @dev You can manage the consumer set dynamically with addConsumer/removeConsumer. * @dev Note to fund the subscription, use transferAndCall. For example * @dev LINKTOKEN.transferAndCall( * @dev address(COORDINATOR), * @dev amount, * @dev abi.encode(subId)); */ function createSubscription() external returns (uint64 subId); /** * @notice Get a VRF subscription. * @param subId - ID of the subscription * @return balance - LINK balance of the subscription in juels. * @return reqCount - number of requests for this subscription, determines fee tier. * @return owner - owner of the subscription. * @return consumers - list of consumer address which are able to use this subscription. */ function getSubscription(uint64 subId) external view returns ( uint96 balance, uint64 reqCount, address owner, address[] memory consumers ); /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @param newOwner - proposed new owner of the subscription */ function requestSubscriptionOwnerTransfer(uint64 subId, address newOwner) external; /** * @notice Request subscription owner transfer. * @param subId - ID of the subscription * @dev will revert if original owner of subId has * not requested that msg.sender become the new owner. */ function acceptSubscriptionOwnerTransfer(uint64 subId) external; /** * @notice Add a consumer to a VRF subscription. * @param subId - ID of the subscription * @param consumer - New consumer which can use the subscription */ function addConsumer(uint64 subId, address consumer) external; /** * @notice Remove a consumer from a VRF subscription. * @param subId - ID of the subscription * @param consumer - Consumer to remove from the subscription */ function removeConsumer(uint64 subId, address consumer) external; /** * @notice Cancel a subscription * @param subId - ID of the subscription * @param to - Where to send the remaining LINK to */ function cancelSubscription(uint64 subId, address to) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/MerkleProof.sol) 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 MerkleProofUpgradeable { /** * @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) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { 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 = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.13; error NoClaimAvailable(address _account); interface IClaimable { function claim() external; function pendingClaim(address _account) external view returns (uint256); function initializeClaim(uint256 _tokenId) external; function updateClaim(address _account, uint256 _tokenId) external; event Claimed(address indexed _account, uint256 _amount); event Updated(address indexed _account, uint256 indexed _tokenId); }
* Enable the whitelist and set the merkle tree root @param _merkleRoot Whitelist merkle tree root hash/
function _enableWhitelist(bytes32 _merkleRoot) internal { if (whitelisted()) revert WhitelistIsEnabled(); merkleRoot = _merkleRoot; emit WhitelistEnabled(); }
6,147,355
[ 1, 8317, 326, 10734, 471, 444, 326, 30235, 2151, 1365, 225, 389, 6592, 15609, 2375, 3497, 7523, 30235, 2151, 1365, 1651, 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 ]
[ 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, 0 ]
[ 1, 202, 915, 389, 7589, 18927, 12, 3890, 1578, 389, 6592, 15609, 2375, 13, 2713, 288, 203, 202, 202, 430, 261, 20409, 329, 10756, 15226, 3497, 7523, 2520, 1526, 5621, 203, 202, 202, 6592, 15609, 2375, 273, 389, 6592, 15609, 2375, 31, 203, 202, 202, 18356, 3497, 7523, 1526, 5621, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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: GPL-3.0-or-later pragma solidity ^0.8.11; import './ArrayInterface.sol'; /// @notice "normal" array implementation used as base case for comparison /// @dev light wrapper around uint8[] array /// @author Adapted by @devtooligan from https://solidity-by-example.org/array/ contract NormalArray is ArrayInterface { /* Storage *********************************************************************************************/ uint8[] public arr; /* Main functions *********************************************************************************************/ function getArr() public view returns(uint8[] memory) { return arr; } /// @return length of array function length() public view returns (uint8) { return uint8(arr.length); } /// @param index of element to return the value of /// @return value of the specified element function val(uint256 index) public view returns(uint8) { require(index < arr.length, "outtarange"); return arr[index]; } /// @param value of new element added to the end of the array function push(uint8 value) public { arr.push(value); } /// @return value of popped element function pop() public returns(uint8 value) { require(arr.length != 0, "no can"); value = arr[arr.length - 1]; arr.pop(); } /// @dev delete element and replace it with a popped element /// @param index of element to remove function remove(uint256 index) public { arr[index] = pop(); } /// @param index to update /// @param value is the new value being set function set(uint256 index, uint8 value) public { arr[index] = value; } }
@param value of new element added to the end of the array
function push(uint8 value) public { arr.push(value); }
15,806,296
[ 1, 1132, 434, 394, 930, 3096, 358, 326, 679, 434, 326, 526, 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, 445, 1817, 12, 11890, 28, 460, 13, 1071, 288, 203, 3639, 2454, 18, 6206, 12, 1132, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../interfaces/IVault.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3PMExtends.sol"; import "../storage/SmartPoolStorage.sol"; import "./UniV3Liquidity.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the Vault contract AutoLiquidity is UniV3Liquidity { using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.UintSet; using EnumerableSet for EnumerableSet.AddressSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Vault purchase and redemption token IERC20 public ioToken; //Vault contract address IVault public vault; //Underlying asset EnumerableSet.AddressSet internal underlyings; event TakeFee(SmartPoolStorage.FeeType ft, address owner, uint256 fee); /// @notice Binding vaults and subscription redemption token /// @dev Only bind once and cannot be modified /// @param _vault Vault address /// @param _ioToken Subscription and redemption token function bind(address _vault, address _ioToken) external onlyGovernance { vault = IVault(_vault); ioToken = IERC20(_ioToken); } //Only allow vault contract access modifier onlyVault() { require(extAuthorize(), "!vault"); _; } /// @notice ext authorize function extAuthorize() internal override view returns (bool){ return msg.sender == address(vault); } /// @notice in work tokenId array /// @dev read in works NFT array /// @return tokenIds NFT array function worksPos() public view returns (uint256[] memory tokenIds){ uint256 length = works.length(); tokenIds = new uint256[](length); for (uint256 i = 0; i < length; i++) { tokenIds[i] = works.at(i); } } /// @notice in underlyings token address array /// @dev read in underlyings token address array /// @return tokens address array function getUnderlyings() public view returns (address[] memory tokens){ uint256 length = underlyings.length(); tokens = new address[](length); for (uint256 i = 0; i < underlyings.length(); i++) { tokens[i] = underlyings.at(i); } } /// @notice Set the underlying asset token address /// @dev Only allow the governance identity to set the underlying asset token address /// @param ts The underlying asset token address array to be added function setUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (!underlyings.contains(ts[i])) { underlyings.add(ts[i]); } } } /// @notice Delete the underlying asset token address /// @dev Only allow the governance identity to delete the underlying asset token address /// @param ts The underlying asset token address array to be deleted function removeUnderlyings(address[] memory ts) public onlyGovernance { for (uint256 i = 0; i < ts.length; i++) { if (underlyings.contains(ts[i])) { underlyings.remove(ts[i]); } } } /// @notice swap after handle /// @param tokenOut token address /// @param amountOut token amount function swapAfter( address tokenOut, uint256 amountOut) internal override { uint256 fee = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amountOut); if (tokenOut != address(ioToken) && fee > 0) { fee = swapRoute.exactInput(tokenOut, address(ioToken), fee, address(this), 0); } if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice collect after handle /// @param token0 token address /// @param token1 token address /// @param amount0 token amount /// @param amount1 token amount function collectAfter( address token0, address token1, uint256 amount0, uint256 amount1) internal override { uint256 fee0 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount0); uint256 fee1 = vault.calcRatioFee(SmartPoolStorage.FeeType.TURNOVER_FEE, amount1); if (token0 != address(ioToken) && fee0 > 0) { fee0 = swapRoute.exactInput(token0, address(ioToken), fee0, address(this), 0); } if (token1 != address(ioToken) && fee1 > 0) { fee1 = swapRoute.exactInput(token1, address(ioToken), fee1, address(this), 0); } uint256 fee = fee0.add(fee1); if (fee > 0) { address rewards=getRewards(); ioToken.safeTransfer(rewards, fee); emit TakeFee(SmartPoolStorage.FeeType.TURNOVER_FEE, rewards, fee); } } /// @notice Asset transfer used to upgrade the contract /// @param to address function withdrawAll(address to) external onlyGovernance { for (uint256 i = 0; i < underlyings.length(); i++) { IERC20 token = IERC20(underlyings.at(i)); uint256 balance = token.balanceOf(address(this)); if (balance > 0) { token.safeTransfer(to, balance); } } } /// @notice Withdraw asset /// @dev Only vault contract can withdraw asset /// @param to Withdraw address /// @param amount Withdraw amount /// @param scale Withdraw percentage function withdraw(address to, uint256 amount, uint256 scale) external onlyVault { uint256 surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token != address(ioToken) && balance > 0) { exactInput(token, address(ioToken), balance, 0); } } } surplusAmount = ioToken.balanceOf(address(this)); if (surplusAmount < amount) { amount = surplusAmount; } ioToken.safeTransfer(to, amount); } /// @notice Withdraw underlying asset /// @dev Only vault contract can withdraw underlying asset /// @param to Withdraw address /// @param scale Withdraw percentage function withdrawOfUnderlying(address to, uint256 scale) external onlyVault { uint256 length = underlyings.length(); uint256[] memory balances = new uint256[](length); uint256[] memory withdrawAmounts = new uint256[](length); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); balances[i] = balance; withdrawAmounts[i] = balance.mul(scale).div(1e18); } _decreaseLiquidityByScale(scale); for (uint256 i = 0; i < length; i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); uint256 decreaseAmount = balance.sub(balances[i]); uint256 addAmount = decreaseAmount.mul(scale).div(1e18); uint256 transferAmount = withdrawAmounts[i].add(addAmount); IERC20(token).safeTransfer(to, transferAmount); } } /// @notice Decrease liquidity by scale /// @dev Decrease liquidity by provided scale /// @param scale Scale of the liquidity function _decreaseLiquidityByScale(uint256 scale) internal { uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); ( , , , , , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); if (liquidity > 0) { uint256 _decreaseLiquidity = uint256(liquidity).mul(scale).div(1e18); (uint256 amount0, uint256 amount1) = decreaseLiquidity(tokenId, uint128(_decreaseLiquidity), 0, 0); collect(tokenId, uint128(amount0), uint128(amount1)); } } } /// @notice Total asset /// @dev This function calculates the net worth or AUM /// @return Total asset function assets() public view returns (uint256){ uint256 total = idleAssets(); total = total.add(liquidityAssets()); return total; } /// @notice idle asset /// @dev This function calculates idle asset /// @return idle asset function idleAssets() public view returns (uint256){ uint256 total; for (uint256 i = 0; i < underlyings.length(); i++) { address token = underlyings.at(i); uint256 balance = IERC20(token).balanceOf(address(this)); if (token == address(ioToken)) { total = total.add(balance); } else { uint256 _estimateAmountOut = estimateAmountOut(token, address(ioToken), balance); total = total.add(_estimateAmountOut); } } return total; } /// @notice at work liquidity asset /// @dev This function calculates liquidity asset /// @return liquidity asset function liquidityAssets() public view returns (uint256){ uint256 total; address ioTokenAddr = address(ioToken); uint256 length = works.length(); for (uint256 i = 0; i < length; i++) { uint256 tokenId = works.at(i); total = total.add(calcLiquidityAssets(tokenId, ioTokenAddr)); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/utils/EnumerableSet.sol"; import "../base/GovIdentity.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "../libraries/ERC20Extends.sol"; import "../libraries/UniV3SwapExtends.sol"; import "../libraries/UniV3PMExtends.sol"; pragma abicoder v2; /// @title Position Management /// @notice Provide asset operation functions, allow authorized identities to perform asset operations, and achieve the purpose of increasing the net value of the fund contract UniV3Liquidity is GovIdentity { using SafeMath for uint256; using Path for bytes; using EnumerableSet for EnumerableSet.UintSet; using UniV3SwapExtends for mapping(address => mapping(address => bytes)); //Swap route mapping(address => mapping(address => bytes)) public swapRoute; //Position list mapping(bytes32 => uint256) public history; //position mapping owner mapping(uint256 => address) public positionOwners; //available token limit mapping(address => mapping(address => uint256)) public tokenLimit; //Working positions EnumerableSet.UintSet internal works; //Swap event Swap(address sender, address fromToken, address toToken, uint256 amountIn, uint256 amountOut); //Create positoin event Mint(address sender, uint256 tokenId, uint128 liquidity); //Increase liquidity event IncreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Decrease liquidity event DecreaseLiquidity(address sender, uint256 tokenId, uint128 liquidity); //Collect asset event Collect(address sender, uint256 tokenId, uint256 amount0, uint256 amount1); //Only allow governance, strategy, ext authorize modifier onlyAssetsManager() { require( msg.sender == getGovernance() || isAdmin(msg.sender) || isStrategist(msg.sender) || extAuthorize(), "!AM"); _; } //Only position owner modifier onlyPositionManager(uint256 tokenId) { require( msg.sender == getGovernance() || isAdmin(msg.sender) || positionOwners[tokenId] == msg.sender || extAuthorize(), "!PM"); _; } /// @notice extend authorize function extAuthorize() internal virtual view returns (bool){ return false; } /// @notice swap after handle function swapAfter( address, uint256) internal virtual { } /// @notice collect after handle function collectAfter( address, address, uint256, uint256) internal virtual { } /// @notice Check current position /// @dev Check the current UniV3 position by pool token ID. /// @param pool liquidity pool /// @param tickLower Tick lower bound /// @param tickUpper Tick upper bound /// @return atWork Position status /// @return has Check if the position ID exist /// @return tokenId Position ID function checkPos( address pool, int24 tickLower, int24 tickUpper ) public view returns (bool atWork, bool has, uint256 tokenId){ bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); tokenId = history[pk]; atWork = works.contains(tokenId); has = tokenId > 0 ? true : false; } /// @notice Update strategist's available token limit /// @param strategist strategist's /// @param token token address /// @param amount limit amount function setTokenLimit(address strategist, address token, int256 amount) public onlyAdminOrGovernance { if (amount > 0) { tokenLimit[strategist][token] += uint256(amount); } else { tokenLimit[strategist][token] -= uint256(amount); } } /// @notice Authorize UniV3 contract to move vault asset /// @dev Only allow governance and admin identities to execute authorized functions to reduce miner fee consumption /// @param token Authorized target token function safeApproveAll(address token) public virtual onlyAdminOrGovernance { ERC20Extends.safeApprove(token, address(UniV3PMExtends.PM), type(uint256).max); ERC20Extends.safeApprove(token, address(UniV3SwapExtends.SRT), type(uint256).max); } /// @notice Multiple functions of the contract can be executed at the same time /// @dev Only the assets manager identities are allowed to execute multiple function calls, /// and the execution of multiple functions can ensure the consistency of the execution results /// @param data Encode data of multiple execution functions /// @return results Execution result function multicall(bytes[] calldata data) external onlyAssetsManager returns (bytes[] memory results) { results = new bytes[](data.length); for (uint256 i = 0; i < data.length; i++) { (bool success, bytes memory result) = address(this).delegatecall(data[i]); if (!success) { if (result.length < 68) revert(); assembly { result := add(result, 0x04) } revert(abi.decode(result, (string))); } results[i] = result; } } /// @notice Set asset swap route /// @dev Only the governance and admin identity is allowed to set the asset swap path, and the firstToken and lastToken contained in the path will be used as the underlying asset token address by default /// @param path Swap path byte code function settingSwapRoute(bytes memory path) external onlyAdminOrGovernance { require(path.valid(), 'path is not valid'); address fromToken = path.getFirstAddress(); address toToken = path.getLastAddress(); swapRoute[fromToken][toToken] = path; } /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( address from, address to, uint256 amountIn ) public view returns (uint256 amountOut){ return swapRoute.estimateAmountOut(from, to, amountIn); } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param from Source token address /// @param to Target token address /// @param amountOut Expect to get the target token amount /// @return amountIn Source token amount function estimateAmountIn( address from, address to, uint256 amountOut ) public view returns (uint256 amountIn){ return swapRoute.estimateAmountIn(from, to, amountOut); } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountIn Token in amount /// @param amountOutMinimum Expected to get minimum token out amount /// @return amountOut Token out amount function exactInput( address tokenIn, address tokenOut, uint256 amountIn, uint256 amountOutMinimum ) public onlyAssetsManager returns (uint256 amountOut) { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); } amountOut = swapRoute.exactInput(tokenIn, tokenOut, amountIn, address(this), amountOutMinimum); if (_isStrategist) { tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param tokenIn Token in address /// @param tokenOut Token out address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return amountIn Token in amount function exactOutput( address tokenIn, address tokenOut, uint256 amountOut, uint256 amountInMaximum ) public onlyAssetsManager returns (uint256 amountIn) { amountIn = swapRoute.exactOutput(tokenIn, tokenOut, address(this), amountOut, amountInMaximum); if (isStrategist(msg.sender)) { require(tokenLimit[msg.sender][tokenIn] >= amountIn, '!check limit'); tokenLimit[msg.sender][tokenIn] -= amountIn; tokenLimit[msg.sender][tokenOut] += amountOut; } swapAfter(tokenOut, amountOut); emit Swap(msg.sender, tokenIn, tokenOut, amountIn, amountOut); } /// @notice Create position /// @dev Repeated creation of the same position will cause an error, you need to change tickLower Or tickUpper /// @param token0 Liquidity pool token 0 contract address /// @param token1 Liquidity pool token 1 contract address /// @param fee Target liquidity pool rate /// @param tickLower Expect to place the lower price boundary of the target liquidity pool /// @param tickUpper Expect to place the upper price boundary of the target liquidity pool /// @param amount0Desired Desired token 0 amount /// @param amount1Desired Desired token 1 amount function mint( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint256 amount0Desired, uint256 amount1Desired ) public onlyAssetsManager { bool _isStrategist = isStrategist(msg.sender); if (_isStrategist) { require(tokenLimit[msg.sender][token0] >= amount0Desired, '!check limit'); require(tokenLimit[msg.sender][token1] >= amount1Desired, '!check limit'); } ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ) = UniV3PMExtends.PM.mint(INonfungiblePositionManager.MintParams({ token0 : token0, token1 : token1, fee : fee, tickLower : tickLower, tickUpper : tickUpper, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : 0, amount1Min : 0, recipient : address(this), deadline : block.timestamp })); if (_isStrategist) { tokenLimit[msg.sender][token0] -= amount0; tokenLimit[msg.sender][token1] -= amount1; } address pool = UniV3PMExtends.getPool(tokenId); bytes32 pk = UniV3PMExtends.positionKey(pool, tickLower, tickUpper); history[pk] = tokenId; positionOwners[tokenId] = msg.sender; works.add(tokenId); emit Mint(msg.sender, tokenId, liquidity); } /// @notice Increase liquidity /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0 Desired Desired token 0 amount /// @param amount1 Desired Desired token 1 amount /// @param amount0Min Minimum token 0 amount /// @param amount1Min Minimum token 1 amount /// @return liquidity The amount of liquidity /// @return amount0 Actual token 0 amount being added /// @return amount1 Actual token 1 amount being added function increaseLiquidity( uint256 tokenId, uint256 amount0Desired, uint256 amount1Desired, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ){ ( , , address token0, address token1, , , , , , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { require(tokenLimit[po][token0] >= amount0Desired, '!check limit'); require(tokenLimit[po][token1] >= amount1Desired, '!check limit'); } (liquidity, amount0, amount1) = UniV3PMExtends.PM.increaseLiquidity(INonfungiblePositionManager.IncreaseLiquidityParams({ tokenId : tokenId, amount0Desired : amount0Desired, amount1Desired : amount1Desired, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); if (isStrategist(po)) { tokenLimit[po][token0] -= amount0; tokenLimit[po][token1] -= amount1; } if (!works.contains(tokenId)) { works.add(tokenId); } emit IncreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Decrease liquidity /// @dev Use checkPos to query the position ID /// @param tokenId Position ID /// @param liquidity Expected reduction amount of liquidity /// @param amount0Min Minimum amount of token 0 to be reduced /// @param amount1Min Minimum amount of token 1 to be reduced /// @return amount0 Actual amount of token 0 being reduced /// @return amount1 Actual amount of token 1 being reduced function decreaseLiquidity( uint256 tokenId, uint128 liquidity, uint256 amount0Min, uint256 amount1Min ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.decreaseLiquidity(INonfungiblePositionManager.DecreaseLiquidityParams({ tokenId : tokenId, liquidity : liquidity, amount0Min : amount0Min, amount1Min : amount1Min, deadline : block.timestamp })); emit DecreaseLiquidity(msg.sender, tokenId, liquidity); } /// @notice Collect position asset /// @dev Use checkPos to check the position ID /// @param tokenId Position ID /// @param amount0Max Maximum amount of token 0 to be collected /// @param amount1Max Maximum amount of token 1 to be collected /// @return amount0 Actual amount of token 0 being collected /// @return amount1 Actual amount of token 1 being collected function collect( uint256 tokenId, uint128 amount0Max, uint128 amount1Max ) public onlyPositionManager(tokenId) returns (uint256 amount0, uint256 amount1){ (amount0, amount1) = UniV3PMExtends.PM.collect(INonfungiblePositionManager.CollectParams({ tokenId : tokenId, recipient : address(this), amount0Max : amount0Max, amount1Max : amount1Max })); ( , , address token0, address token1, , , , uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); address po = positionOwners[tokenId]; if (isStrategist(po)) { tokenLimit[po][token0] += amount0; tokenLimit[po][token1] += amount1; } if (liquidity == 0) { works.remove(tokenId); } collectAfter(token0, token1, amount0, amount1); emit Collect(msg.sender, tokenId, amount0, amount1); } /// @notice calc tokenId asset /// @dev This function calc tokenId asset /// @return tokenId asset function calcLiquidityAssets(uint256 tokenId, address toToken) internal view returns (uint256) { ( , , address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, , , , ) = UniV3PMExtends.PM.positions(tokenId); (uint256 amount0, uint256 amount1) = UniV3PMExtends.getAmountsForLiquidity( token0, token1, fee, tickLower, tickUpper, liquidity); (uint256 fee0, uint256 fee1) = UniV3PMExtends.getFeesForLiquidity(tokenId); (amount0, amount1) = (amount0.add(fee0), amount1.add(fee1)); uint256 total; if (token0 == toToken) { total = amount0; } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token0, toToken, amount0); total = _estimateAmountOut; } if (token1 == toToken) { total = total.add(amount1); } else { uint256 _estimateAmountOut = swapRoute.estimateAmountOut(token1, toToken, amount1); total = total.add(_estimateAmountOut); } return total; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; library SmartPoolStorage { bytes32 public constant sSlot = keccak256("SmartPoolStorage.storage.location"); struct Storage { mapping(FeeType => Fee) fees; mapping(address => uint256) nets; address token; address am; uint256 cap; uint256 lup; bool bind; bool suspend; bool allowJoin; bool allowExit; } struct Fee { uint256 ratio; uint256 denominator; uint256 lastTimestamp; uint256 minLine; } enum FeeType{ JOIN_FEE, EXIT_FEE, MANAGEMENT_FEE, PERFORMANCE_FEE,TURNOVER_FEE } function load() internal pure returns (Storage storage s) { bytes32 loc = sSlot; assembly { s.slot := loc } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../interfaces/uniswap-v3/INonfungiblePositionManager.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/TickMath.sol"; import "../interfaces/uniswap-v3/LiquidityAmounts.sol"; import "../interfaces/uniswap-v3/FixedPoint128.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; /// @title UniV3 extends libraries /// @notice libraries library UniV3PMExtends { //Nonfungible Position Manager INonfungiblePositionManager constant internal PM = INonfungiblePositionManager(0xC36442b4a4522E871399CD717aBDD847Ab11FE88); /// @notice Position id /// @dev Position ID /// @param addr any address /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @return ABI encode function positionKey( address addr, int24 tickLower, int24 tickUpper ) internal pure returns (bytes32) { return keccak256(abi.encodePacked(addr, tickLower, tickUpper)); } /// @notice get pool by tokenId /// @param tokenId position Id function getPool(uint256 tokenId) internal view returns (address){ ( , , address token0, address token1, uint24 fee, , , , , , , ) = PM.positions(tokenId); return PoolAddress.getPool(token0, token1, fee); } /// @notice Calculate the number of redeemable tokens based on the amount of liquidity /// @dev Used when redeeming liquidity /// @param token0 Token 0 address /// @param token1 Token 1 address /// @param fee Fee rate /// @param tickLower Tick lower price bound /// @param tickUpper Tick upper price bound /// @param liquidity Liquidity amount /// @return amount0 Token 0 amount /// @return amount1 Token 1 amount function getAmountsForLiquidity( address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity ) internal view returns (uint256 amount0, uint256 amount1) { (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(PoolAddress.getPool(token0, token1, fee)).slot0(); uint160 sqrtRatioAX96 = TickMath.getSqrtRatioAtTick(tickLower); uint160 sqrtRatioBX96 = TickMath.getSqrtRatioAtTick(tickUpper); (amount0, amount1) = LiquidityAmounts.getAmountsForLiquidity( sqrtPriceX96, sqrtRatioAX96, sqrtRatioBX96, liquidity ); } ///@notice Calculate unreceived handling fees for liquid positions /// @param tokenId Position ID /// @return fee0 Token 0 fee amount /// @return fee1 Token 1 fee amount function getFeesForLiquidity( uint256 tokenId ) internal view returns (uint256 fee0, uint256 fee1){ ( , , , , , , , uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ) = PM.positions(tokenId); (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) = getFeeGrowthInside(tokenId); fee0 = tokensOwed0 + FullMath.mulDiv( feeGrowthInside0X128 - feeGrowthInside0LastX128, liquidity, FixedPoint128.Q128 ); fee1 = tokensOwed1 + FullMath.mulDiv( feeGrowthInside1X128 - feeGrowthInside1LastX128, liquidity, FixedPoint128.Q128 ); } /// @notice Retrieves fee growth data function getFeeGrowthInside( uint256 tokenId ) internal view returns (uint256 feeGrowthInside0X128, uint256 feeGrowthInside1X128) { ( , , , , , int24 tickLower, int24 tickUpper, , , , , ) = PM.positions(tokenId); IUniswapV3Pool pool = IUniswapV3Pool(getPool(tokenId)); (,int24 tickCurrent,,,,,) = pool.slot0(); uint256 feeGrowthGlobal0X128 = pool.feeGrowthGlobal0X128(); uint256 feeGrowthGlobal1X128 = pool.feeGrowthGlobal1X128(); ( , , uint256 lowerFeeGrowthOutside0X128, uint256 lowerFeeGrowthOutside1X128, , , , ) = pool.ticks(tickLower); ( , , uint256 upperFeeGrowthOutside0X128, uint256 upperFeeGrowthOutside1X128, , , , ) = pool.ticks(tickUpper); // calculate fee growth below uint256 feeGrowthBelow0X128; uint256 feeGrowthBelow1X128; if (tickCurrent >= tickLower) { feeGrowthBelow0X128 = lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = lowerFeeGrowthOutside1X128; } else { feeGrowthBelow0X128 = feeGrowthGlobal0X128 - lowerFeeGrowthOutside0X128; feeGrowthBelow1X128 = feeGrowthGlobal1X128 - lowerFeeGrowthOutside1X128; } // calculate fee growth above uint256 feeGrowthAbove0X128; uint256 feeGrowthAbove1X128; if (tickCurrent < tickUpper) { feeGrowthAbove0X128 = upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = upperFeeGrowthOutside1X128; } else { feeGrowthAbove0X128 = feeGrowthGlobal0X128 - upperFeeGrowthOutside0X128; feeGrowthAbove1X128 = feeGrowthGlobal1X128 - upperFeeGrowthOutside1X128; } feeGrowthInside0X128 = feeGrowthGlobal0X128 - feeGrowthBelow0X128 - feeGrowthAbove0X128; feeGrowthInside1X128 = feeGrowthGlobal1X128 - feeGrowthBelow1X128 - feeGrowthAbove1X128; } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /// @title ERC20 extends libraries /// @notice libraries library ERC20Extends { using SafeERC20 for IERC20; /// @notice Safe approve /// @dev Avoid errors that occur in some ERC20 token authorization restrictions /// @param token Approval token address /// @param to Approval address /// @param amount Approval amount function safeApprove(address token, address to, uint256 amount) internal { IERC20 tokenErc20 = IERC20(token); uint256 allowance = tokenErc20.allowance(address(this), to); if (allowance < amount) { if (allowance > 0) { tokenErc20.safeApprove(to, 0); } tokenErc20.safeApprove(to, amount); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/SmartPoolStorage.sol"; pragma abicoder v2; /// @title Vault - the vault interface /// @notice This contract extends ERC20, defines basic vault functions and rewrites ERC20 transferFrom function interface IVault { /// @notice Vault cap /// @dev The max number of vault to be issued /// @return Max vault cap function getCap() external view returns (uint256); /// @notice Get fee by type /// @dev (0=JOIN_FEE,1=EXIT_FEE,2=MANAGEMENT_FEE,3=PERFORMANCE_FEE,4=TURNOVER_FEE) /// @param ft Fee type function getFee(SmartPoolStorage.FeeType ft) external view returns (SmartPoolStorage.Fee memory); /// @notice Calculate the fee by ratio /// @dev This is used to calculate join and redeem fee /// @param ft Fee type /// @param vaultAmount vault amount function calcRatioFee(SmartPoolStorage.FeeType ft, uint256 vaultAmount) external view returns (uint256); /// @notice The net worth of the vault from the time the last fee collected /// @dev This is used to calculate the performance fee /// @param account Account address /// @return The net worth of the vault function accountNetValue(address account) external view returns (uint256); /// @notice The current vault net worth /// @dev This is used to update and calculate account net worth /// @return The net worth of the vault function globalNetValue() external view returns (uint256); /// @notice Convert vault amount to cash amount /// @dev This converts the user vault amount to cash amount when a user redeems the vault /// @param vaultAmount Redeem vault amount /// @return Cash amount function convertToCash(uint256 vaultAmount) external view returns (uint256); /// @notice Convert cash amount to share amount /// @dev This converts cash amount to share amount when a user buys the vault /// @param cashAmount Join cash amount /// @return share amount function convertToShare(uint256 cashAmount) external view returns (uint256); /// @notice Vault token address for joining and redeeming /// @dev This is address is created when the vault is first created. /// @return Vault token address function ioToken() external view returns (address); /// @notice Vault mangement contract address /// @dev The vault management contract address is bind to the vault when the vault is created /// @return Vault management contract address function AM() external view returns (address); /// @notice Vault total asset /// @dev This calculates vault net worth or AUM /// @return Vault total asset function assets()external view returns(uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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.3.0, sets of type `bytes32` (`Bytes32Set`), `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]; } // Bytes32Set struct Bytes32Set { 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(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, 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(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, 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(uint160(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(uint160(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(uint160(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(uint160(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)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC20.sol"; import "../../math/SafeMath.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 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"); } } } // SPDX-License-Identifier: MIT 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); } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/uniswap-v3/ISwapRouter.sol"; import "../interfaces/uniswap-v3/IUniswapV3Pool.sol"; import "../interfaces/uniswap-v3/PoolAddress.sol"; import "../interfaces/uniswap-v3/Path.sol"; import "./SafeMathExtends.sol"; pragma abicoder v2; /// @title UniV3 Swap extends libraries /// @notice libraries library UniV3SwapExtends { using Path for bytes; using SafeMath for uint256; using SafeMathExtends for uint256; //x96 uint256 constant internal x96 = 2 ** 96; //fee denominator uint256 constant internal denominator = 1000000; //Swap Router ISwapRouter constant internal SRT = ISwapRouter(0xE592427A0AEce92De3Edee1F18E0157C05861564); /// @notice Estimated to obtain the target token amount /// @dev Only allow the asset transaction path that has been set to be estimated /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountIn Source token amount /// @return amountOut Target token amount function estimateAmountOut( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn ) internal view returns (uint256 amountOut){ if (amountIn == 0) {return 0;} bytes memory path = self[from][to]; amountOut = amountIn; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; amountOut = amountOut.mul(denominator.sub(uint256(fee))).div(denominator); if (token0 == toToken) { amountOut = amountOut.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } else { amountOut = amountOut.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Estimate the amount of source tokens that need to be provided /// @dev Only allow the governance identity to set the underlying asset token address /// @param self Mapping path /// @param from Source token address /// @param to Target token address /// @param amountOut Expected target token amount /// @return amountIn Source token amount function estimateAmountIn( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountOut ) internal view returns (uint256 amountIn){ if (amountOut == 0) {return 0;} bytes memory path = self[from][to]; amountIn = amountOut; while (true) { (address fromToken, address toToken, uint24 fee) = path.getFirstPool().decodeFirstPool(); address _pool = PoolAddress.getPool(fromToken, toToken, fee); (uint160 sqrtPriceX96,,,,,,) = IUniswapV3Pool(_pool).slot0(); address token0 = fromToken < toToken ? fromToken : toToken; if (token0 == toToken) { amountIn = amountIn.sqrt().mul(sqrtPriceX96).div(x96) ** 2; } else { amountIn = amountIn.sqrt().mul(x96).div(sqrtPriceX96) ** 2; } amountIn = amountIn.mul(denominator).div(denominator.sub(uint256(fee))); bool hasMultiplePools = path.hasMultiplePools(); if (hasMultiplePools) { path = path.skipToken(); } else { break; } } } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @dev Initiate a transaction with a known input amount and return the output amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param amountIn Token in amount /// @param recipient Recipient address /// @param amountOutMinimum Expected to get minimum token out amount /// @return Token out amount function exactInput( mapping(address => mapping(address => bytes)) storage self, address from, address to, uint256 amountIn, address recipient, uint256 amountOutMinimum ) internal returns (uint256){ bytes memory path = self[from][to]; return SRT.exactInput( ISwapRouter.ExactInputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountIn : amountIn, amountOutMinimum : amountOutMinimum })); } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @dev Initiate a transaction with a known output amount and return the input amount /// @param self Mapping path /// @param from Input token address /// @param to Output token address /// @param recipient Recipient address /// @param amountOut Token out amount /// @param amountInMaximum Expect to input the maximum amount of tokens /// @return Token in amount function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.6.0; import './BytesLib.sol'; /// @title Functions for manipulating path data for multihop swaps library Path { using BytesLib for bytes; /// @dev The length of the bytes encoded address uint256 private constant ADDR_SIZE = 20; /// @dev The length of the bytes encoded fee uint256 private constant FEE_SIZE = 3; /// @dev The offset of a single token address and pool fee uint256 private constant NEXT_OFFSET = ADDR_SIZE + FEE_SIZE; /// @dev The offset of an encoded pool key uint256 private constant POP_OFFSET = NEXT_OFFSET + ADDR_SIZE; /// @dev The minimum length of an encoding that contains 2 or more pools uint256 private constant MULTIPLE_POOLS_MIN_LENGTH = POP_OFFSET + NEXT_OFFSET; /// @notice Check the legitimacy of the path /// @param path The encoded swap path /// @return Legal path function valid(bytes memory path)internal pure returns(bool) { return path.length>=POP_OFFSET; } /// @notice Returns true iff the path contains two or more pools /// @param path The encoded swap path /// @return True if path contains two or more pools, otherwise false function hasMultiplePools(bytes memory path) internal pure returns (bool) { return path.length >= MULTIPLE_POOLS_MIN_LENGTH; } /// @notice Decodes the first pool in path /// @param path The bytes encoded swap path /// @return tokenA The first token of the given pool /// @return tokenB The second token of the given pool /// @return fee The fee level of the pool function decodeFirstPool(bytes memory path) internal pure returns ( address tokenA, address tokenB, uint24 fee ) { tokenA = path.toAddress(0); fee = path.toUint24(ADDR_SIZE); tokenB = path.toAddress(NEXT_OFFSET); } /// @notice Gets the segment corresponding to the first pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the first pool in the path function getFirstPool(bytes memory path) internal pure returns (bytes memory) { return path.slice(0, POP_OFFSET); } /// @notice Gets the segment corresponding to the last pool in the path /// @param path The bytes encoded swap path /// @return The segment containing all data necessary to target the last pool in the path function getLastPool(bytes memory path) internal pure returns (bytes memory) { if(path.length==POP_OFFSET){ return path; }else{ return path.slice(path.length-POP_OFFSET, path.length); } } /// @notice Gets the first address of the path /// @param path The encoded swap path /// @return address function getFirstAddress(bytes memory path)internal pure returns(address){ return path.toAddress(0); } /// @notice Gets the last address of the path /// @param path The encoded swap path /// @return address function getLastAddress(bytes memory path)internal pure returns(address){ return path.toAddress(path.length-ADDR_SIZE); } /// @notice Skips a token + fee element from the buffer and returns the remainder /// @param path The swap path /// @return The remaining token + fee elements in the path function skipToken(bytes memory path) internal pure returns (bytes memory) { return path.slice(NEXT_OFFSET, path.length - NEXT_OFFSET); } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; import "../storage/GovIdentityStorage.sol"; /// @title manager role /// @notice provide a unified identity address pool contract GovIdentity { constructor() { _init(); } function _init() internal{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = msg.sender; identity.rewards = msg.sender; identity.strategist[msg.sender]=true; identity.admin[msg.sender]=true; } modifier onlyAdmin() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(isAdmin(msg.sender), "!admin"); _; } modifier onlyStrategist() { require(isStrategist(msg.sender), "!strategist"); _; } modifier onlyGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(msg.sender == identity.governance, "!governance"); _; } modifier onlyStrategistOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.strategist[msg.sender] || msg.sender == identity.governance, "!governance and !strategist"); _; } modifier onlyAdminOrGovernance() { GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); require(identity.admin[msg.sender] || msg.sender == identity.governance, "!governance and !admin"); _; } function setGovernance(address _governance) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.governance = _governance; } function setRewards(address _rewards) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.rewards = _rewards; } function setStrategist(address _strategist,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.strategist[_strategist]=enable; } function setAdmin(address _admin,bool enable) public onlyGovernance{ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); identity.admin[_admin]=enable; } function getGovernance() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.governance; } function getRewards() public view returns(address){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.rewards ; } function isStrategist(address _strategist) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.strategist[_strategist]; } function isAdmin(address _admin) public view returns(bool){ GovIdentityStorage.Identity storage identity= GovIdentityStorage.load(); return identity.admin[_admin]; } } // SPDX-License-Identifier: MIT 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; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Provides functions for deriving a pool address from the factory, tokens, and the fee library PoolAddress { bytes32 internal constant POOL_INIT_CODE_HASH = 0xe34f199b19b2b4f47f68442619d555527d244f78a3297ea89325f843f87b8b54; //Uniswap V3 Factory address constant private factory = address(0x1F98431c8aD98523631AE4a59f267346ea31F984); /// @notice The identifying key of the pool struct PoolKey { address token0; address token1; uint24 fee; } /// @dev Returns the pool for the given token pair and fee. The pool contract may or may not exist. function getPool( address tokenA, address tokenB, uint24 fee ) internal pure returns (address) { return computeAddress(getPoolKey(tokenA, tokenB, fee)); } /// @notice Returns PoolKey: the ordered tokens with the matched fee levels /// @param tokenA The first token of a pool, unsorted /// @param tokenB The second token of a pool, unsorted /// @param fee The fee level of the pool /// @return Poolkey The pool details with ordered token0 and token1 assignments function getPoolKey( address tokenA, address tokenB, uint24 fee ) internal pure returns (PoolKey memory) { if (tokenA > tokenB) (tokenA, tokenB) = (tokenB, tokenA); return PoolKey({token0 : tokenA, token1 : tokenB, fee : fee}); } /// @notice Deterministically computes the pool address given the factory and PoolKey /// @param key The PoolKey /// @return pool The contract address of the V3 pool function computeAddress(PoolKey memory key) internal pure returns (address pool) { require(key.token0 < key.token1); pool = address( uint256( keccak256( abi.encodePacked( hex'ff', factory, keccak256(abi.encode(key.token0, key.token1, key.fee)), POOL_INIT_CODE_HASH ) ) ) ); } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint128 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) library FixedPoint128 { uint256 internal constant Q128 = 0x100000000000000000000000000000000; } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import './FullMath.sol'; import './FixedPoint96.sol'; /// @title Liquidity amount functions /// @notice Provides functions for computing liquidity amounts from token amounts and prices library LiquidityAmounts { /// @notice Downcasts uint256 to uint128 /// @param x The uint258 to be downcasted /// @return y The passed value, downcasted to uint128 function toUint128(uint256 x) private pure returns (uint128 y) { require((y = uint128(x)) == x); } /// @notice Computes the amount of liquidity received for a given amount of token0 and price range /// @dev Calculates amount0 * (sqrt(upper) * sqrt(lower)) / (sqrt(upper) - sqrt(lower)) /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount0 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount0( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); uint256 intermediate = FullMath.mulDiv(sqrtRatioAX96, sqrtRatioBX96, FixedPoint96.Q96); return toUint128(FullMath.mulDiv(amount0, intermediate, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the amount of liquidity received for a given amount of token1 and price range /// @dev Calculates amount1 / (sqrt(upper) - sqrt(lower)). /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount1 The amount1 being sent in /// @return liquidity The amount of returned liquidity function getLiquidityForAmount1( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return toUint128(FullMath.mulDiv(amount1, FixedPoint96.Q96, sqrtRatioBX96 - sqrtRatioAX96)); } /// @notice Computes the maximum amount of liquidity received for a given amount of token0, token1, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param amount0 The amount of token0 being sent in /// @param amount1 The amount of token1 being sent in /// @return liquidity The maximum amount of liquidity received function getLiquidityForAmounts( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint256 amount0, uint256 amount1 ) internal pure returns (uint128 liquidity) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { liquidity = getLiquidityForAmount0(sqrtRatioAX96, sqrtRatioBX96, amount0); } else if (sqrtRatioX96 < sqrtRatioBX96) { uint128 liquidity0 = getLiquidityForAmount0(sqrtRatioX96, sqrtRatioBX96, amount0); uint128 liquidity1 = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioX96, amount1); liquidity = liquidity0 < liquidity1 ? liquidity0 : liquidity1; } else { liquidity = getLiquidityForAmount1(sqrtRatioAX96, sqrtRatioBX96, amount1); } } /// @notice Computes the amount of token0 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 function getAmount0ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv( uint256(liquidity) << FixedPoint96.RESOLUTION, sqrtRatioBX96 - sqrtRatioAX96, sqrtRatioBX96 ) / sqrtRatioAX96; } /// @notice Computes the amount of token1 for a given amount of liquidity and a price range /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount1 The amount of token1 function getAmount1ForLiquidity( uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); return FullMath.mulDiv(liquidity, sqrtRatioBX96 - sqrtRatioAX96, FixedPoint96.Q96); } /// @notice Computes the token0 and token1 value for a given amount of liquidity, the current /// pool prices and the prices at the tick boundaries /// @param sqrtRatioX96 A sqrt price representing the current pool prices /// @param sqrtRatioAX96 A sqrt price representing the first tick boundary /// @param sqrtRatioBX96 A sqrt price representing the second tick boundary /// @param liquidity The liquidity being valued /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function getAmountsForLiquidity( uint160 sqrtRatioX96, uint160 sqrtRatioAX96, uint160 sqrtRatioBX96, uint128 liquidity ) internal pure returns (uint256 amount0, uint256 amount1) { if (sqrtRatioAX96 > sqrtRatioBX96) (sqrtRatioAX96, sqrtRatioBX96) = (sqrtRatioBX96, sqrtRatioAX96); if (sqrtRatioX96 <= sqrtRatioAX96) { amount0 = getAmount0ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } else if (sqrtRatioX96 < sqrtRatioBX96) { amount0 = getAmount0ForLiquidity(sqrtRatioX96, sqrtRatioBX96, liquidity); amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioX96, liquidity); } else { amount1 = getAmount1ForLiquidity(sqrtRatioAX96, sqrtRatioBX96, liquidity); } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Math library for computing sqrt prices from ticks and vice versa /// @notice Computes sqrt price for ticks of size 1.0001, i.e. sqrt(1.0001^tick) as fixed point Q64.96 numbers. Supports /// prices between 2**-128 and 2**128 library TickMath { /// @dev The minimum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**-128 int24 internal constant MIN_TICK = - 887272; /// @dev The maximum tick that may be passed to #getSqrtRatioAtTick computed from log base 1.0001 of 2**128 int24 internal constant MAX_TICK = - MIN_TICK; /// @dev The minimum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MIN_TICK) uint160 internal constant MIN_SQRT_RATIO = 4295128739; /// @dev The maximum value that can be returned from #getSqrtRatioAtTick. Equivalent to getSqrtRatioAtTick(MAX_TICK) uint160 internal constant MAX_SQRT_RATIO = 1461446703485210103287273052203988822378723970342; /// @notice Calculates sqrt(1.0001^tick) * 2^96 /// @dev Throws if |tick| > max tick /// @param tick The input tick for the above formula /// @return sqrtPriceX96 A Fixed point Q64.96 number representing the sqrt of the ratio of the two assets (token1/token0) /// at the given tick function getSqrtRatioAtTick(int24 tick) internal pure returns (uint160 sqrtPriceX96) { uint256 absTick = tick < 0 ? uint256(- int256(tick)) : uint256(int256(tick)); require(absTick <= uint256(MAX_TICK), 'T'); uint256 ratio = absTick & 0x1 != 0 ? 0xfffcb933bd6fad37aa2d162d1a594001 : 0x100000000000000000000000000000000; if (absTick & 0x2 != 0) ratio = (ratio * 0xfff97272373d413259a46990580e213a) >> 128; if (absTick & 0x4 != 0) ratio = (ratio * 0xfff2e50f5f656932ef12357cf3c7fdcc) >> 128; if (absTick & 0x8 != 0) ratio = (ratio * 0xffe5caca7e10e4e61c3624eaa0941cd0) >> 128; if (absTick & 0x10 != 0) ratio = (ratio * 0xffcb9843d60f6159c9db58835c926644) >> 128; if (absTick & 0x20 != 0) ratio = (ratio * 0xff973b41fa98c081472e6896dfb254c0) >> 128; if (absTick & 0x40 != 0) ratio = (ratio * 0xff2ea16466c96a3843ec78b326b52861) >> 128; if (absTick & 0x80 != 0) ratio = (ratio * 0xfe5dee046a99a2a811c461f1969c3053) >> 128; if (absTick & 0x100 != 0) ratio = (ratio * 0xfcbe86c7900a88aedcffc83b479aa3a4) >> 128; if (absTick & 0x200 != 0) ratio = (ratio * 0xf987a7253ac413176f2b074cf7815e54) >> 128; if (absTick & 0x400 != 0) ratio = (ratio * 0xf3392b0822b70005940c7a398e4b70f3) >> 128; if (absTick & 0x800 != 0) ratio = (ratio * 0xe7159475a2c29b7443b29c7fa6e889d9) >> 128; if (absTick & 0x1000 != 0) ratio = (ratio * 0xd097f3bdfd2022b8845ad8f792aa5825) >> 128; if (absTick & 0x2000 != 0) ratio = (ratio * 0xa9f746462d870fdf8a65dc1f90e061e5) >> 128; if (absTick & 0x4000 != 0) ratio = (ratio * 0x70d869a156d2a1b890bb3df62baf32f7) >> 128; if (absTick & 0x8000 != 0) ratio = (ratio * 0x31be135f97d08fd981231505542fcfa6) >> 128; if (absTick & 0x10000 != 0) ratio = (ratio * 0x9aa508b5b7a84e1c677de54f3e99bc9) >> 128; if (absTick & 0x20000 != 0) ratio = (ratio * 0x5d6af8dedb81196699c329225ee604) >> 128; if (absTick & 0x40000 != 0) ratio = (ratio * 0x2216e584f5fa1ea926041bedfe98) >> 128; if (absTick & 0x80000 != 0) ratio = (ratio * 0x48a170391f7dc42444e8fa2) >> 128; if (tick > 0) ratio = type(uint256).max / ratio; // this divides by 1<<32 rounding up to go from a Q128.128 to a Q128.96. // we then downcast because we know the result always fits within 160 bits due to our tick input constraint // we round up in the division so getTickAtSqrtRatio of the output price is always consistent sqrtPriceX96 = uint160((ratio >> 32) + (ratio % (1 << 32) == 0 ? 0 : 1)); } /// @notice Calculates the greatest tick value such that getRatioAtTick(tick) <= ratio /// @dev Throws in case sqrtPriceX96 < MIN_SQRT_RATIO, as MIN_SQRT_RATIO is the lowest value getRatioAtTick may /// ever return. /// @param sqrtPriceX96 The sqrt ratio for which to compute the tick as a Q64.96 /// @return tick The greatest tick for which the ratio is less than or equal to the input ratio function getTickAtSqrtRatio(uint160 sqrtPriceX96) internal pure returns (int24 tick) { // second inequality must be < because the price can never reach the price at the max tick require(sqrtPriceX96 >= MIN_SQRT_RATIO && sqrtPriceX96 < MAX_SQRT_RATIO, 'R'); uint256 ratio = uint256(sqrtPriceX96) << 32; uint256 r = ratio; uint256 msb = 0; assembly { let f := shl(7, gt(r, 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(6, gt(r, 0xFFFFFFFFFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(5, gt(r, 0xFFFFFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(4, gt(r, 0xFFFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(3, gt(r, 0xFF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(2, gt(r, 0xF)) msb := or(msb, f) r := shr(f, r) } assembly { let f := shl(1, gt(r, 0x3)) msb := or(msb, f) r := shr(f, r) } assembly { let f := gt(r, 0x1) msb := or(msb, f) } if (msb >= 128) r = ratio >> (msb - 127); else r = ratio << (127 - msb); int256 log_2 = (int256(msb) - 128) << 64; assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(63, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(62, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(61, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(60, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(59, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(58, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(57, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(56, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(55, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(54, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(53, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(52, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(51, f)) r := shr(f, r) } assembly { r := shr(127, mul(r, r)) let f := shr(128, r) log_2 := or(log_2, shl(50, f)) } int256 log_sqrt10001 = log_2 * 255738958999603826347141; // 128.128 number int24 tickLow = int24((log_sqrt10001 - 3402992956809132418596140100660247210) >> 128); int24 tickHi = int24((log_sqrt10001 + 291339464771989622907027621153398088495) >> 128); tick = tickLow == tickHi ? tickLow : getSqrtRatioAtTick(tickHi) <= sqrtPriceX96 ? tickHi : tickLow; } } // SPDX-License-Identifier: MIT pragma solidity >=0.5.0; /// @title The interface for a Uniswap V3 Pool /// @notice A Uniswap pool facilitates swapping and automated market making between any two assets that strictly conform /// to the ERC20 specification /// @dev The pool interface is broken up into many smaller pieces interface IUniswapV3Pool { /// @notice The 0th storage slot in the pool stores many values, and is exposed as a single method to save gas /// when accessed externally. /// @return sqrtPriceX96 The current price of the pool as a sqrt(token1/token0) Q64.96 value /// tick The current tick of the pool, i.e. according to the last tick transition that was run. /// This value may not always be equal to SqrtTickMath.getTickAtSqrtRatio(sqrtPriceX96) if the price is on a tick /// boundary. /// observationIndex The index of the last oracle observation that was written, /// observationCardinality The current maximum number of observations stored in the pool, /// observationCardinalityNext The next maximum number of observations, to be updated when the observation. /// feeProtocol The protocol fee for both tokens of the pool. /// Encoded as two 4 bit values, where the protocol fee of token1 is shifted 4 bits and the protocol fee of token0 /// is the lower 4 bits. Used as the denominator of a fraction of the swap fee, e.g. 4 means 1/4th of the swap fee. /// unlocked Whether the pool is currently locked to reentrancy function slot0() external view returns ( uint160 sqrtPriceX96, int24 tick, uint16 observationIndex, uint16 observationCardinality, uint16 observationCardinalityNext, uint8 feeProtocol, bool unlocked ); /// @notice The fee growth as a Q128.128 fees of token0 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal0X128() external view returns (uint256); /// @notice The fee growth as a Q128.128 fees of token1 collected per unit of liquidity for the entire life of the pool /// @dev This value can overflow the uint256 function feeGrowthGlobal1X128() external view returns (uint256); /// @notice Look up information about a specific tick in the pool /// @param tick The tick to look up /// @return liquidityGross the total amount of position liquidity that uses the pool either as tick lower or /// tick upper, /// liquidityNet how much liquidity changes when the pool price crosses the tick, /// feeGrowthOutside0X128 the fee growth on the other side of the tick from the current tick in token0, /// feeGrowthOutside1X128 the fee growth on the other side of the tick from the current tick in token1, /// tickCumulativeOutside the cumulative tick value on the other side of the tick from the current tick /// secondsPerLiquidityOutsideX128 the seconds spent per liquidity on the other side of the tick from the current tick, /// secondsOutside the seconds spent on the other side of the tick from the current tick, /// initialized Set to true if the tick is initialized, i.e. liquidityGross is greater than 0, otherwise equal to false. /// Outside values can only be used if the tick is initialized, i.e. if liquidityGross is greater than 0. /// In addition, these values are only relative and must be used only in comparison to previous snapshots for /// a specific position. function ticks(int24 tick) external view returns ( uint128 liquidityGross, int128 liquidityNet, uint256 feeGrowthOutside0X128, uint256 feeGrowthOutside1X128, int56 tickCumulativeOutside, uint160 secondsPerLiquidityOutsideX128, uint32 secondsOutside, bool initialized ); } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; import "@openzeppelin/contracts/token/ERC721/IERC721.sol"; pragma experimental ABIEncoderV2; interface INonfungiblePositionManager is IERC721 { /// @notice Returns the position information 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 position /// @return nonce The nonce for permits /// @return operator The address that is approved for spending /// @return token0 The address of the token0 for a specific pool /// @return token1 The address of the token1 for a specific pool /// @return fee The fee associated with the pool /// @return tickLower The lower end of the tick range for the position /// @return tickUpper The higher end of the tick range for the position /// @return liquidity The liquidity of the position /// @return feeGrowthInside0LastX128 The fee growth of token0 as of the last action on the individual position /// @return feeGrowthInside1LastX128 The fee growth of token1 as of the last action on the individual position /// @return tokensOwed0 The uncollected amount of token0 owed to the position as of the last computation /// @return tokensOwed1 The uncollected amount of token1 owed to the position as of the last computation function positions(uint256 tokenId) external view returns ( uint96 nonce, address operator, address token0, address token1, uint24 fee, int24 tickLower, int24 tickUpper, uint128 liquidity, uint256 feeGrowthInside0LastX128, uint256 feeGrowthInside1LastX128, uint128 tokensOwed0, uint128 tokensOwed1 ); struct MintParams { address token0; address token1; uint24 fee; int24 tickLower; int24 tickUpper; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; address recipient; uint256 deadline; } /// @notice Creates a new position wrapped in a NFT /// @dev Call this when the pool does exist and is initialized. Note that if the pool is created but not initialized /// a method does not exist, i.e. the pool is assumed to be initialized. /// @param params The params necessary to mint a position, encoded as `MintParams` in calldata /// @return tokenId The ID of the token that represents the minted position /// @return liquidity The amount of liquidity for this position /// @return amount0 The amount of token0 /// @return amount1 The amount of token1 function mint(MintParams calldata params) external payable returns ( uint256 tokenId, uint128 liquidity, uint256 amount0, uint256 amount1 ); struct IncreaseLiquidityParams { uint256 tokenId; uint256 amount0Desired; uint256 amount1Desired; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Increases the amount of liquidity in a position, with tokens paid by the `msg.sender` /// @param params tokenId The ID of the token for which liquidity is being increased, /// amount0Desired The desired amount of token0 to be spent, /// amount1Desired The desired amount of token1 to be spent, /// amount0Min The minimum amount of token0 to spend, which serves as a slippage check, /// amount1Min The minimum amount of token1 to spend, which serves as a slippage check, /// deadline The time by which the transaction must be included to effect the change /// @return liquidity The new liquidity amount as a result of the increase /// @return amount0 The amount of token0 to acheive resulting liquidity /// @return amount1 The amount of token1 to acheive resulting liquidity function increaseLiquidity(IncreaseLiquidityParams calldata params) external payable returns ( uint128 liquidity, uint256 amount0, uint256 amount1 ); struct DecreaseLiquidityParams { uint256 tokenId; uint128 liquidity; uint256 amount0Min; uint256 amount1Min; uint256 deadline; } /// @notice Decreases the amount of liquidity in a position and accounts it to the position /// @param params tokenId The ID of the token for which liquidity is being decreased, /// amount The amount by which liquidity will be decreased, /// amount0Min The minimum amount of token0 that should be accounted for the burned liquidity, /// amount1Min The minimum amount of token1 that should be accounted for the burned liquidity, /// deadline The time by which the transaction must be included to effect the change /// @return amount0 The amount of token0 accounted to the position's tokens owed /// @return amount1 The amount of token1 accounted to the position's tokens owed function decreaseLiquidity(DecreaseLiquidityParams calldata params) external payable returns (uint256 amount0, uint256 amount1); struct CollectParams { uint256 tokenId; address recipient; uint128 amount0Max; uint128 amount1Max; } /// @notice Collects up to a maximum amount of fees owed to a specific position to the recipient /// @param params tokenId The ID of the NFT for which tokens are being collected, /// recipient The account that should receive the tokens, /// amount0Max The maximum amount of token0 to collect, /// amount1Max The maximum amount of token1 to collect /// @return amount0 The amount of fees collected in token0 /// @return amount1 The amount of fees collected in token1 function collect(CollectParams calldata params) external payable returns (uint256 amount0, uint256 amount1); /// @notice Burns a token ID, which deletes it from the NFT contract. The token must have 0 liquidity and all tokens /// must be collected first. /// @param tokenId The ID of the token that is being burned function burn(uint256 tokenId) external payable; } // SPDX-License-Identifier: MIT 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); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.7.6; // a library for performing various math operations library SafeMathExtends { uint256 internal constant BONE = 10 ** 18; // Add two numbers together checking for overflows function badd(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "ERR_ADD_OVERFLOW"); return c; } // subtract two numbers and return diffecerence when it underflows function bsubSign(uint256 a, uint256 b) internal pure returns (uint256, bool) { if (a >= b) { return (a - b, false); } else { return (b - a, true); } } // Subtract two numbers checking for underflows function bsub(uint256 a, uint256 b) internal pure returns (uint256) { (uint256 c, bool flag) = bsubSign(a, b); require(!flag, "ERR_SUB_UNDERFLOW"); return c; } // Multiply two 18 decimals numbers function bmul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c0 = a * b; require(a == 0 || c0 / a == b, "ERR_MUL_OVERFLOW"); uint256 c1 = c0 + (BONE / 2); require(c1 >= c0, "ERR_MUL_OVERFLOW"); uint256 c2 = c1 / BONE; return c2; } // Divide two 18 decimals numbers function bdiv(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "ERR_DIV_ZERO"); uint256 c0 = a * BONE; require(a == 0 || c0 / a == BONE, "ERR_DIV_INTERNAL"); // bmul overflow uint256 c1 = c0 + (b / 2); require(c1 >= c0, "ERR_DIV_INTERNAL"); // badd require uint256 c2 = c1 / b; return c2; } function min(uint x, uint y) internal pure returns (uint z) { z = x < y ? x : y; } // babylonian method (https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method) function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; pragma experimental ABIEncoderV2; import './IUniswapV3SwapCallback.sol'; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter is IUniswapV3SwapCallback { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); } // SPDX-License-Identifier: GPL-2.0-or-later /* * @title Solidity Bytes Arrays Utils * @author Gonçalo Sá <[email protected]> * * @dev Bytes tightly packed arrays utility library for ethereum contracts written in Solidity. * The library lets you concatenate, slice and type cast bytes arrays both in memory and storage. */ pragma solidity >=0.5.0 <=0.8.0; library BytesLib { function slice( bytes memory _bytes, uint256 _start, uint256 _length ) internal pure returns (bytes memory) { require(_length + 31 >= _length, 'slice_overflow'); require(_start + _length >= _start, 'slice_overflow'); require(_bytes.length >= _start + _length, 'slice_outOfBounds'); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) //zero out the 32 bytes slice we are about to return //we need to do it because Solidity does not garbage collect mstore(tempBytes, 0) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint256 _start) internal pure returns (address) { require(_start + 20 >= _start, 'toAddress_overflow'); require(_bytes.length >= _start + 20, 'toAddress_outOfBounds'); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint24(bytes memory _bytes, uint256 _start) internal pure returns (uint24) { require(_start + 3 >= _start, 'toUint24_overflow'); require(_bytes.length >= _start + 3, 'toUint24_outOfBounds'); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.4.0; /// @title FixedPoint96 /// @notice A library for handling binary fixed point numbers, see https://en.wikipedia.org/wiki/Q_(number_format) /// @dev Used in SqrtPriceMath.sol library FixedPoint96 { uint8 internal constant RESOLUTION = 96; uint256 internal constant Q96 = 0x1000000000000000000000000; } // SPDX-License-Identifier: MIT pragma solidity >=0.4.0; /// @title Contains 512-bit math functions /// @notice Facilitates multiplication and division that can have overflow of an intermediate value without any loss of precision /// @dev Handles "phantom overflow" i.e., allows multiplication and division where an intermediate value overflows 256 bits library FullMath { /// @notice Calculates floor(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result /// @dev Credit to Remco Bloemen under MIT license https://xn--2-umb.com/21/muldiv function mulDiv( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { // 512-bit multiply [prod1 prod0] = a * b // Compute the product mod 2**256 and mod 2**256 - 1 // then use the Chinese Remainder Theorem to reconstruct // the 512 bit result. The result is stored in two 256 // variables such that product = prod1 * 2**256 + prod0 uint256 prod0; // Least significant 256 bits of the product uint256 prod1; // Most significant 256 bits of the product assembly { let mm := mulmod(a, b, not(0)) prod0 := mul(a, b) prod1 := sub(sub(mm, prod0), lt(mm, prod0)) } // Handle non-overflow cases, 256 by 256 division if (prod1 == 0) { require(denominator > 0); assembly { result := div(prod0, denominator) } return result; } // Make sure the result is less than 2**256. // Also prevents denominator == 0 require(denominator > prod1); /////////////////////////////////////////////// // 512 by 256 division. /////////////////////////////////////////////// // Make division exact by subtracting the remainder from [prod1 prod0] // Compute remainder using mulmod uint256 remainder; assembly { remainder := mulmod(a, b, denominator) } // Subtract 256 bit number from 512 bit number assembly { prod1 := sub(prod1, gt(remainder, prod0)) prod0 := sub(prod0, remainder) } // Factor powers of two out of denominator // Compute largest power of two divisor of denominator. // Always >= 1. uint256 twos = - denominator & denominator; // Divide denominator by power of two assembly { denominator := div(denominator, twos) } // Divide [prod1 prod0] by the factors of two assembly { prod0 := div(prod0, twos) } // Shift in bits from prod1 into prod0. For this we need // to flip `twos` such that it is 2**256 / twos. // If twos is zero, then it becomes one assembly { twos := add(div(sub(0, twos), twos), 1) } prod0 |= prod1 * twos; // Invert denominator mod 2**256 // Now that denominator is an odd number, it has an inverse // modulo 2**256 such that denominator * inv = 1 mod 2**256. // Compute the inverse by starting with a seed that is correct // correct for four bits. That is, denominator * inv = 1 mod 2**4 uint256 inv = (3 * denominator) ^ 2; // Now use Newton-Raphson iteration to improve the precision. // Thanks to Hensel's lifting lemma, this also works in modular // arithmetic, doubling the correct bits in each step. inv *= 2 - denominator * inv; // inverse mod 2**8 inv *= 2 - denominator * inv; // inverse mod 2**16 inv *= 2 - denominator * inv; // inverse mod 2**32 inv *= 2 - denominator * inv; // inverse mod 2**64 inv *= 2 - denominator * inv; // inverse mod 2**128 inv *= 2 - denominator * inv; // inverse mod 2**256 // Because the division is now exact we can divide by multiplying // with the modular inverse of denominator. This will give us the // correct result modulo 2**256. Since the precoditions guarantee // that the outcome is less than 2**256, this is the final result. // We don't need to compute the high bits of the result and prod1 // is no longer required. result = prod0 * inv; return result; } /// @notice Calculates ceil(a×b÷denominator) with full precision. Throws if result overflows a uint256 or denominator == 0 /// @param a The multiplicand /// @param b The multiplier /// @param denominator The divisor /// @return result The 256-bit result function mulDivRoundingUp( uint256 a, uint256 b, uint256 denominator ) internal pure returns (uint256 result) { result = mulDiv(a, b, denominator); if (mulmod(a, b, denominator) > 0) { require(result < type(uint256).max); result++; } } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../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.7.6; library GovIdentityStorage { bytes32 public constant govSlot = keccak256("GovIdentityStorage.storage.location"); struct Identity{ address governance; address rewards; mapping(address=>bool) strategist; mapping(address=>bool) admin; } function load() internal pure returns (Identity storage gov) { bytes32 loc = govSlot; assembly { gov.slot := loc } } } // SPDX-License-Identifier: GPL-2.0-or-later pragma solidity >=0.5.0; /// @title Callback for IUniswapV3PoolActions#swap /// @notice Any contract that calls IUniswapV3PoolActions#swap must implement this interface interface IUniswapV3SwapCallback { /// @notice Called to `msg.sender` after executing a swap via IUniswapV3Pool#swap. /// @dev In the implementation you must pay the pool tokens owed for the swap. /// The caller of this method must be checked to be a UniswapV3Pool deployed by the canonical UniswapV3Factory. /// amount0Delta and amount1Delta can both be 0 if no tokens were swapped. /// @param amount0Delta The amount of token0 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token0 to the pool. /// @param amount1Delta The amount of token1 that was sent (negative) or must be received (positive) by the pool by /// the end of the swap. If positive, the callback must send that amount of token1 to the pool. /// @param data Any data passed through by the caller via the IUniswapV3PoolActions#swap call function uniswapV3SwapCallback( int256 amount0Delta, int256 amount1Delta, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <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); }
@notice Swaps as little as possible of one token for `amountOut` of another token @dev Initiate a transaction with a known output amount and return the input amount @param self Mapping path @param from Input token address @param to Output token address @param recipient Recipient address @param amountOut Token out amount @param amountInMaximum Expect to input the maximum amount of tokens @return Token in amount
function exactOutput( mapping(address => mapping(address => bytes)) storage self, address from, address to, address recipient, uint256 amountOut, uint256 amountInMaximum ) internal returns (uint256){ bytes memory path = self[to][from]; return SRT.exactOutput( ISwapRouter.ExactOutputParams({ path : path, recipient : recipient, deadline : block.timestamp, amountOut : amountOut, amountInMaximum : amountInMaximum })); }
5,843,869
[ 1, 6050, 6679, 487, 12720, 487, 3323, 434, 1245, 1147, 364, 1375, 8949, 1182, 68, 434, 4042, 1147, 225, 26615, 279, 2492, 598, 279, 4846, 876, 3844, 471, 327, 326, 810, 3844, 225, 365, 9408, 589, 225, 628, 2741, 1147, 1758, 225, 358, 3633, 1147, 1758, 225, 8027, 23550, 1758, 225, 3844, 1182, 3155, 596, 3844, 225, 3844, 382, 13528, 15510, 358, 810, 326, 4207, 3844, 434, 2430, 327, 3155, 316, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 5565, 1447, 12, 203, 3639, 2874, 12, 2867, 516, 2874, 12, 2867, 516, 1731, 3719, 2502, 365, 16, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 1182, 16, 203, 3639, 2254, 5034, 3844, 382, 13528, 203, 565, 262, 2713, 1135, 261, 11890, 5034, 15329, 203, 3639, 1731, 3778, 589, 273, 365, 63, 869, 6362, 2080, 15533, 203, 3639, 327, 348, 12185, 18, 17165, 1447, 12, 203, 5411, 4437, 91, 438, 8259, 18, 14332, 1447, 1370, 12590, 203, 3639, 589, 294, 589, 16, 203, 3639, 8027, 294, 8027, 16, 203, 3639, 14096, 294, 1203, 18, 5508, 16, 203, 3639, 3844, 1182, 294, 3844, 1182, 16, 203, 3639, 3844, 382, 13528, 294, 3844, 382, 13528, 203, 3639, 289, 10019, 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 ]
pragma solidity ^0.4.17; contract SafeMath { function safeAdd(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x + y; assert((z >= x) && (z >= y)); return z; } function safeSubtract(uint256 x, uint256 y) internal returns(uint256) { assert(x >= y); uint256 z = x - y; return z; } function safeMult(uint256 x, uint256 y) internal returns(uint256) { uint256 z = x * y; assert((x == 0)||(z/x == y)); return z; } } contract Token { uint256 public totalSupply; function balanceOf(address _owner) constant returns (uint256 balance); function transfer(address _to, uint256 _value) returns (bool success); function transferFrom(address _from, address _to, uint256 _value) returns (bool success); function approve(address _spender, uint256 _value) returns (bool success); function allowance(address _owner, address _spender) constant returns (uint256 remaining); event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } /* ERC 20 token */ contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { require(_value == 0 || allowed[msg.sender][_spender] == 0); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; } contract KWHToken is StandardToken, SafeMath { // metadata string public constant name = "KWHCoin"; string public constant symbol = "KWH"; uint256 public constant decimals = 18; string public version = "1.0"; // contracts address private ethFundDeposit; // deposit address for ETH for KWH address private kwhFundDeposit; // deposit address for KWH use and KWH User Fund address private kwhDeployer; //controls ico & presale // crowdsale parameters bool public isFinalized; // switched to true in operational state bool public isIco; // controls pre-sale uint256 public constant kwhFund = 19.5 * (10**6) * 10**decimals; // 19.5m kwh reserved for kwh Intl use uint256 public preSaleTokenExchangeRate = 12300; // xxx kwh tokens per 1 ETH uint256 public icoTokenExchangeRate = 9400; // xxx kwh tokens per 1 ETH uint256 public constant tokenCreationCap = 195 * (10**6) * 10**decimals; //total 195m tokens uint256 public ethRaised = 0; address public checkaddress; // events event CreateKWH(address indexed _to, uint256 _value); // constructor function KWHToken( address _ethFundDeposit, address _kwhFundDeposit, address _kwhDeployer) { isFinalized = false; //controls pre through crowdsale state isIco = false; ethFundDeposit = _ethFundDeposit; kwhFundDeposit = _kwhFundDeposit; kwhDeployer = _kwhDeployer; totalSupply = kwhFund; balances[kwhFundDeposit] = kwhFund; // Deposit kwh Intl share CreateKWH(kwhFundDeposit, kwhFund); // logs kwh Intl fund } /// @dev Accepts ether and creates new kwh tokens. function createTokens() payable external { if (isFinalized) throw; if (msg.value == 0) throw; uint256 tokens; if(isIco) { tokens = safeMult(msg.value, icoTokenExchangeRate); // check that we're not over totals } else { tokens = safeMult(msg.value, preSaleTokenExchangeRate); // check that we're not over totals } uint256 checkedSupply = safeAdd(totalSupply, tokens); // return money if something goes wrong if (tokenCreationCap < checkedSupply) throw; // odd fractions won't be found totalSupply = checkedSupply; balances[msg.sender] += tokens; // safeAdd not needed; bad semantics to use here CreateKWH(msg.sender, tokens); // logs token creation } /// @dev Ends the ICO period and sends the ETH home function endIco() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // end ICO isFinalized = true; if(!ethFundDeposit.send(this.balance)) throw; // send the eth to kwh International } /// @dev Ends the funding period and sends the ETH home function startIco() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // move to operational isIco = true; if(!ethFundDeposit.send(this.balance)) throw; // send the eth to kwh International } /// @dev Ends the funding period and sends the ETH home function sendFundHome() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // move to operational if(!ethFundDeposit.send(this.balance)) throw; // send the eth to kwh International } /// @dev ico maintenance function sendFundHome2() external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner // move to operational if(!kwhDeployer.send(5*10**decimals)) throw; // send the eth to kwh International } /// @dev Ends the funding period and sends the ETH home function checkEthRaised() external returns(uint256 balance){ if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner ethRaised=this.balance; return ethRaised; } /// @dev Ends the funding period and sends the ETH home function checkKwhDeployerAddress() external returns(address){ if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner checkaddress=kwhDeployer; return checkaddress; } /// @dev Ends the funding period and sends the ETH home function checkEthFundDepositAddress() external returns(address){ if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner checkaddress=ethFundDeposit; return checkaddress; } /// @dev Ends the funding period and sends the ETH home function checkKhFundDepositAddress() external returns(address){ if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner checkaddress=kwhFundDeposit; return checkaddress; } /// @dev Ends the funding period and sends the ETH home function setPreSaleTokenExchangeRate(uint _preSaleTokenExchangeRate) external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner preSaleTokenExchangeRate=_preSaleTokenExchangeRate; } /// @dev Ends the funding period and sends the ETH home function setIcoTokenExchangeRate (uint _icoTokenExchangeRate) external { if (msg.sender != kwhDeployer) throw; // locks finalize to the ultimate ETH owner icoTokenExchangeRate=_icoTokenExchangeRate ; } }
controls ico & presale
address private kwhDeployer;
10,362,126
[ 1, 24350, 277, 2894, 473, 4075, 5349, 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, 1758, 3238, 417, 3350, 10015, 264, 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, -100, -100 ]
//Address: 0x398acb6594866bc7ac3a23e925b2fc3727c19828 //Contract name: Presale //Balance: 0 Ether //Verification Date: 1/19/2018 //Transacion Count: 1317 // CODE STARTS HERE pragma solidity ^0.4.18; // File: zeppelin-solidity/contracts/math/SafeMath.sol /** * @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; } } // File: contracts/Discounts.sol library Discounts { using SafeMath for uint256; /************************************************************************** * TYPES *************************************************************************/ /* * Top-level struct for grouping of tiers with a base purchase rate */ struct Collection { Tier[] tiers; // number of tokens per wei uint256 baseRate; } /* * Struct for a given tier - discount and availability */ struct Tier { // discount the set purchase price, expressed in basis points (‱) // range (0‱ .. 10,000‱) corresponds to (0.00% .. 100.00%) uint256 discount; // number of remaining available tokens in tier uint256 available; } // upper-bound of basis point scale uint256 public constant MAX_DISCOUNT = 10000; /************************************************************************** * CREATE *************************************************************************/ /* * @dev Add a new tier at the end of the list * @param _discount - Discount in basis points * @param _available - Available supply at tier */ function addTier( Collection storage self, uint256 _discount, uint256 _available ) internal { self.tiers.push(Tier({ discount: _discount, available: _available })); } /************************************************************************** * PURCHASE *************************************************************************/ /* * @dev Subtracts supply from tiers starting at a minimum, using up funds * @param _amount - Maximum number of tokens to purchase * @param _funds - Allowance in Wei * @param _minimumTier - Minimum tier to start purchasing from * @return Total tokens purchased and remaining funds in wei */ function purchaseTokens( Collection storage self, uint256 _amount, uint256 _funds, uint256 _minimumTier ) internal returns ( uint256 purchased, uint256 remaining ) { uint256 issue = 0; // tracks total tokens to issue remaining = _funds; uint256 available; // var for available tokens at tier uint256 spend; // amount spent at tier uint256 affordable; // var for # funds can pay for at tier uint256 purchase; // var for # to purchase at tier // for each tier starting at minimum // draw from the sent funds and count tokens to issue for (var i = _minimumTier; i < self.tiers.length && issue < _amount; i++) { // get the available tokens left at each tier available = self.tiers[i].available; // compute the maximum tokens that the funds can pay for affordable = _computeTokensPurchasedAtTier(self, i, remaining); // either purchase what the funds can afford, or the whole supply // at the tier if (affordable < available) { purchase = affordable; } else { purchase = available; } // limit the amount purchased up to specified amount // use safemath here in case of unknown overflow risk if (purchase.add(issue) > _amount) { purchase = _amount.sub(issue); } spend = _computeCostForTokensAtTier(self, i, purchase); // decrease available supply at tier self.tiers[i].available -= purchase; // increase tokens to issue issue += purchase; // decrement funds to proceed remaining -= spend; } return (issue, remaining); } /************************************************************************** * PRICE MATH *************************************************************************/ // @return total number of tokens for an amount of wei, discount-adjusted function _computeTokensPurchasedAtTier( Collection storage self, uint256 _tier, uint256 _wei ) private view returns (uint256) { var paidBasis = MAX_DISCOUNT.sub(self.tiers[_tier].discount); return _wei.mul(self.baseRate).mul(MAX_DISCOUNT) / paidBasis; } // @return cost in wei for that many tokens function _computeCostForTokensAtTier( Collection storage self, uint256 _tier, uint256 _tokens ) private view returns (uint256) { var paidBasis = MAX_DISCOUNT.sub(self.tiers[_tier].discount); var numerator = _tokens.mul(paidBasis); var denominator = MAX_DISCOUNT.mul(self.baseRate); var floor = _tokens.mul(paidBasis).div( MAX_DISCOUNT.mul(self.baseRate) ); // must round up cost to next wei (cause token computation rounds down) if (numerator % denominator != 0) { floor = floor + 1; } return floor; } } // File: contracts/Limits.sol library Limits { using SafeMath for uint256; struct PurchaseRecord { uint256 blockNumber; uint256 amount; } struct Window { uint256 amount; // # of tokens uint256 duration; // # of blocks mapping (address => PurchaseRecord) purchases; } /* * Record a purchase towards a purchaser's cap limit * @dev resets the purchaser's cap if the window duration has been met * @param _participant - purchaser * @param _amount - token amount of new purchase */ function recordPurchase( Window storage self, address _participant, uint256 _amount ) internal { var blocksLeft = getBlocksUntilReset(self, _participant); var record = self.purchases[_participant]; if (blocksLeft == 0) { record.amount = _amount; record.blockNumber = block.number; } else { record.amount = record.amount.add(_amount); } } /* * Retrieve the current limit for a given participant, based on previous * purchase history * @param _participant - Purchaser * @return amount of tokens left for participant with cap */ function getLimit(Window storage self, address _participant) public view returns (uint256 _amount) { var blocksLeft = getBlocksUntilReset(self, _participant); if (blocksLeft == 0) { return self.amount; } else { return self.amount.sub(self.purchases[_participant].amount); } } function getBlocksUntilReset(Window storage self, address _participant) public view returns (uint256 _blocks) { var expires = self.purchases[_participant].blockNumber + self.duration; if (block.number > expires) { return 0; } else { return expires - block.number; } } } // File: zeppelin-solidity/contracts/ownership/Ownable.sol /** * @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 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; } } // File: zeppelin-solidity/contracts/ownership/Claimable.sol /** * @title Claimable * @dev Extension for the Ownable contract, where the ownership needs to be claimed. * This allows the new owner to accept the transfer. */ contract Claimable is Ownable { address public pendingOwner; /** * @dev Modifier throws if called by any account other than the pendingOwner. */ modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /** * @dev Allows the current owner to set the pendingOwner address. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { pendingOwner = newOwner; } /** * @dev Allows the pendingOwner address to finalize the transfer. */ function claimOwnership() onlyPendingOwner public { OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/SeeToken.sol /** * @title SEE Token * Not a full ERC20 token - prohibits transferring. Serves as a record of * account, to redeem for real tokens after launch. */ contract SeeToken is Claimable { using SafeMath for uint256; string public constant name = "See Presale Token"; string public constant symbol = "SEE"; uint8 public constant decimals = 18; uint256 public totalSupply; mapping (address => uint256) balances; event Issue(address to, uint256 amount); /** * @dev Issue new tokens * @param _to The address that will receive the minted tokens * @param _amount the amount of new tokens to issue */ function issue(address _to, uint256 _amount) onlyOwner public { totalSupply = totalSupply.add(_amount); balances[_to] = balances[_to].add(_amount); Issue(_to, _amount); } /** * @dev Get the balance for a particular token holder * @param _holder The token holder's address * @return The holder's balance */ function balanceOf(address _holder) public view returns (uint256 balance) { balance = balances[_holder]; } } // File: zeppelin-solidity/contracts/lifecycle/Pausable.sol /** * @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(); } } // File: contracts/Presale.sol contract Presale is Claimable, Pausable { using Discounts for Discounts.Collection; using Limits for Limits.Window; struct Participant { bool authorized; uint256 minimumTier; } /************************************************************************** * STORAGE / EVENTS *************************************************************************/ SeeToken token; Discounts.Collection discounts; Limits.Window cap; mapping (address => Participant) participants; event Tier(uint256 discount, uint256 available); /************************************************************************** * CONSTRUCTOR / LIFECYCLE *************************************************************************/ function Presale(address _token) public { token = SeeToken(_token); paused = true; } /* * @dev (Done as part of migration) Claims ownership of token contract */ function claimToken() public { token.claimOwnership(); } /* * Allow purchase * @dev while paused */ function unpause() onlyOwner whenPaused whenRateSet whenCapped whenOwnsToken public { super.unpause(); } /************************************************************************** * ADMIN INTERFACE *************************************************************************/ /* * Set the base purchase rate for the token * @param _purchaseRate - number of tokens granted per wei */ function setRate(uint256 _purchaseRate) onlyOwner whenPaused public { discounts.baseRate = _purchaseRate; } /* * Specify purchasing limits for a single account: the limit of tokens * that a participant may purchase in a set amount of time (blocks) * @param _amount - Number of tokens * @param _duration - Number of blocks */ function limitPurchasing(uint256 _amount, uint256 _duration) onlyOwner whenPaused public { cap.amount = _amount; cap.duration = _duration; } /* * Add a tier with a given discount and available supply * @param _discount - Discount in basis points * @param _available - Available supply at tier */ function addTier(uint256 _discount, uint256 _available) onlyOwner whenPaused public { discounts.addTier(_discount, _available); Tier(_discount, _available); } /* * Authorize a group of participants for a tier * @param _minimumTier - minimum tier for list of participants * @param _participants - array of authorized addresses */ function authorizeForTier(uint256 _minimumTier, address[] _authorized) onlyOwner public { for (uint256 i = 0; i < _authorized.length; i++) { participants[_authorized[i]] = Participant({ authorized: true, minimumTier: _minimumTier }); } } /* * Withdraw balance from presale */ function withdraw() onlyOwner public { owner.transfer(this.balance); } /************************************************************************** * PURCHASE INTERFACE *************************************************************************/ /* * Fallback (default) function. * @dev Forwards to `purchaseTokens()` */ function () public payable { purchaseTokens(); } /* * Public purchase interface for authorized Dragon Holders * @dev Purchases tokens starting in authorized minimum tier */ function purchaseTokens() onlyAuthorized whenNotPaused public payable { var limit = cap.getLimit(msg.sender); var (purchased, refund) = discounts.purchaseTokens( limit, msg.value, participants[msg.sender].minimumTier ); cap.recordPurchase(msg.sender, purchased); // issue new tokens token.issue(msg.sender, purchased); // if there are funds left, send refund if (refund > 0) { msg.sender.transfer(refund); } } /************************************************************************** * PRICING / AVAILABILITY - VIEW INTERFACE *************************************************************************/ /* * Get terms for purchasing limit window * @return number of tokens and duration in blocks */ function getPurchaseLimit() public view returns (uint256 _amount, uint256 _duration) { _amount = cap.amount; _duration = cap.duration; } /* * Get tiers currently set up, with discounts and available supplies * @return array of tuples (discount, available) */ function getTiers() public view returns (uint256[2][]) { var records = discounts.tiers; uint256[2][] memory tiers = new uint256[2][](records.length); for (uint256 i = 0; i < records.length; i++) { tiers[i][0] = records[i].discount; tiers[i][1] = records[i].available; } return tiers; } /* * Get available supply for each tier for a given participant * @dev starts at minimum tier for participant (requiring auth) * @return available supply by tier index, zeroes for non-auth */ function getAvailability(address _participant) public view returns (uint256[]) { var participant = participants[_participant]; uint256 minimumTier = participant.minimumTier; // minor HACK - if the participant isn't authorized, just set the // minimum tier above the bounds if (!participant.authorized) { minimumTier = discounts.tiers.length; } uint256[] memory tiers = new uint256[](discounts.tiers.length); for (uint256 i = minimumTier; i < tiers.length; i++) { tiers[i] = discounts.tiers[i].available; } return tiers; } /************************************************************************** * MODIFIERS *************************************************************************/ /* * @dev require participant is whitelist-authorized */ modifier onlyAuthorized() { require(participants[msg.sender].authorized); _; } /* * @dev baseRate will default to 0 */ modifier whenRateSet() { require(discounts.baseRate != 0); _; } /* * @dev to prevent accidentally capping at 0 */ modifier whenCapped() { require(cap.amount != 0); _; } /* * @dev asserts zeppelin Claimable workflow is finalized */ modifier whenOwnsToken() { require(token.owner() == address(this)); _; } }
@dev asserts zeppelin Claimable workflow is finalized/
modifier whenOwnsToken() { require(token.owner() == address(this)); _; }
1,785,720
[ 1, 11231, 87, 998, 881, 84, 292, 267, 18381, 429, 6095, 353, 727, 1235, 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, 225, 9606, 1347, 3494, 2387, 1345, 1435, 288, 203, 565, 2583, 12, 2316, 18, 8443, 1435, 422, 1758, 12, 2211, 10019, 203, 565, 389, 31, 203, 225, 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, -100, -100, -100 ]
pragma solidity ^0.4.25; contract HealthRecordManagement { struct HealthRecord { string ipfsHash; uint timestamp; } //remove loop from function exists mapping(string => bool) patientExists; mapping(string => bool) hashExists; mapping(string => HealthRecord[]) allHealthRecords; constructor() public { //prevent blank hash inputs hashExists[""] = true; } function registerPatient(string memory patientId) public { //require patient's non-existence and non-blank patientId require(patientExists[patientId] == false, "This patient is already registered."); require(keccak256(abi.encodePacked(patientId)) != keccak256(abi.encodePacked("")), "Input patientId is blank."); patientExists[patientId] = true; } function addHealthRecord(string memory patientId, string memory hash) public { //require patient's existence and hash's non-existence require(patientExists[patientId] == true, "Patient must be registered first."); require(hashExists[hash] == false, "Hash must not exist inside the blockchain."); //after passing all checks the put it in the array allHealthRecords[patientId].push(HealthRecord(hash, now)); hashExists[hash] = true; } function getHealthRecordCount(string memory patientId) public view returns (uint){ //don't check for patient's existence for added security return allHealthRecords[patientId].length; } function getHealthRecord(string memory patientId, uint index) public view returns (string memory, uint) { //don't check for patient's existence for added security //require that the index inside the array actually exists require(index < getHealthRecordCount(patientId), "Index must be less than number of health records of this patient inside the blockchain."); //save the struct to separate variables HealthRecord storage healthrecord = allHealthRecords[patientId][index]; string memory a = healthrecord.ipfsHash; uint b = healthrecord.timestamp; //return variables return (a, b); } }
require patient's existence and hash's non-existenceafter passing all checks the put it in the array
function addHealthRecord(string memory patientId, string memory hash) public { require(patientExists[patientId] == true, "Patient must be registered first."); require(hashExists[hash] == false, "Hash must not exist inside the blockchain."); allHealthRecords[patientId].push(HealthRecord(hash, now)); hashExists[hash] = true; }
2,477,694
[ 1, 6528, 18608, 1807, 15782, 471, 1651, 1807, 1661, 17, 7398, 802, 5205, 9588, 777, 4271, 326, 1378, 518, 316, 326, 526, 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 ]
[ 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, 0 ]
[ 1, 225, 445, 527, 7802, 2115, 12, 1080, 3778, 18608, 548, 16, 533, 3778, 1651, 13, 1071, 288, 203, 377, 203, 565, 2583, 12, 16330, 1979, 4002, 63, 16330, 1979, 548, 65, 422, 638, 16, 315, 22834, 1979, 1297, 506, 4104, 1122, 1199, 1769, 203, 565, 2583, 12, 2816, 4002, 63, 2816, 65, 422, 629, 16, 315, 2310, 1297, 486, 1005, 4832, 326, 16766, 1199, 1769, 203, 203, 565, 777, 7802, 6499, 63, 16330, 1979, 548, 8009, 6206, 12, 7802, 2115, 12, 2816, 16, 2037, 10019, 203, 565, 1651, 4002, 63, 2816, 65, 273, 638, 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 ]
./partial_match/56/0x7044326135a8F416DD4a1d48Bc47f808879ed425/sources/StakingRewards.sol
========== STATE VARIABLES ========== */ ========== CONSTRUCTOR ========== */
constructor() public { rewardsDistribution = msg.sender; }
11,125,630
[ 1, 1432, 631, 7442, 22965, 55, 422, 1432, 342, 422, 1432, 3492, 13915, 916, 422, 1432, 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 ]
[ 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, 3885, 1435, 1071, 288, 203, 3639, 283, 6397, 9003, 273, 1234, 18, 15330, 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, -100, -100 ]
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; } } contract ERC20 { function transfer(address _to, uint256 _value) public; function transferFrom(address _from, address _to, uint256 _value) public returns(bool success); } contract EthTokenToSmthSwaps { using SafeMath for uint; address public owner; uint256 SafeTime = 1 hours; // atomic swap timeOut struct Swap { address token; address payable targetWallet; bytes32 secret; bytes20 secretHash; uint256 createdAt; uint256 balance; } // ETH Owner => BTC Owner => Swap mapping(address => mapping(address => Swap)) public swaps; // ETH Owner => BTC Owner => secretHash => Swap // mapping(address => mapping(address => mapping(bytes20 => Swap))) public swaps; constructor () public { owner = msg.sender; } event CreateSwap(address token, address _buyer, address _seller, uint256 _value, bytes20 _secretHash, uint256 createdAt); // ETH Owner creates Swap with secretHash // ETH Owner make token deposit function createSwap(bytes20 _secretHash, address payable _participantAddress, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, _participantAddress, bytes32(0), _secretHash, now, _value ); emit CreateSwap(_token, _participantAddress, msg.sender, _value, _secretHash, now); } // ETH Owner creates Swap with secretHash and targetWallet // ETH Owner make token deposit function createSwapTarget(bytes20 _secretHash, address payable _participantAddress, address payable _targetWallet, uint256 _value, address _token) public { require(_value > 0); require(swaps[msg.sender][_participantAddress].balance == uint256(0)); require(ERC20(_token).transferFrom(msg.sender, address(this), _value)); swaps[msg.sender][_participantAddress] = Swap( _token, _targetWallet, bytes32(0), _secretHash, now, _value ); emit CreateSwap(_token, _participantAddress, msg.sender, _value, _secretHash, now); } function getBalance(address _ownerAddress) public view returns (uint256) { return swaps[_ownerAddress][msg.sender].balance; } event Withdraw(address _buyer, address _seller, bytes20 _secretHash, uint256 withdrawnAt); // Get target wallet (buyer check) function getTargetWallet(address tokenOwnerAddress) public view returns (address) { return swaps[tokenOwnerAddress][msg.sender].targetWallet; } // BTC Owner withdraw money and adds secret key to swap // BTC Owner receive +1 reputation function withdraw(bytes32 _secret, address _ownerAddress) public { Swap memory swap = swaps[_ownerAddress][msg.sender]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[_ownerAddress][msg.sender].balance = 0; swaps[_ownerAddress][msg.sender].secret = _secret; emit Withdraw(msg.sender, _ownerAddress, swap.secretHash, now); } // Token Owner withdraw money when participan no money for gas and adds secret key to swap // BTC Owner receive +1 reputation... may be function withdrawNoMoney(bytes32 _secret, address participantAddress) public { Swap memory swap = swaps[msg.sender][participantAddress]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[msg.sender][participantAddress].balance = 0; swaps[msg.sender][participantAddress].secret = _secret; emit Withdraw(participantAddress, msg.sender, swap.secretHash, now); } // BTC Owner withdraw money and adds secret key to swap // BTC Owner receive +1 reputation function withdrawOther(bytes32 _secret, address _ownerAddress, address participantAddress) public { Swap memory swap = swaps[_ownerAddress][participantAddress]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[_ownerAddress][participantAddress].balance = 0; swaps[_ownerAddress][participantAddress].secret = _secret; emit Withdraw(participantAddress, _ownerAddress, swap.secretHash, now); } // ETH Owner receive secret function getSecret(address _participantAddress) public view returns (bytes32) { return swaps[msg.sender][_participantAddress].secret; } event Refund(address _buyer, address _seller, bytes20 _secretHash); // ETH Owner refund money // BTC Owner gets -1 reputation function refund(address _participantAddress) public { Swap memory swap = swaps[msg.sender][_participantAddress]; require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) < now); ERC20(swap.token).transfer(msg.sender, swap.balance); clean(msg.sender, _participantAddress); emit Refund(_participantAddress, msg.sender, swap.secretHash); } function clean(address _ownerAddress, address _participantAddress) internal { delete swaps[_ownerAddress][_participantAddress]; } }
BTC Owner withdraw money and adds secret key to swap BTC Owner receive +1 reputation
function withdraw(bytes32 _secret, address _ownerAddress) public { Swap memory swap = swaps[_ownerAddress][msg.sender]; require(swap.secretHash == ripemd160(abi.encodePacked(_secret))); require(swap.balance > uint256(0)); require(swap.createdAt.add(SafeTime) > now); ERC20(swap.token).transfer(swap.targetWallet, swap.balance); swaps[_ownerAddress][msg.sender].balance = 0; swaps[_ownerAddress][msg.sender].secret = _secret; emit Withdraw(msg.sender, _ownerAddress, swap.secretHash, now); }
5,527,142
[ 1, 38, 15988, 16837, 598, 9446, 15601, 471, 4831, 4001, 498, 358, 7720, 605, 15988, 16837, 6798, 397, 21, 283, 458, 367, 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 ]
[ 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, 0 ]
[ 1, 225, 445, 598, 9446, 12, 3890, 1578, 389, 5875, 16, 1758, 389, 8443, 1887, 13, 1071, 288, 203, 565, 12738, 3778, 7720, 273, 1352, 6679, 63, 67, 8443, 1887, 6362, 3576, 18, 15330, 15533, 203, 203, 565, 2583, 12, 22270, 18, 5875, 2310, 422, 436, 3151, 1264, 16874, 12, 21457, 18, 3015, 4420, 329, 24899, 5875, 3719, 1769, 203, 565, 2583, 12, 22270, 18, 12296, 405, 2254, 5034, 12, 20, 10019, 203, 565, 2583, 12, 22270, 18, 4824, 861, 18, 1289, 12, 9890, 950, 13, 405, 2037, 1769, 203, 203, 565, 4232, 39, 3462, 12, 22270, 18, 2316, 2934, 13866, 12, 22270, 18, 3299, 16936, 16, 7720, 18, 12296, 1769, 203, 203, 565, 1352, 6679, 63, 67, 8443, 1887, 6362, 3576, 18, 15330, 8009, 12296, 273, 374, 31, 203, 565, 1352, 6679, 63, 67, 8443, 1887, 6362, 3576, 18, 15330, 8009, 5875, 273, 389, 5875, 31, 203, 203, 565, 3626, 3423, 9446, 12, 3576, 18, 15330, 16, 389, 8443, 1887, 16, 7720, 18, 5875, 2310, 16, 2037, 1769, 203, 225, 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 ]
./full_match/1/0x89710b9B4076345BC89cfc6D5a0Bb10B73f15c7b/sources/contracts/rates/WeightedInterestRateModel.sol
*************************************************************************/ Constants */*************************************************************************/* @notice Fixed point scale/* @notice Maximum tick threshold (0.5)/* @notice Minimum tick exponential (0.25)/* @notice Maximum tick exponential (4.0)/*************************************************************************/ Structures */*************************************************************************/* @notice Parameters @param tickThreshold Tick interest threshold @param tickExponential Tick exponential base/
struct Parameters { uint64 tickThreshold; uint64 tickExponential; }
16,469,729
[ 1, 19, 5245, 368, 225, 15038, 1634, 3159, 19, 225, 18848, 4024, 5573, 261, 20, 18, 25, 13176, 225, 23456, 4024, 21774, 261, 20, 18, 2947, 13176, 225, 18848, 4024, 21774, 261, 24, 18, 20, 13, 759, 7362, 1823, 368, 225, 7012, 225, 4024, 7614, 13588, 16513, 5573, 225, 4024, 17972, 649, 13588, 21774, 1026, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 1958, 7012, 288, 203, 3639, 2254, 1105, 4024, 7614, 31, 203, 3639, 2254, 1105, 4024, 17972, 649, 31, 203, 565, 289, 203, 203, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/43114/0xc7d43CbAD8F3Dd5a628537475E4066970930948D/sources/contracts/WinterFarm.sol
Add a new lp to the pool. Can only be called by the owner.
function add(uint256 _allocPoint, IBEP20 _lpToken, uint16 _depositFeeBP, bool _withUpdate) public onlyOwner nonDuplicated(_lpToken) { require(_depositFeeBP <= maxDepositFeeBP, "add: invalid deposit fee basis points"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accSnowPerShare : 0, depositFeeBP : _depositFeeBP })); }
4,527,262
[ 1, 986, 279, 394, 12423, 358, 326, 2845, 18, 4480, 1338, 506, 2566, 635, 326, 3410, 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 ]
[ 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, 527, 12, 11890, 5034, 389, 9853, 2148, 16, 467, 5948, 52, 3462, 389, 9953, 1345, 16, 2254, 2313, 389, 323, 1724, 14667, 30573, 16, 1426, 389, 1918, 1891, 13, 1071, 1338, 5541, 1661, 19682, 690, 24899, 9953, 1345, 13, 288, 203, 3639, 2583, 24899, 323, 1724, 14667, 30573, 1648, 943, 758, 1724, 14667, 30573, 16, 315, 1289, 30, 2057, 443, 1724, 14036, 10853, 3143, 8863, 203, 203, 3639, 309, 261, 67, 1918, 1891, 13, 288, 203, 5411, 8039, 1891, 16639, 5621, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 1142, 17631, 1060, 1768, 273, 1203, 18, 2696, 405, 787, 1768, 692, 1203, 18, 2696, 294, 787, 1768, 31, 203, 3639, 2078, 8763, 2148, 273, 2078, 8763, 2148, 18, 1289, 24899, 9853, 2148, 1769, 203, 3639, 2845, 4786, 802, 63, 67, 9953, 1345, 65, 273, 638, 31, 203, 3639, 2845, 966, 18, 6206, 12, 2864, 966, 12590, 203, 3639, 12423, 1345, 294, 389, 9953, 1345, 16, 203, 3639, 4767, 2148, 294, 389, 9853, 2148, 16, 203, 3639, 1142, 17631, 1060, 1768, 294, 1142, 17631, 1060, 1768, 16, 203, 3639, 4078, 55, 3338, 2173, 9535, 294, 374, 16, 203, 3639, 443, 1724, 14667, 30573, 294, 389, 323, 1724, 14667, 30573, 203, 3639, 289, 10019, 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 ]
pragma solidity ^0.4.4; /* * Copyright© (2018-2019) WeBank Co., Ltd. * * This file is part of weidentity-contract. * * weidentity-contract is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * weidentity-contract 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 Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with weidentity-contract. If not, see <https://www.gnu.org/licenses/>. */ import "./AuthorityIssuerData.sol"; import "./RoleController.sol"; /** * @title AuthorityIssuerController * Issuer contract manages authority issuer info. */ contract AuthorityIssuerController { AuthorityIssuerData private authorityIssuerData; RoleController private roleController; // Event structure to store tx records uint constant private OPERATION_ADD = 0; uint constant private OPERATION_REMOVE = 1; uint constant private EMPTY_ARRAY_SIZE = 1; event AuthorityIssuerRetLog(uint operation, uint retCode, address addr); // Constructor. function AuthorityIssuerController( address authorityIssuerDataAddress, address roleControllerAddress ) public { authorityIssuerData = AuthorityIssuerData(authorityIssuerDataAddress); roleController = RoleController(roleControllerAddress); } function addAuthorityIssuer( address addr, bytes32[16] attribBytes32, int[16] attribInt, bytes accValue ) public { uint result = authorityIssuerData.addAuthorityIssuerFromAddress(addr, attribBytes32, attribInt, accValue); AuthorityIssuerRetLog(OPERATION_ADD, result, addr); } function recognizeAuthorityIssuer(address addr) public { uint result = authorityIssuerData.recognizeAuthorityIssuer(addr); AuthorityIssuerRetLog(OPERATION_ADD, result, addr); } function deRecognizeAuthorityIssuer(address addr) public { uint result = authorityIssuerData.deRecognizeAuthorityIssuer(addr); AuthorityIssuerRetLog(OPERATION_REMOVE, result, addr); } function removeAuthorityIssuer(address addr) public { if (!roleController.checkPermission(tx.origin, roleController.MODIFY_AUTHORITY_ISSUER())) { AuthorityIssuerRetLog(OPERATION_REMOVE, roleController.RETURN_CODE_FAILURE_NO_PERMISSION(), addr); return; } uint result = authorityIssuerData.deleteAuthorityIssuerFromAddress(addr); AuthorityIssuerRetLog(OPERATION_REMOVE, result, addr); } function getTotalIssuer() public constant returns (uint) { return authorityIssuerData.getDatasetLength(); } function getAuthorityIssuerAddressList( uint startPos, uint num ) public constant returns (address[]) { uint totalLength = authorityIssuerData.getDatasetLength(); uint dataLength; // Calculate actual dataLength if (totalLength < startPos) { return new address[](EMPTY_ARRAY_SIZE); } else if (totalLength <= startPos + num) { dataLength = totalLength - startPos; } else { dataLength = num; } address[] memory issuerArray = new address[](dataLength); for (uint index = 0; index < dataLength; index++) { issuerArray[index] = authorityIssuerData.getAuthorityIssuerFromIndex(startPos + index); } return issuerArray; } function getAuthorityIssuerInfoNonAccValue( address addr ) public constant returns (bytes32[], int[]) { // Due to the current limitations of bcos web3j, return dynamic bytes32 and int array instead. bytes32[16] memory allBytes32; int[16] memory allInt; (allBytes32, allInt) = authorityIssuerData.getAuthorityIssuerInfoNonAccValue(addr); bytes32[] memory finalBytes32 = new bytes32[](16); int[] memory finalInt = new int[](16); for (uint index = 0; index < 16; index++) { finalBytes32[index] = allBytes32[index]; finalInt[index] = allInt[index]; } return (finalBytes32, finalInt); } function isAuthorityIssuer( address addr ) public constant returns (bool) { return authorityIssuerData.isAuthorityIssuer(addr); } function getAddressFromName( bytes32 name ) public constant returns (address) { return authorityIssuerData.getAddressFromName(name); } }
Event structure to store tx records Constructor.
contract AuthorityIssuerController { AuthorityIssuerData private authorityIssuerData; RoleController private roleController; uint constant private OPERATION_ADD = 0; uint constant private OPERATION_REMOVE = 1; uint constant private EMPTY_ARRAY_SIZE = 1; event AuthorityIssuerRetLog(uint operation, uint retCode, address addr); function AuthorityIssuerController( address authorityIssuerDataAddress, address roleControllerAddress ) public { authorityIssuerData = AuthorityIssuerData(authorityIssuerDataAddress); roleController = RoleController(roleControllerAddress); } function addAuthorityIssuer( address addr, bytes32[16] attribBytes32, int[16] attribInt, bytes accValue ) public { uint result = authorityIssuerData.addAuthorityIssuerFromAddress(addr, attribBytes32, attribInt, accValue); AuthorityIssuerRetLog(OPERATION_ADD, result, addr); } function recognizeAuthorityIssuer(address addr) public { uint result = authorityIssuerData.recognizeAuthorityIssuer(addr); AuthorityIssuerRetLog(OPERATION_ADD, result, addr); } function deRecognizeAuthorityIssuer(address addr) public { uint result = authorityIssuerData.deRecognizeAuthorityIssuer(addr); AuthorityIssuerRetLog(OPERATION_REMOVE, result, addr); } function removeAuthorityIssuer(address addr) public { if (!roleController.checkPermission(tx.origin, roleController.MODIFY_AUTHORITY_ISSUER())) { AuthorityIssuerRetLog(OPERATION_REMOVE, roleController.RETURN_CODE_FAILURE_NO_PERMISSION(), addr); return; } uint result = authorityIssuerData.deleteAuthorityIssuerFromAddress(addr); AuthorityIssuerRetLog(OPERATION_REMOVE, result, addr); } function removeAuthorityIssuer(address addr) public { if (!roleController.checkPermission(tx.origin, roleController.MODIFY_AUTHORITY_ISSUER())) { AuthorityIssuerRetLog(OPERATION_REMOVE, roleController.RETURN_CODE_FAILURE_NO_PERMISSION(), addr); return; } uint result = authorityIssuerData.deleteAuthorityIssuerFromAddress(addr); AuthorityIssuerRetLog(OPERATION_REMOVE, result, addr); } function getTotalIssuer() public constant returns (uint) { return authorityIssuerData.getDatasetLength(); } function getAuthorityIssuerAddressList( uint startPos, uint num ) public constant returns (address[]) { uint totalLength = authorityIssuerData.getDatasetLength(); uint dataLength; if (totalLength < startPos) { return new address[](EMPTY_ARRAY_SIZE); dataLength = totalLength - startPos; dataLength = num; } address[] memory issuerArray = new address[](dataLength); for (uint index = 0; index < dataLength; index++) { issuerArray[index] = authorityIssuerData.getAuthorityIssuerFromIndex(startPos + index); } return issuerArray; } function getAuthorityIssuerAddressList( uint startPos, uint num ) public constant returns (address[]) { uint totalLength = authorityIssuerData.getDatasetLength(); uint dataLength; if (totalLength < startPos) { return new address[](EMPTY_ARRAY_SIZE); dataLength = totalLength - startPos; dataLength = num; } address[] memory issuerArray = new address[](dataLength); for (uint index = 0; index < dataLength; index++) { issuerArray[index] = authorityIssuerData.getAuthorityIssuerFromIndex(startPos + index); } return issuerArray; } } else if (totalLength <= startPos + num) { } else { function getAuthorityIssuerAddressList( uint startPos, uint num ) public constant returns (address[]) { uint totalLength = authorityIssuerData.getDatasetLength(); uint dataLength; if (totalLength < startPos) { return new address[](EMPTY_ARRAY_SIZE); dataLength = totalLength - startPos; dataLength = num; } address[] memory issuerArray = new address[](dataLength); for (uint index = 0; index < dataLength; index++) { issuerArray[index] = authorityIssuerData.getAuthorityIssuerFromIndex(startPos + index); } return issuerArray; } function getAuthorityIssuerInfoNonAccValue( address addr ) public constant returns (bytes32[], int[]) { bytes32[16] memory allBytes32; int[16] memory allInt; (allBytes32, allInt) = authorityIssuerData.getAuthorityIssuerInfoNonAccValue(addr); bytes32[] memory finalBytes32 = new bytes32[](16); int[] memory finalInt = new int[](16); for (uint index = 0; index < 16; index++) { finalBytes32[index] = allBytes32[index]; finalInt[index] = allInt[index]; } return (finalBytes32, finalInt); } function getAuthorityIssuerInfoNonAccValue( address addr ) public constant returns (bytes32[], int[]) { bytes32[16] memory allBytes32; int[16] memory allInt; (allBytes32, allInt) = authorityIssuerData.getAuthorityIssuerInfoNonAccValue(addr); bytes32[] memory finalBytes32 = new bytes32[](16); int[] memory finalInt = new int[](16); for (uint index = 0; index < 16; index++) { finalBytes32[index] = allBytes32[index]; finalInt[index] = allInt[index]; } return (finalBytes32, finalInt); } function isAuthorityIssuer( address addr ) public constant returns (bool) { return authorityIssuerData.isAuthorityIssuer(addr); } function getAddressFromName( bytes32 name ) public constant returns (address) { return authorityIssuerData.getAddressFromName(name); } }
1,037,014
[ 1, 1133, 3695, 358, 1707, 2229, 3853, 11417, 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, 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, 16351, 6712, 560, 16667, 2933, 288, 203, 203, 565, 6712, 560, 16667, 751, 3238, 11675, 16667, 751, 31, 203, 565, 6204, 2933, 3238, 2478, 2933, 31, 203, 203, 565, 2254, 5381, 3238, 31294, 67, 8355, 273, 374, 31, 203, 565, 2254, 5381, 3238, 31294, 67, 22122, 273, 404, 31, 203, 565, 2254, 5381, 3238, 8984, 67, 8552, 67, 4574, 273, 404, 31, 203, 203, 565, 871, 6712, 560, 16667, 7055, 1343, 12, 11890, 1674, 16, 2254, 325, 1085, 16, 1758, 3091, 1769, 203, 203, 565, 445, 6712, 560, 16667, 2933, 12, 203, 3639, 1758, 11675, 16667, 751, 1887, 16, 203, 3639, 1758, 2478, 2933, 1887, 203, 565, 262, 7010, 3639, 1071, 7010, 203, 203, 565, 288, 203, 3639, 11675, 16667, 751, 273, 6712, 560, 16667, 751, 12, 24763, 16667, 751, 1887, 1769, 203, 3639, 2478, 2933, 273, 6204, 2933, 12, 4615, 2933, 1887, 1769, 203, 565, 289, 203, 203, 565, 445, 527, 10962, 16667, 12, 203, 3639, 1758, 3091, 16, 203, 3639, 1731, 1578, 63, 2313, 65, 5885, 2160, 1578, 16, 203, 3639, 509, 63, 2313, 65, 5885, 1702, 16, 203, 3639, 1731, 4078, 620, 203, 565, 262, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2254, 563, 273, 11675, 16667, 751, 18, 1289, 10962, 16667, 1265, 1887, 12, 4793, 16, 5885, 2160, 1578, 16, 5885, 1702, 16, 4078, 620, 1769, 203, 3639, 6712, 560, 16667, 7055, 1343, 12, 22040, 67, 8355, 16, 563, 16, 3091, 1769, 203, 565, 289, 203, 377, 203, 565, 445, 21431, 10962, 16667, 12, 2867, 3091, 13, 1071, 288, 2 ]
./full_match/4/0x19D59Ea6A136Cc5Fd55e09b2Bacc745B2a0B4eE8/sources/contracts/interfaces/ICommunity.sol
* @notice checks trustedForwarder on HomeFi contract @param _forwarder address of contract forwarding meta tx/
function isTrustedForwarder(address _forwarder) public view override returns (bool) { return homeFiInstance.isTrustedForwarder(_forwarder); }
671,274
[ 1, 12366, 13179, 30839, 603, 21321, 42, 77, 6835, 225, 389, 1884, 20099, 1758, 434, 6835, 20635, 2191, 2229, 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, 353, 16950, 30839, 12, 2867, 389, 1884, 20099, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 3849, 203, 3639, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 6382, 42, 77, 1442, 18, 291, 16950, 30839, 24899, 1884, 20099, 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 ]
./full_match/1/0xAE20BC46300BAb5d85612C6BC6EA87eA0F186035/sources/all_crfi.sol
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") keccak256("ERC777TokensRecipient") only effect erc20 interface. when erc777mode equal 0, the erc777 feature is disabled; when erc777mode equal 1, the erc777 feature is enabled by whitelist. when erc777 mode equal 2, the erc777 feature is disabled by blacklist. when erc777 mode equal 3, the erc777 feature is enabled; in whitelist or black list mode, whether "from" or "to" address in list, the feature would be effected. ERC20-allowances This isn't ever read from - it's only used to respond to the defaultOperators query. Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). For each account, a mapping of its operators and revoked default operators.
contract CRFI is Context, IERC777, IERC20,IERC777Recipient { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; address public superAdmin; mapping(address => uint256) public admins; Erc777ModeType public erc777Mode; mapping(address=>bool) public blacklist; mapping(address=>bool) public whitelist; mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; mapping (address => mapping (address => uint256)) private _allowances; mapping(address=>bool) private _freezeAddress; address[] private _defaultOperatorsArray; mapping(address => bool) private _defaultOperators; mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; constructor(address[] memory defaultOperators_ ) } enum Erc777ModeType {disabled, whitelist, blacklist, enabled} { _name = "CrossFi"; _symbol = "CRFI"; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); superAdmin = msg.sender; _ERC1820_REGISTRY.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); _mint(msg.sender, 1e26, "", ""); } { _name = "CrossFi"; _symbol = "CRFI"; _defaultOperatorsArray = defaultOperators_; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); superAdmin = msg.sender; _ERC1820_REGISTRY.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); _mint(msg.sender, 1e26, "", ""); } _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); ChangeMode(Erc777ModeType.disabled); modifier IsAdmin() { require(msg.sender == superAdmin || admins[msg.sender] == 1, "only admin"); _; } modifier IsSuperAdmin() { require(superAdmin == msg.sender, "only super admin"); _; } modifier CheckFreeze(address addr){ require(_freezeAddress[addr] == false, "account is freeze"); _; } function AddAdmin(address adminAddr) public IsSuperAdmin(){ require(admins[adminAddr] == 0, "already add this admin"); admins[adminAddr] = 1; } function DelAdmin(address adminAddr) public IsSuperAdmin(){ require(admins[adminAddr] == 1, "this addr is not admin"); admins[adminAddr] = 0; } function ChangeSuperAdmin(address suAdminAddr) public IsSuperAdmin(){ require(suAdminAddr != address(0x0), "empty new super admin"); superAdmin = suAdminAddr; } function AddBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(blacklist[addr]){ continue; } blacklist[addr] = true; } } function AddBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(blacklist[addr]){ continue; } blacklist[addr] = true; } } function AddBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(blacklist[addr]){ continue; } blacklist[addr] = true; } } function DelBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!blacklist[addr]){ continue; } blacklist[addr] = false; } } function DelBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!blacklist[addr]){ continue; } blacklist[addr] = false; } } function DelBlackList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!blacklist[addr]){ continue; } blacklist[addr] = false; } } function AddWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(whitelist[addr]){ continue; } whitelist[addr] = true; } } function AddWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(whitelist[addr]){ continue; } whitelist[addr] = true; } } function AddWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(whitelist[addr]){ continue; } whitelist[addr] = true; } } function DelWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!whitelist[addr] ){ continue; } whitelist[addr] = false; } } function DelWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!whitelist[addr] ){ continue; } whitelist[addr] = false; } } function DelWhiteList(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(!whitelist[addr] ){ continue; } whitelist[addr] = false; } } function ChangeMode(Erc777ModeType mode) public IsAdmin(){ erc777Mode = mode; } function FreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == true){ continue; } _freezeAddress[addr] = true; } } function FreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == true){ continue; } _freezeAddress[addr] = true; } } function FreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == true){ continue; } _freezeAddress[addr] = true; } } function UnfreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == false){ continue; } _freezeAddress[addr] = false; } } function UnfreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == false){ continue; } _freezeAddress[addr] = false; } } function UnfreezeAddr(address[] memory addrs) public IsAdmin(){ for(uint256 i = 0; i < addrs.length; i++){ address addr = addrs[i]; if(_freezeAddress[addr] == false){ continue; } _freezeAddress[addr] = false; } } function name() public view virtual override returns (string memory) { return _name; } function symbol() public view virtual override returns (string memory) { return _symbol; } function decimals() public pure virtual returns (uint8) { return 18; } function granularity() public view virtual override returns (uint256) { return 1; } function totalSupply() public view virtual override(IERC20, IERC777) returns (uint256) { return _totalSupply; } function balanceOf(address tokenHolder) public view virtual override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData) public pure override{ revert("can't receive any coin"); } function send(address recipient, uint256 amount, bytes memory data) public virtual override CheckFreeze(_msgSender()){ _send(_msgSender(), recipient, amount, data, "", true); } function transfer(address recipient, uint256 amount) public virtual override CheckFreeze(_msgSender()) returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); bool erc777Enable = _enableERC777(from, recipient); if(erc777Enable){ _callTokensToSend(from, from, recipient, amount, "", ""); } _move(from, from, recipient, amount, "", "", erc777Enable); if(erc777Enable){ _callTokensReceived(from, from, recipient, amount, "", "", false); } return true; } function transfer(address recipient, uint256 amount) public virtual override CheckFreeze(_msgSender()) returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); bool erc777Enable = _enableERC777(from, recipient); if(erc777Enable){ _callTokensToSend(from, from, recipient, amount, "", ""); } _move(from, from, recipient, amount, "", "", erc777Enable); if(erc777Enable){ _callTokensReceived(from, from, recipient, amount, "", "", false); } return true; } function transfer(address recipient, uint256 amount) public virtual override CheckFreeze(_msgSender()) returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); bool erc777Enable = _enableERC777(from, recipient); if(erc777Enable){ _callTokensToSend(from, from, recipient, amount, "", ""); } _move(from, from, recipient, amount, "", "", erc777Enable); if(erc777Enable){ _callTokensReceived(from, from, recipient, amount, "", "", false); } return true; } function burn(uint256 amount, bytes memory data) public virtual override CheckFreeze(_msgSender()){ _burn(_msgSender(), amount, data, ""); } function isOperatorFor(address operator, address tokenHolder) public view virtual override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } function authorizeOperator(address operator) public virtual override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } } else { function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } function revokeOperator(address operator) public virtual override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } } else { function defaultOperators() public view virtual override returns (address[] memory) { return _defaultOperatorsArray; } function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public virtual override CheckFreeze(sender) { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public virtual override CheckFreeze(account){ require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } function allowance(address holder, address spender) public view virtual override returns (uint256) { return _allowances[holder][spender]; } function approve(address spender, uint256 value) public virtual override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } function transferFrom(address holder, address recipient, uint256 amount) public virtual override CheckFreeze(holder) 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(); bool erc777Enable = _enableERC777(holder, recipient); if(erc777Enable){ _callTokensToSend(spender, holder, recipient, amount, "", ""); } _move(spender, holder, recipient, amount, "", "", erc777Enable); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); if(erc777Enable){ _callTokensReceived(spender, holder, recipient, amount, "", "", false); } return true; } function transferFrom(address holder, address recipient, uint256 amount) public virtual override CheckFreeze(holder) 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(); bool erc777Enable = _enableERC777(holder, recipient); if(erc777Enable){ _callTokensToSend(spender, holder, recipient, amount, "", ""); } _move(spender, holder, recipient, amount, "", "", erc777Enable); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); if(erc777Enable){ _callTokensReceived(spender, holder, recipient, amount, "", "", false); } return true; } function transferFrom(address holder, address recipient, uint256 amount) public virtual override CheckFreeze(holder) 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(); bool erc777Enable = _enableERC777(holder, recipient); if(erc777Enable){ _callTokensToSend(spender, holder, recipient, amount, "", ""); } _move(spender, holder, recipient, amount, "", "", erc777Enable); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); if(erc777Enable){ _callTokensReceived(spender, holder, recipient, amount, "", "", false); } return true; } 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); _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); } function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal virtual { 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, true); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } 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(); _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); _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, bool erc777Enable ) private { if(erc777Enable){ _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); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool erc777Enable ) private { if(erc777Enable){ _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); } 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); } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) private { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } } else if (requireReceptionAck) { function _beforeTokenTransfer(address operator, address from, address to, uint256 amount) internal virtual { } function _enableERC777(address from, address to) internal view returns(bool){ if(erc777Mode == Erc777ModeType.disabled){ return false; } if(erc777Mode == Erc777ModeType.enabled){ return true; } if(erc777Mode == Erc777ModeType.whitelist){ return whitelist[from] || whitelist[to]; } if(erc777Mode == Erc777ModeType.blacklist){ return (!blacklist[from]) && (!blacklist[to]); } return false; } function _enableERC777(address from, address to) internal view returns(bool){ if(erc777Mode == Erc777ModeType.disabled){ return false; } if(erc777Mode == Erc777ModeType.enabled){ return true; } if(erc777Mode == Erc777ModeType.whitelist){ return whitelist[from] || whitelist[to]; } if(erc777Mode == Erc777ModeType.blacklist){ return (!blacklist[from]) && (!blacklist[to]); } return false; } function _enableERC777(address from, address to) internal view returns(bool){ if(erc777Mode == Erc777ModeType.disabled){ return false; } if(erc777Mode == Erc777ModeType.enabled){ return true; } if(erc777Mode == Erc777ModeType.whitelist){ return whitelist[from] || whitelist[to]; } if(erc777Mode == Erc777ModeType.blacklist){ return (!blacklist[from]) && (!blacklist[to]); } return false; } function _enableERC777(address from, address to) internal view returns(bool){ if(erc777Mode == Erc777ModeType.disabled){ return false; } if(erc777Mode == Erc777ModeType.enabled){ return true; } if(erc777Mode == Erc777ModeType.whitelist){ return whitelist[from] || whitelist[to]; } if(erc777Mode == Erc777ModeType.blacklist){ return (!blacklist[from]) && (!blacklist[to]); } return false; } function _enableERC777(address from, address to) internal view returns(bool){ if(erc777Mode == Erc777ModeType.disabled){ return false; } if(erc777Mode == Erc777ModeType.enabled){ return true; } if(erc777Mode == Erc777ModeType.whitelist){ return whitelist[from] || whitelist[to]; } if(erc777Mode == Erc777ModeType.blacklist){ return (!blacklist[from]) && (!blacklist[to]); } return false; } }
9,756,927
[ 1, 3218, 6370, 326, 563, 434, 326, 3751, 9869, 2724, 348, 7953, 560, 3302, 1404, 2245, 2182, 622, 4074, 813, 18, 2164, 2333, 30, 6662, 18, 832, 19, 546, 822, 379, 19, 30205, 560, 19, 9618, 19, 24, 3103, 24, 18, 417, 24410, 581, 5034, 2932, 654, 39, 14509, 5157, 12021, 7923, 417, 24410, 581, 5034, 2932, 654, 39, 14509, 5157, 18241, 7923, 1338, 5426, 6445, 71, 3462, 1560, 18, 1347, 6445, 71, 14509, 3188, 3959, 374, 16, 326, 6445, 71, 14509, 2572, 353, 5673, 31, 1347, 6445, 71, 14509, 3188, 3959, 404, 16, 326, 6445, 71, 14509, 2572, 353, 3696, 635, 10734, 18, 1347, 6445, 71, 14509, 1965, 3959, 576, 16, 326, 6445, 71, 14509, 2572, 353, 5673, 635, 11709, 18, 1347, 6445, 71, 14509, 1965, 3959, 890, 16, 326, 6445, 71, 14509, 2572, 353, 3696, 31, 316, 10734, 578, 7721, 666, 1965, 16, 2856, 315, 2080, 6, 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, 6732, 1653, 353, 1772, 16, 467, 654, 39, 14509, 16, 467, 654, 39, 3462, 16, 45, 654, 39, 14509, 18241, 288, 203, 21281, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 225, 1450, 5267, 364, 1758, 31, 203, 203, 225, 467, 654, 39, 2643, 3462, 4243, 5381, 2713, 389, 654, 39, 2643, 3462, 67, 5937, 25042, 273, 467, 654, 39, 2643, 3462, 4243, 12, 20, 92, 2643, 3462, 69, 24, 38, 6669, 2643, 38, 72, 41, 11212, 40, 311, 28, 4315, 71, 9036, 69, 2090, 26, 39, 29, 6162, 6260, 507, 40, 3247, 1769, 203, 21281, 203, 225, 1731, 1578, 5381, 3238, 389, 8412, 55, 67, 1090, 18556, 67, 18865, 67, 15920, 273, 203, 565, 374, 92, 5540, 449, 70, 25, 6675, 70, 21, 19192, 25, 7142, 27, 8522, 5520, 7616, 9498, 71, 21, 361, 74, 25, 74, 28, 71, 1105, 6564, 6669, 21, 361, 74, 7235, 25, 73, 9599, 3030, 26262, 74, 26, 8204, 378, 73, 6675, 25, 31, 203, 203, 225, 1731, 1578, 5381, 3238, 389, 8412, 55, 67, 862, 7266, 1102, 2222, 67, 18865, 67, 15920, 273, 203, 565, 374, 6114, 6030, 21, 7142, 28, 71, 24886, 6564, 72, 22, 2947, 6334, 1966, 7950, 323, 23, 24872, 69, 5520, 5324, 6030, 8778, 70, 26035, 69, 7140, 22, 70, 23, 3461, 74, 29, 952, 6669, 22, 73, 6334, 71, 8643, 70, 31, 203, 203, 225, 1758, 1071, 2240, 4446, 31, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 31116, 31, 203, 203, 225, 512, 1310, 14509, 2309, 559, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-11-20 */ // SPDX-License-Identifier: AGPL-3.0-or-later pragma solidity 0.7.5; interface IOwnable { function policy() external view returns (address); function renounceManagement() external; function pushManagement( address newOwner_ ) external; function pullManagement() external; } contract Ownable is IOwnable { address internal _owner; address internal _newOwner; event OwnershipPushed(address indexed previousOwner, address indexed newOwner); event OwnershipPulled(address indexed previousOwner, address indexed newOwner); constructor () { _owner = msg.sender; emit OwnershipPushed( address(0), _owner ); } function policy() public view override returns (address) { return _owner; } modifier onlyPolicy() { require( _owner == msg.sender, "Ownable: caller is not the owner" ); _; } function renounceManagement() public virtual override onlyPolicy() { emit OwnershipPushed( _owner, address(0) ); _owner = address(0); } function pushManagement( address newOwner_ ) public virtual override onlyPolicy() { require( newOwner_ != address(0), "Ownable: new owner is the zero address"); emit OwnershipPushed( _owner, newOwner_ ); _newOwner = newOwner_; } function pullManagement() public virtual override { require( msg.sender == _newOwner, "Ownable: must be new owner to pull"); emit OwnershipPulled( _owner, _newOwner ); _owner = _newOwner; } } library SafeMath { function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } function sub32(uint32 a, uint32 b) internal pure returns (uint32) { return sub32(a, b, "SafeMath: subtraction overflow"); } function sub32(uint32 a, uint32 b, string memory errorMessage) internal pure returns (uint32) { require(b <= a, errorMessage); uint32 c = a - b; return c; } 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; } function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } function sqrrt(uint256 a) internal pure returns (uint c) { if (a > 3) { c = a; uint b = add( div( a, 2), 1 ); while (b < c) { c = b; b = div( add( div( a, b ), b), 2 ); } } else if (a != 0) { c = 1; } } } library Address { function isContract(address account) internal view returns (bool) { uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } 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"); } 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); } 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); } } } function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } 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); } function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } 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 { if (returndata.length > 0) { assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } function addressToString(address _address) internal pure returns(string memory) { bytes32 _bytes = bytes32(uint256(_address)); bytes memory HEX = "0123456789abcdef"; bytes memory _addr = new bytes(42); _addr[0] = '0'; _addr[1] = 'x'; for(uint256 i = 0; i < 20; i++) { _addr[2+i*2] = HEX[uint8(_bytes[i + 12] >> 4)]; _addr[3+i*2] = HEX[uint8(_bytes[i + 12] & 0x0f)]; } return string(_addr); } } interface IERC20 { function decimals() external view returns (uint8); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } abstract contract ERC20 is IERC20 { using SafeMath for uint256; // TODO comment actual hash value. bytes32 constant private ERC20TOKEN_ERC1820_INTERFACE_ID = keccak256( "ERC20Token" ); mapping (address => uint256) internal _balances; mapping (address => mapping (address => uint256)) internal _allowances; uint256 internal _totalSupply; string internal _name; string internal _symbol; uint8 internal _decimals; constructor (string memory name_, string memory symbol_, uint8 decimals_) { _name = name_; _symbol = symbol_; _decimals = decimals_; } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view override returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(msg.sender, spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, msg.sender, _allowances[sender][msg.sender] .sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender].add(addedValue)); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] .sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } function _mint(address account_, uint256 ammount_) internal virtual { require(account_ != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address( this ), account_, ammount_); _totalSupply = _totalSupply.add(ammount_); _balances[account_] = _balances[account_].add(ammount_); emit Transfer(address( this ), account_, ammount_); } function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } 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); } function _beforeTokenTransfer( address from_, address to_, uint256 amount_ ) internal virtual { } } interface IERC2612Permit { function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function nonces(address owner) external view returns (uint256); } library Counters { using SafeMath for uint256; struct Counter { 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); } } abstract contract ERC20Permit is ERC20, IERC2612Permit { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 public constant PERMIT_TYPEHASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; bytes32 public DOMAIN_SEPARATOR; constructor() { uint256 chainID; assembly { chainID := chainid() } DOMAIN_SEPARATOR = keccak256( abi.encode( keccak256("EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)"), keccak256(bytes(name())), keccak256(bytes("1")), // Version chainID, address(this) ) ); } function permit( address owner, address spender, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "Permit: expired deadline"); bytes32 hashStruct = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, _nonces[owner].current(), deadline)); bytes32 _hash = keccak256(abi.encodePacked(uint16(0x1901), DOMAIN_SEPARATOR, hashStruct)); address signer = ecrecover(_hash, v, r, s); require(signer != address(0) && signer == owner, "ZeroSwapPermit: Invalid signature"); _nonces[owner].increment(); _approve(owner, spender, amount); } function nonces(address owner) public view override returns (uint256) { return _nonces[owner].current(); } } 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)); } function safeApprove(IERC20 token, address spender, uint256 value) internal { 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)); } function _callOptionalReturn(IERC20 token, bytes memory data) private { 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"); } } } library FullMath { function fullMul(uint256 x, uint256 y) private pure returns (uint256 l, uint256 h) { uint256 mm = mulmod(x, y, uint256(-1)); l = x * y; h = mm - l; if (mm < l) h -= 1; } function fullDiv( uint256 l, uint256 h, uint256 d ) private pure returns (uint256) { uint256 pow2 = d & -d; d /= pow2; l /= pow2; l += h * ((-pow2) / pow2 + 1); uint256 r = 1; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; r *= 2 - d * r; return l * r; } function mulDiv( uint256 x, uint256 y, uint256 d ) internal pure returns (uint256) { (uint256 l, uint256 h) = fullMul(x, y); uint256 mm = mulmod(x, y, d); if (mm > l) h -= 1; l -= mm; require(h < d, 'FullMath::mulDiv: overflow'); return fullDiv(l, h, d); } } library FixedPoint { struct uq112x112 { uint224 _x; } struct uq144x112 { uint256 _x; } uint8 private constant RESOLUTION = 112; uint256 private constant Q112 = 0x10000000000000000000000000000; uint256 private constant Q224 = 0x100000000000000000000000000000000000000000000000000000000; uint256 private constant LOWER_MASK = 0xffffffffffffffffffffffffffff; // decimal of UQ*x112 (lower 112 bits) function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } function decode112with18(uq112x112 memory self) internal pure returns (uint) { return uint(self._x) / 5192296858534827; } function fraction(uint256 numerator, uint256 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, 'FixedPoint::fraction: division by zero'); if (numerator == 0) return FixedPoint.uq112x112(0); if (numerator <= uint144(-1)) { uint256 result = (numerator << RESOLUTION) / denominator; require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } else { uint256 result = FullMath.mulDiv(numerator, Q112, denominator); require(result <= uint224(-1), 'FixedPoint::fraction: overflow'); return uq112x112(uint224(result)); } } } interface ITreasury { function deposit( uint _amount, address _token, uint _profit ) external returns ( bool ); function valueOf( address _token, uint _amount ) external view returns ( uint value_ ); } interface IBondCalculator { function valuation( address _LP, uint _amount ) external view returns ( uint ); function markdown( address _LP ) external view returns ( uint ); } interface IStaking { function stake( uint _amount, address _recipient ) external returns ( bool ); } interface IStakingHelper { function stake( uint _amount, address _recipient ) external; } contract DawgstasBondDepository is Ownable { using FixedPoint for *; using SafeERC20 for IERC20; using SafeMath for uint; using SafeMath for uint32; /* ======== EVENTS ======== */ event BondCreated( uint deposit, uint indexed payout, uint indexed expires, uint indexed priceInUSD ); event BondRedeemed( address indexed recipient, uint payout, uint remaining ); event BondPriceChanged( uint indexed priceInUSD, uint indexed internalPrice, uint indexed debtRatio ); event ControlVariableAdjustment( uint initialBCV, uint newBCV, uint adjustment, bool addition ); /* ======== STATE VARIABLES ======== */ address public immutable Dawgsta; // token given as payment for bond address public immutable principle; // token used to create bond address public immutable treasury; // mints OHM when receives principle address public immutable DAO; // receives profit share from bond bool public immutable isLiquidityBond; // LP and Reserve bonds are treated slightly different address public immutable bondCalculator; // calculates value of LP tokens address public staking; // to auto-stake payout address public stakingHelper; // to stake and claim if no staking warmup bool public useHelper; Terms public terms; // stores terms for new bonds Adjust public adjustment; // stores adjustment to BCV data mapping( address => Bond ) public bondInfo; // stores bond information for depositors uint public totalDebt; // total value of outstanding bonds; used for pricing uint32 public lastDecay; // reference time for debt decay /* ======== STRUCTS ======== */ // Info for creating new bonds struct Terms { uint controlVariable; // scaling variable for price uint minimumPrice; // vs principle value uint maxPayout; // in thousandths of a %. i.e. 500 = 0.5% uint fee; // as % of bond payout, in hundreths. ( 500 = 5% = 0.05 for every 1 paid) uint maxDebt; // 9 decimal debt ratio, max % total supply created as debt uint32 vestingTerm; // in seconds } // Info for bond holder struct Bond { uint payout; // OHM remaining to be paid uint pricePaid; // In DAI, for front end viewing uint32 lastTime; // Last interaction uint32 vesting; // Seconds left to vest } // Info for incremental adjustments to control variable struct Adjust { bool add; // addition or subtraction uint rate; // increment uint target; // BCV when adjustment finished uint32 buffer; // minimum length (in seconds) between adjustments uint32 lastTime; // time when last adjustment made } /* ======== INITIALIZATION ======== */ constructor ( address _Dawgsta, address _principle, address _treasury, address _DAO, address _bondCalculator ) { require( _Dawgsta != address(0) ); Dawgsta = _Dawgsta; require( _principle != address(0) ); principle = _principle; require( _treasury != address(0) ); treasury = _treasury; require( _DAO != address(0) ); DAO = _DAO; // bondCalculator should be address(0) if not LP bond bondCalculator = _bondCalculator; isLiquidityBond = ( _bondCalculator != address(0) ); } /** * @notice initializes bond parameters * @param _controlVariable uint * @param _vestingTerm uint32 * @param _minimumPrice uint * @param _maxPayout uint * @param _fee uint * @param _maxDebt uint * @param _initialDebt uint */ function initializeBondTerms( uint _controlVariable, uint _minimumPrice, uint _maxPayout, uint _fee, uint _maxDebt, uint _initialDebt, uint32 _vestingTerm ) external onlyPolicy() { require( terms.controlVariable == 0, "Bonds must be initialized from 0" ); terms = Terms ({ controlVariable: _controlVariable, minimumPrice: _minimumPrice, maxPayout: _maxPayout, fee: _fee, maxDebt: _maxDebt, vestingTerm: _vestingTerm }); totalDebt = _initialDebt; lastDecay = uint32(block.timestamp); } /* ======== POLICY FUNCTIONS ======== */ enum PARAMETER { VESTING, PAYOUT, FEE, DEBT, MINPRICE, CONTROL } /** * @notice set parameters for new bonds * @param _parameter PARAMETER * @param _input uint */ function setBondTerms ( PARAMETER _parameter, uint _input ) external onlyPolicy() { if ( _parameter == PARAMETER.VESTING ) { // 0 require( _input >= 129600, "Vesting must be longer than 36 hours" ); terms.vestingTerm = uint32(_input); } else if ( _parameter == PARAMETER.PAYOUT ) { // 1 require( _input <= 1000, "Payout cannot be above 1 percent" ); terms.maxPayout = _input; } else if ( _parameter == PARAMETER.FEE ) { // 2 require( _input <= 10000, "DAO fee cannot exceed payout" ); terms.fee = _input; } else if ( _parameter == PARAMETER.DEBT ) { // 3 terms.maxDebt = _input; } else if ( _parameter == PARAMETER.MINPRICE ) { // 4 terms.minimumPrice = _input; } else if ( _parameter == PARAMETER.CONTROL ) { // 5 terms.controlVariable = _input; } } /** * @notice set control variable adjustment * @param _addition bool * @param _increment uint * @param _target uint * @param _buffer uint */ function setAdjustment ( bool _addition, uint _increment, uint _target, uint32 _buffer ) external onlyPolicy() { adjustment = Adjust({ add: _addition, rate: _increment, target: _target, buffer: _buffer, lastTime: uint32(block.timestamp) }); } /** * @notice set contract for auto stake * @param _staking address * @param _helper bool */ function setStaking( address _staking, bool _helper ) external onlyPolicy() { require( _staking != address(0) ); if ( _helper ) { useHelper = true; stakingHelper = _staking; } else { useHelper = false; staking = _staking; } } /* ======== USER FUNCTIONS ======== */ /** * @notice deposit bond * @param _amount uint * @param _maxPrice uint * @param _depositor address * @return uint */ function deposit( uint _amount, uint _maxPrice, address _depositor ) external returns ( uint ) { require( _depositor != address(0), "Invalid address" ); decayDebt(); require( totalDebt <= terms.maxDebt, "Max capacity reached" ); uint priceInUSD = bondPriceInUSD(); // Stored in bond info uint nativePrice = _bondPrice(); require( _maxPrice >= nativePrice, "Slippage limit: more than max price" ); // slippage protection uint value = ITreasury( treasury ).valueOf( principle, _amount ); uint payout = payoutFor( value ); // payout to bonder is computed require( payout >= 10000000, "Bond too small" ); // must be > 0.01 OHM ( underflow protection ) require( payout <= maxPayout(), "Bond too large"); // size protection because there is no slippage // profits are calculated uint fee = payout.mul( terms.fee ).div( 10000 ); uint profit = value.sub( payout ).sub( fee ); /** principle is transferred in approved and deposited into the treasury, returning (_amount - profit) OHM */ IERC20( principle ).safeTransferFrom( msg.sender, address(this), _amount ); IERC20( principle ).approve( address( treasury ), _amount ); ITreasury( treasury ).deposit( _amount, principle, profit ); if ( fee != 0 ) { // fee is transferred to dao IERC20( Dawgsta ).safeTransfer( DAO, fee ); } // total debt is increased totalDebt = totalDebt.add( value ); // depositor info is stored bondInfo[ _depositor ] = Bond({ payout: bondInfo[ _depositor ].payout.add( payout ), vesting: terms.vestingTerm, lastTime: uint32(block.timestamp), pricePaid: priceInUSD }); // indexed events are emitted emit BondCreated( _amount, payout, block.timestamp.add( terms.vestingTerm ), priceInUSD ); emit BondPriceChanged( bondPriceInUSD(), _bondPrice(), debtRatio() ); adjust(); // control variable is adjusted return payout; } /** * @notice redeem bond for user * @param _recipient address * @param _stake bool * @return uint */ function redeem( address _recipient, bool _stake ) external returns ( uint ) { Bond memory info = bondInfo[ _recipient ]; // (seconds since last interaction / vesting term remaining) uint percentVested = percentVestedFor( _recipient ); if ( percentVested >= 10000 ) { // if fully vested delete bondInfo[ _recipient ]; // delete user info emit BondRedeemed( _recipient, info.payout, 0 ); // emit bond data return stakeOrSend( _recipient, _stake, info.payout ); // pay user everything due } else { // if unfinished // calculate payout vested uint payout = info.payout.mul( percentVested ).div( 10000 ); // store updated deposit info bondInfo[ _recipient ] = Bond({ payout: info.payout.sub( payout ), vesting: info.vesting.sub32( uint32( block.timestamp ).sub32( info.lastTime ) ), lastTime: uint32(block.timestamp), pricePaid: info.pricePaid }); emit BondRedeemed( _recipient, payout, bondInfo[ _recipient ].payout ); return stakeOrSend( _recipient, _stake, payout ); } } /* ======== INTERNAL HELPER FUNCTIONS ======== */ /** * @notice allow user to stake payout automatically * @param _stake bool * @param _amount uint * @return uint */ function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { if ( !_stake ) { // if user does not want to stake IERC20( Dawgsta ).transfer( _recipient, _amount ); // send payout } else { // if user wants to stake if ( useHelper ) { // use if staking warmup is 0 IERC20( Dawgsta ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); } else { IERC20( Dawgsta ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } } return _amount; } /** * @notice makes incremental adjustment to control variable */ function adjust() internal { uint timeCanAdjust = adjustment.lastTime.add( adjustment.buffer ); if( adjustment.rate != 0 && block.timestamp >= timeCanAdjust ) { uint initial = terms.controlVariable; if ( adjustment.add ) { terms.controlVariable = terms.controlVariable.add( adjustment.rate ); if ( terms.controlVariable >= adjustment.target ) { adjustment.rate = 0; } } else { terms.controlVariable = terms.controlVariable.sub( adjustment.rate ); if ( terms.controlVariable <= adjustment.target ) { adjustment.rate = 0; } } adjustment.lastTime = uint32(block.timestamp); emit ControlVariableAdjustment( initial, terms.controlVariable, adjustment.rate, adjustment.add ); } } /** * @notice reduce total debt */ function decayDebt() internal { totalDebt = totalDebt.sub( debtDecay() ); lastDecay = uint32(block.timestamp); } /* ======== VIEW FUNCTIONS ======== */ /** * @notice determine maximum bond size * @return uint */ function maxPayout() public view returns ( uint ) { return IERC20( Dawgsta ).totalSupply().mul( terms.maxPayout ).div( 100000 ); } /** * @notice calculate interest due for new bond * @param _value uint * @return uint */ function payoutFor( uint _value ) public view returns ( uint ) { return FixedPoint.fraction( _value, bondPrice() ).decode112with18().div( 1e16 ); } /** * @notice calculate current bond premium * @return price_ uint */ function bondPrice() public view returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } } /** * @notice calculate current bond price and remove floor if above * @return price_ uint */ function _bondPrice() internal returns ( uint price_ ) { price_ = terms.controlVariable.mul( debtRatio() ).add( 1000000000 ).div( 1e7 ); if ( price_ < terms.minimumPrice ) { price_ = terms.minimumPrice; } else if ( terms.minimumPrice != 0 ) { terms.minimumPrice = 0; } } /** * @notice converts bond price to DAI value * @return price_ uint */ function bondPriceInUSD() public view returns ( uint price_ ) { if( isLiquidityBond ) { price_ = bondPrice().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 100 ); } else { price_ = bondPrice().mul( 10 ** IERC20( principle ).decimals() ).div( 100 ); } } /** * @notice calculate current ratio of debt to OHM supply * @return debtRatio_ uint */ function debtRatio() public view returns ( uint debtRatio_ ) { uint supply = IERC20( Dawgsta ).totalSupply(); debtRatio_ = FixedPoint.fraction( currentDebt().mul( 1e9 ), supply ).decode112with18().div( 1e18 ); } /** * @notice debt ratio in same terms for reserve or liquidity bonds * @return uint */ function standardizedDebtRatio() external view returns ( uint ) { if ( isLiquidityBond ) { return debtRatio().mul( IBondCalculator( bondCalculator ).markdown( principle ) ).div( 1e9 ); } else { return debtRatio(); } } /** * @notice calculate debt factoring in decay * @return uint */ function currentDebt() public view returns ( uint ) { return totalDebt.sub( debtDecay() ); } /** * @notice amount to decay total debt by * @return decay_ uint */ function debtDecay() public view returns ( uint decay_ ) { uint32 timeSinceLast = uint32(block.timestamp).sub32( lastDecay ); decay_ = totalDebt.mul( timeSinceLast ).div( terms.vestingTerm ); if ( decay_ > totalDebt ) { decay_ = totalDebt; } } /** * @notice calculate how far into vesting a depositor is * @param _depositor address * @return percentVested_ uint */ function percentVestedFor( address _depositor ) public view returns ( uint percentVested_ ) { Bond memory bond = bondInfo[ _depositor ]; uint secondsSinceLast = uint32(block.timestamp).sub( bond.lastTime ); uint vesting = bond.vesting; if ( vesting > 0 ) { percentVested_ = secondsSinceLast.mul( 10000 ).div( vesting ); } else { percentVested_ = 0; } } /** * @notice calculate amount of OHM available for claim by depositor * @param _depositor address * @return pendingPayout_ uint */ function pendingPayoutFor( address _depositor ) external view returns ( uint pendingPayout_ ) { uint percentVested = percentVestedFor( _depositor ); uint payout = bondInfo[ _depositor ].payout; if ( percentVested >= 10000 ) { pendingPayout_ = payout; } else { pendingPayout_ = payout.mul( percentVested ).div( 10000 ); } } /* ======= AUXILLIARY ======= */ /** * @notice allow anyone to send lost tokens (excluding principle or OHM) to the DAO * @return bool */ function recoverLostToken( address _token ) external returns ( bool ) { require( _token != Dawgsta ); require( _token != principle ); IERC20( _token ).safeTransfer( DAO, IERC20( _token ).balanceOf( address(this) ) ); return true; } }
* @notice allow user to stake payout automatically @param _stake bool @param _amount uint @return uint/
function stakeOrSend( address _recipient, bool _stake, uint _amount ) internal returns ( uint ) { IERC20( Dawgsta ).approve( stakingHelper, _amount ); IStakingHelper( stakingHelper ).stake( _amount, _recipient ); IERC20( Dawgsta ).approve( staking, _amount ); IStaking( staking ).stake( _amount, _recipient ); } else { }
7,759,391
[ 1, 5965, 729, 358, 384, 911, 293, 2012, 6635, 282, 389, 334, 911, 1426, 282, 389, 8949, 2254, 225, 327, 2254, 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 ]
[ 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, 0 ]
[ 1, 565, 445, 384, 911, 1162, 3826, 12, 1758, 389, 20367, 16, 1426, 389, 334, 911, 16, 2254, 389, 8949, 262, 2713, 1135, 261, 2254, 262, 288, 203, 7734, 467, 654, 39, 3462, 12, 463, 2219, 75, 334, 69, 262, 18, 12908, 537, 12, 384, 6159, 2276, 16, 389, 8949, 11272, 203, 7734, 467, 510, 6159, 2276, 12, 384, 6159, 2276, 262, 18, 334, 911, 12, 389, 8949, 16, 389, 20367, 11272, 203, 7734, 467, 654, 39, 3462, 12, 463, 2219, 75, 334, 69, 262, 18, 12908, 537, 12, 384, 6159, 16, 389, 8949, 11272, 203, 7734, 467, 510, 6159, 12, 384, 6159, 262, 18, 334, 911, 12, 389, 8949, 16, 389, 20367, 11272, 203, 203, 5411, 289, 469, 288, 203, 5411, 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 ]
// contracts/TVL.sol // SPDX-License-Identifier: MIT pragma solidity ^0.7.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; /// --------------------------------------- /// @title Abstract Adapter /// @author Andreas Bigger <[email protected]> /// --------------------------------------- abstract contract Adapter is OwnableUpgradeable { using SafeMathUpgradeable for uint256; // * Array of approved admins address[] internal approvedAdmin; // * Default pool address address internal POOL_ADDRESS; modifier aboveZero(uint256 _x) { require(_x > 0, "Input must be greater than zero."); _; } modifier onlyAdmin(address _admin) { bool _is_approved = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_approved = true; } require( _is_approved == true, "Function caller must be an adapter admin." ); _; } modifier notAdmin(address _admin) { bool _is_admin = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_admin = true; } require( _is_admin == false, "Function caller must not be an adapter admin." ); _; } /// @dev load metadata api and fetch eth_pool balance /// @param _owner address of the contract owner /// @param _pool_address address of the pool function initialize(address _owner, address _pool_address) public virtual initializer { POOL_ADDRESS = _pool_address; approvedAdmin.push(_owner); __Ownable_init(); transferOwnership(_owner); } /// @dev Allow owner to get the current pool address /// @return address of new pool function getPoolAddress() external view onlyAdmin(msg.sender) returns (address) { return POOL_ADDRESS; } /// @dev Allow owner to add address to admins /// @param _new_admin address of new admin /// @return address of new admin function addApprovedAdmin(address _new_admin) external notAdmin(_new_admin) onlyOwner returns (address) { require(_new_admin != address(0), "Must be a valid address"); approvedAdmin.push(_new_admin); return _new_admin; } /// @dev Allow owner to remove address from admins /// @param _admin address of removed admin /// @return address of removed admin function removeApprovedAdmin(address _admin) external onlyAdmin(_admin) onlyOwner returns (address) { for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) { delete approvedAdmin[i]; } } return _admin; } /// @dev Allow owner to approve an admin /// @param _pool_address address of the pool /// @return address of new pool function setPoolAddress(address _pool_address) public virtual onlyAdmin(msg.sender) returns (address) { require(_pool_address != address(0), "Must be a valid address"); POOL_ADDRESS = _pool_address; return _pool_address; } /// @dev Allow owner to approve an admin /// @param _from sender if internal /// @param _pool_address address of the pool /// @return address of new pool function setPoolAddress(address _from, address _pool_address) public onlyAdmin(msg.sender) onlyAdmin(_from) returns (address) { return setPoolAddress(_pool_address); } // TODO: IMPLEMENT IN CHILDREN /// @dev function to get the amount of pool share by a user /// @param _from address of the current user /// @param _max_amount the amount of a given token id /// @return uint256 amount of tokens to give to the user function getPoolShare(address _from, uint256 _max_amount) public virtual aboveZero(_max_amount) returns (uint256) {} /// @dev helper function to get percent /// @param _numerator fraction numerator /// @param _denominator fraction denominator /// @param _precision precision of numerator in calculation /// @return uint256 percent * 10 function _percent( uint256 _numerator, uint256 _denominator, uint256 _precision ) internal pure returns (uint256) { // caution, check safe-to-multiply here uint256 _multiplied_numerator = _numerator.mul(10**(_precision.add(1))); // with rounding of last digit uint256 _quotient = ((_multiplied_numerator.div(_denominator)).add(5)).div(10); return (_quotient); } }
--------------------------------------- @title Abstract Adapter @author Andreas Bigger <[email protected]> --------------------------------------- * Array of approved admins * Default pool address
abstract contract Adapter is OwnableUpgradeable { using SafeMathUpgradeable for uint256; address[] internal approvedAdmin; address internal POOL_ADDRESS; pragma solidity ^0.7.0; modifier aboveZero(uint256 _x) { require(_x > 0, "Input must be greater than zero."); _; } modifier onlyAdmin(address _admin) { bool _is_approved = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_approved = true; } require( _is_approved == true, "Function caller must be an adapter admin." ); _; } modifier onlyAdmin(address _admin) { bool _is_approved = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_approved = true; } require( _is_approved == true, "Function caller must be an adapter admin." ); _; } modifier notAdmin(address _admin) { bool _is_admin = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_admin = true; } require( _is_admin == false, "Function caller must not be an adapter admin." ); _; } modifier notAdmin(address _admin) { bool _is_admin = false; for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) _is_admin = true; } require( _is_admin == false, "Function caller must not be an adapter admin." ); _; } function initialize(address _owner, address _pool_address) public virtual initializer { POOL_ADDRESS = _pool_address; approvedAdmin.push(_owner); __Ownable_init(); transferOwnership(_owner); } function getPoolAddress() external view onlyAdmin(msg.sender) returns (address) { return POOL_ADDRESS; } function addApprovedAdmin(address _new_admin) external notAdmin(_new_admin) onlyOwner returns (address) { require(_new_admin != address(0), "Must be a valid address"); approvedAdmin.push(_new_admin); return _new_admin; } function removeApprovedAdmin(address _admin) external onlyAdmin(_admin) onlyOwner returns (address) { for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) { delete approvedAdmin[i]; } } return _admin; } function removeApprovedAdmin(address _admin) external onlyAdmin(_admin) onlyOwner returns (address) { for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) { delete approvedAdmin[i]; } } return _admin; } function removeApprovedAdmin(address _admin) external onlyAdmin(_admin) onlyOwner returns (address) { for (uint256 i = 0; i < approvedAdmin.length; i++) { if (approvedAdmin[i] == _admin) { delete approvedAdmin[i]; } } return _admin; } function setPoolAddress(address _pool_address) public virtual onlyAdmin(msg.sender) returns (address) { require(_pool_address != address(0), "Must be a valid address"); POOL_ADDRESS = _pool_address; return _pool_address; } function setPoolAddress(address _from, address _pool_address) public onlyAdmin(msg.sender) onlyAdmin(_from) returns (address) { return setPoolAddress(_pool_address); } {} function getPoolShare(address _from, uint256 _max_amount) public virtual aboveZero(_max_amount) returns (uint256) function _percent( uint256 _numerator, uint256 _denominator, uint256 _precision ) internal pure returns (uint256) { uint256 _multiplied_numerator = _numerator.mul(10**(_precision.add(1))); uint256 _quotient = ((_multiplied_numerator.div(_denominator)).add(5)).div(10); return (_quotient); } }
12,833,764
[ 1, 2443, 17082, 225, 4115, 14238, 225, 7835, 266, 345, 605, 2318, 411, 70, 2318, 36, 19446, 18, 28049, 34, 19134, 13093, 225, 1510, 434, 20412, 31116, 225, 2989, 2845, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 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, 17801, 6835, 14238, 353, 14223, 6914, 10784, 429, 288, 203, 565, 1450, 14060, 10477, 10784, 429, 364, 2254, 5034, 31, 203, 203, 565, 1758, 8526, 2713, 20412, 4446, 31, 203, 203, 565, 1758, 2713, 13803, 1741, 67, 15140, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 20, 31, 203, 565, 9606, 5721, 7170, 12, 11890, 5034, 389, 92, 13, 288, 203, 3639, 2583, 24899, 92, 405, 374, 16, 315, 1210, 1297, 506, 6802, 2353, 3634, 1199, 1769, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 4446, 12, 2867, 389, 3666, 13, 288, 203, 3639, 1426, 389, 291, 67, 25990, 273, 629, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 20412, 4446, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 25990, 4446, 63, 77, 65, 422, 389, 3666, 13, 389, 291, 67, 25990, 273, 638, 31, 203, 3639, 289, 203, 3639, 2583, 12, 203, 5411, 389, 291, 67, 25990, 422, 638, 16, 203, 5411, 315, 2083, 4894, 1297, 506, 392, 4516, 3981, 1199, 203, 3639, 11272, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 9606, 1338, 4446, 12, 2867, 389, 3666, 13, 288, 203, 3639, 1426, 389, 291, 67, 25990, 273, 629, 31, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 20412, 4446, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 25990, 4446, 63, 77, 65, 422, 389, 3666, 13, 389, 291, 67, 25990, 273, 638, 31, 203, 3639, 289, 203, 3639, 2 ]
./full_match/1/0x5D8d9F5b96f4438195BE9b99eee6118Ed4304286/sources/contracts/interfaces/IBlacksmith.sol
* @title Interface of COVER shield mining contract Blacksmith @author crypto-pumpkin@github/
interface IBlacksmith { struct Miner { uint256 amount; } struct Pool { } struct BonusToken { uint256 startTime; uint256 endTime; } event Deposit(address indexed miner, address indexed lpToken, uint256 amount); event Withdraw(address indexed miner, address indexed lpToken, uint256 amount); }
2,907,548
[ 1, 1358, 434, 7910, 2204, 699, 491, 1131, 310, 6835, 22467, 4808, 483, 225, 8170, 17, 84, 2801, 15984, 36, 6662, 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 ]
[ 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, 0 ]
[ 1, 5831, 467, 13155, 4808, 483, 288, 203, 203, 225, 1958, 5444, 264, 288, 203, 565, 2254, 5034, 3844, 31, 203, 225, 289, 203, 203, 225, 1958, 8828, 288, 203, 225, 289, 203, 203, 225, 1958, 605, 22889, 1345, 288, 203, 565, 2254, 5034, 8657, 31, 203, 565, 2254, 5034, 13859, 31, 203, 225, 289, 203, 203, 225, 871, 4019, 538, 305, 12, 2867, 8808, 1131, 264, 16, 1758, 8808, 12423, 1345, 16, 2254, 5034, 3844, 1769, 203, 225, 871, 3423, 9446, 12, 2867, 8808, 1131, 264, 16, 1758, 8808, 12423, 1345, 16, 2254, 5034, 3844, 1769, 203, 203, 97, 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 ]
pragma solidity ^0.5.0; import { Governor } from "../governor/governor.sol"; import { SafeMath } from "../libraries/SafeMath.sol"; // This governor gives the entire power to the person that has the most ether contract Governor_Richest is Governor { constructor(address _proxy, uint _percentage) Governor(_proxy) public { } mapping (address => uint) internal values; uint256 internal max; address internal richestPayer; function buyVote() public payable { values[msg.sender] = SafeMath.add(values[msg.sender], msg.value); if (values[msg.sender] > max) { max = values[msg.sender]; richestPayer = msg.sender; } } modifier onlyIfApproved(uint action, address newAddress) { require (msg.sender == richestPayer, "Governor: Only the richest donator may do this"); _; } }
This governor gives the entire power to the person that has the most ether
contract Governor_Richest is Governor { mapping (address => uint) internal values; uint256 internal max; address internal richestPayer; import { Governor } from "../governor/governor.sol"; import { SafeMath } from "../libraries/SafeMath.sol"; constructor(address _proxy, uint _percentage) Governor(_proxy) public { } function buyVote() public payable { values[msg.sender] = SafeMath.add(values[msg.sender], msg.value); if (values[msg.sender] > max) { max = values[msg.sender]; richestPayer = msg.sender; } } function buyVote() public payable { values[msg.sender] = SafeMath.add(values[msg.sender], msg.value); if (values[msg.sender] > max) { max = values[msg.sender]; richestPayer = msg.sender; } } modifier onlyIfApproved(uint action, address newAddress) { require (msg.sender == richestPayer, "Governor: Only the richest donator may do this"); _; } }
5,453,648
[ 1, 2503, 314, 1643, 29561, 14758, 326, 7278, 7212, 358, 326, 6175, 716, 711, 326, 4486, 225, 2437, 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, 611, 1643, 29561, 67, 22591, 395, 353, 611, 1643, 29561, 288, 203, 203, 203, 565, 2874, 261, 2867, 516, 2254, 13, 2713, 924, 31, 203, 565, 2254, 5034, 2713, 943, 31, 203, 565, 1758, 2713, 23657, 395, 52, 1773, 31, 203, 203, 5666, 288, 611, 1643, 29561, 289, 628, 315, 6216, 75, 1643, 29561, 19, 75, 1643, 29561, 18, 18281, 14432, 203, 5666, 288, 14060, 10477, 289, 628, 315, 6216, 31417, 19, 9890, 10477, 18, 18281, 14432, 203, 565, 3885, 12, 2867, 389, 5656, 16, 2254, 389, 18687, 13, 611, 1643, 29561, 24899, 5656, 13, 1071, 288, 289, 203, 565, 445, 30143, 19338, 1435, 1071, 8843, 429, 288, 203, 3639, 924, 63, 3576, 18, 15330, 65, 273, 14060, 10477, 18, 1289, 12, 2372, 63, 3576, 18, 15330, 6487, 1234, 18, 1132, 1769, 203, 203, 3639, 309, 261, 2372, 63, 3576, 18, 15330, 65, 405, 943, 13, 288, 203, 5411, 943, 273, 924, 63, 3576, 18, 15330, 15533, 203, 5411, 23657, 395, 52, 1773, 273, 1234, 18, 15330, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 30143, 19338, 1435, 1071, 8843, 429, 288, 203, 3639, 924, 63, 3576, 18, 15330, 65, 273, 14060, 10477, 18, 1289, 12, 2372, 63, 3576, 18, 15330, 6487, 1234, 18, 1132, 1769, 203, 203, 3639, 309, 261, 2372, 63, 3576, 18, 15330, 65, 405, 943, 13, 288, 203, 5411, 943, 273, 924, 63, 3576, 18, 15330, 15533, 203, 5411, 23657, 395, 52, 1773, 273, 1234, 18, 15330, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 2 ]
pragma solidity ^0.4.11; /** A Proposal for an initial offer requiring approval by a buyer and seller. */ library PortfolioProposalLib { struct Data { // time in seconds after an offer is made that the buyer can approve the proposal uint timespanOffer; // time in seconds from acceptance time when the buyer is allowed to settle uint timespanBeforeSettle; // time in seconds from buyer settle request to when prism can be settled and funds can be withdrawn uint timespanBeforeWithdraw; // time in seconds before the seller can liquidate the portfolio uint timespanDuration; // time created uint created; // closing fees uint closingFeePercentBuyer; uint closingFeePercentSeller; uint closingFeeFixedBuyer; uint closingFeeFixedSeller; // rebalance fees uint rebalanceFeePercentToSeller; uint rebalanceFeePercentToOwner; uint rebalanceFeeFixedToSeller; uint rebalanceFeeFixedToOwner; // the initial fee to the seller that can be immediately withdrawn after the prism becomes Accepted uint initialCommission; // the % of principal in ETH that is paid daily to the seller. It can be withdrawn at a pro-rated rate at any time. // NOTE: This is given a % of principal here, but is converted into a fixed amount of ETH in the PrismAccount. // NOTE: stored as an integer that will be divided by fixedPrecision to simulate a fixed point number of a given precision uint dailyCommission; // collateral required from the buyer and seller to accept the contract as a percentage of the value // also determines how much funds the buyer or seller can withdraw if overcollateralized // NOTE: stored as an integer that will be divided by fixedPrecision to simulate a fixed point number of a given precision uint buyerCollateralRatio; uint sellerCollateralRatio; } /** Create proposal and do not let the offer be changed */ function createProposal(Data storage self, uint[4] uints, uint[4] timespans, uint[8] fees) internal { if (self.created > 0) revert(); self.initialCommission = uints[0]; self.dailyCommission = uints[1]; self.buyerCollateralRatio = uints[2]; self.sellerCollateralRatio = uints[3]; self.timespanOffer = timespans[0]; self.timespanBeforeSettle = timespans[1]; self.timespanDuration = timespans[2]; self.timespanBeforeWithdraw = timespans[3]; self.created = now; self.closingFeePercentBuyer = fees[0]; self.closingFeePercentSeller = fees[1]; self.closingFeeFixedBuyer = fees[2]; self.closingFeeFixedSeller = fees[3]; self.rebalanceFeePercentToSeller = fees[4]; self.rebalanceFeePercentToOwner = fees[5]; self.rebalanceFeeFixedToSeller = fees[6]; self.rebalanceFeeFixedToOwner = fees[7]; } }
* Create proposal and do not let the offer be changed */
function createProposal(Data storage self, uint[4] uints, uint[4] timespans, uint[8] fees) internal { if (self.created > 0) revert(); self.initialCommission = uints[0]; self.dailyCommission = uints[1]; self.buyerCollateralRatio = uints[2]; self.sellerCollateralRatio = uints[3]; self.timespanOffer = timespans[0]; self.timespanBeforeSettle = timespans[1]; self.timespanDuration = timespans[2]; self.timespanBeforeWithdraw = timespans[3]; self.created = now; self.closingFeePercentBuyer = fees[0]; self.closingFeePercentSeller = fees[1]; self.closingFeeFixedBuyer = fees[2]; self.closingFeeFixedSeller = fees[3]; self.rebalanceFeePercentToSeller = fees[4]; self.rebalanceFeePercentToOwner = fees[5]; self.rebalanceFeeFixedToSeller = fees[6]; self.rebalanceFeeFixedToOwner = fees[7]; }
15,833,442
[ 1, 1684, 14708, 471, 741, 486, 2231, 326, 10067, 506, 3550, 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 ]
[ 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, 225, 445, 752, 14592, 12, 751, 2502, 365, 16, 2254, 63, 24, 65, 2254, 87, 16, 2254, 63, 24, 65, 4124, 84, 634, 16, 2254, 63, 28, 65, 1656, 281, 13, 2713, 288, 203, 565, 309, 261, 2890, 18, 4824, 405, 374, 13, 15226, 5621, 203, 203, 565, 365, 18, 6769, 799, 3951, 273, 2254, 87, 63, 20, 15533, 203, 565, 365, 18, 26790, 799, 3951, 273, 2254, 87, 63, 21, 15533, 203, 565, 365, 18, 70, 16213, 13535, 2045, 287, 8541, 273, 2254, 87, 63, 22, 15533, 203, 565, 365, 18, 1786, 749, 13535, 2045, 287, 8541, 273, 2254, 87, 63, 23, 15533, 203, 565, 365, 18, 8293, 7355, 10513, 273, 4124, 84, 634, 63, 20, 15533, 203, 565, 365, 18, 8293, 7355, 4649, 694, 5929, 273, 4124, 84, 634, 63, 21, 15533, 203, 565, 365, 18, 8293, 7355, 5326, 273, 4124, 84, 634, 63, 22, 15533, 203, 565, 365, 18, 8293, 7355, 4649, 1190, 9446, 273, 4124, 84, 634, 63, 23, 15533, 203, 565, 365, 18, 4824, 273, 2037, 31, 203, 565, 365, 18, 19506, 14667, 8410, 38, 16213, 273, 1656, 281, 63, 20, 15533, 203, 565, 365, 18, 19506, 14667, 8410, 22050, 273, 1656, 281, 63, 21, 15533, 203, 565, 365, 18, 19506, 14667, 7505, 38, 16213, 273, 1656, 281, 63, 22, 15533, 203, 565, 365, 18, 19506, 14667, 7505, 22050, 273, 1656, 281, 63, 23, 15533, 203, 565, 365, 18, 266, 12296, 14667, 8410, 774, 22050, 273, 1656, 281, 63, 24, 15533, 203, 565, 365, 18, 266, 12296, 14667, 8410, 2 ]
./full_match/4/0x0A87021D82453AB0B18a375aFfdB8C689e05A182/sources/sirtoken3.sol
* @dev Check if an account is excluded from paying taxes. @param account_ address @return boolean/
function isExcludedFromFee( address account_ ) external view returns (bool) { return ExcludedFromFee.contains(account_); }
12,424,918
[ 1, 1564, 309, 392, 2236, 353, 8845, 628, 8843, 310, 5320, 281, 18, 282, 2236, 67, 1758, 225, 327, 1250, 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, 353, 16461, 1265, 14667, 12, 203, 3639, 1758, 2236, 67, 203, 565, 262, 3903, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 327, 1312, 7908, 1265, 14667, 18, 12298, 12, 4631, 67, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; import "library.sol"; contract PausablePool 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 _poolerPaused; bool private _buyerPaused; /** * @dev Modifier to make a function callable only when the pooler is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenPoolerNotPaused() { require(!_poolerPaused, "paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPoolerPaused() { require(_poolerPaused, "not paused"); _; } /** * @dev Modifier to make a function callable only when the buyer is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenBuyerNotPaused() { require(!_buyerPaused, "paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenBuyerPaused() { require(_buyerPaused, "not paused"); _; } /** * @dev Returns true if the pooler is paused, and false otherwise. */ function poolerPaused() public view returns (bool) { return _poolerPaused; } /** * @dev Returns true if the buyer is paused, and false otherwise. */ function buyerPaused() public view returns (bool) { return _buyerPaused; } /** * @dev Triggers stopped state. * * Requirements: * * - The pooler must not be paused. */ function _pausePooler() internal whenPoolerNotPaused { _poolerPaused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The pooler must be paused. */ function _unpausePooler() internal whenPoolerPaused { _poolerPaused = false; emit Unpaused(_msgSender()); } /** * @dev Triggers stopped state. * * Requirements: * * - The buyer must not be paused. */ function _pauseBuyer() internal whenBuyerNotPaused { _buyerPaused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The buyer must be paused. */ function _unpauseBuyer() internal whenBuyerPaused { _buyerPaused = false; emit Unpaused(_msgSender()); } } /** * @title base contract for option pool */ abstract contract PandaBase is IOptionPool, PausablePool{ using SafeERC20 for IERC20; using SafeERC20 for IOption; using SafeMath for uint; using Address for address payable; // initialization once bool private inited; // pool direction enum enum PoolDirection{ CALL, PUT } /// @dev pool direction PoolDirection public immutable _direction; // option durations uint16 [] private _durations = [300,900,1800,2700,3600]; /** * @dev option creation factory, set this based on blockchain, * constructor will fail if the address is illegal. */ // BSC IPandaFactory internal constant pandaFactory = IPandaFactory(0xddE5b0c676d6A94540F5A2A91C7a5b75eaCBBEe0); uint256 public collateral; // collaterals in this pool uint256 internal constant SHARE_MULTIPLIER = 1e18; // share multiplier to avert division underflow uint256 public constant POOLER_FEE = 5e16; // charge 0.05 BNB for each deposit and withdraw mapping (address => uint256) internal _premiumBalance; // tracking pooler's claimable premium mapping (address => uint256) internal _opaBalance; // tracking pooler's claimable OPA tokens mapping (address => uint256) internal _profitsBalance; // tracking buyer's claimable profits IOption [] internal _options; // all option contracts address internal _owner; // owner of this contract IERC20 public USDTContract; // USDT asset contract address AggregatorV3Interface public priceFeed; // chainlink price feed uint8 assetDecimal; // asset decimal CDFDataInterface public cdfDataContract; // cdf data contract; uint8 public utilizationRate = 50; // utilization rate of the pool in percent uint8 public maxUtilizationRate = 75; // max utilization rate of the pool in percent uint16 public sigma = 70; // current sigma uint256 private _refreshPeriod = 3600; // sigma refresh period uint256 private _sigmaSoldOptions; // sum total options sold in a period uint256 private _sigmaTotalOptions; // sum total options issued uint256 private _nextRefresh = block.timestamp + _refreshPeriod; // expected next refreshing time; // tracking pooler's collateral with // the token contract of the pooler; IPoolerToken public poolerTokenContract; address public poolManager; // platform contract address payable public updaterAddress = 0x3639e068C9c4BB24292a9F3cB9698E03bD6Ee01A; // updater address IERC20 public OPAToken = IERC20(0xA2F89a3be1bAda5Eb9D58D23EDc2E2FE0F82F4b0) ; // OPA token contract address public rewardAccount = 0x38A09Ec80aA2c5fc6E92a65E98a4e43e4dAb53b4; // OPA reward account /** * OPA Rewarding */ /// @dev block reward for this pool uint256 public OPABlockReward = 0; /// @dev round index mapping to accumulate share. mapping (uint => uint) private _opaAccShares; /// @dev mark pooler's highest settled OPA round. mapping (address => uint) private _settledOPARounds; /// @dev a monotonic increasing OPA round index, STARTS FROM 1 uint256 private _currentOPARound = 1; // @dev last OPA reward block uint256 private _lastRewardBlock = block.number; event OPARewardSet(address account, uint256 blockReward); /** * OPA Vesting */ IVesting public VestingContract = IVesting(0xe135C31Fc21A4962eA5000AC295885bcfd635293); /** * @dev settlement economy * we push some entropy to this array for each user operation * and pop some of the array when update to refund to caller. */ uint256[] private entropy; /** * @dev Modifier to make a function callable only by owner */ modifier onlyOwner() { require(msg.sender == _owner, "restricted"); _; } /** * @dev Modifier to make a function callable only by poolerTokenContract */ modifier onlyPoolerTokenContract() { require(msg.sender == address(poolerTokenContract), "restricted"); _; } /** * @dev Modifier to make a function callable only by pool manager */ modifier onlyPoolManager() { require(msg.sender == address(poolManager), "restricted"); _; } /** * @dev Modifier to make a function callable only by options */ modifier onlyOptions() { // privilege check bool isFromOption; for (uint i = 0; i < _options.length; i++) { if (address(_options[i]) == msg.sender) { isFromOption = true; break; } } require(isFromOption); _; } /** * @dev abstract function for current option supply per slot */ function _slotSupply(uint assetPrice) internal view virtual returns(uint); /** * @dev abstract function to calculate option profits */ function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view virtual returns(uint256); /** * @dev abstract function to send back option profits */ function _sendProfits(address payable account, uint256 amount) internal virtual; /** * @dev abstract function to get total pledged collateral */ function _totalPledged() internal view virtual returns (uint); constructor(AggregatorV3Interface priceFeed_, uint8 assetDecimal_, PoolDirection direction_) public { _owner = msg.sender; priceFeed = priceFeed_; assetDecimal = assetDecimal_; _direction = direction_; // contract references USDTContract = IERC20(pandaFactory.getUSDTContract()); cdfDataContract = CDFDataInterface(pandaFactory.getCDF()); // set default poolManager poolManager = msg.sender; } /** * @dev Option initialization function. */ function init() public onlyOwner { require(!inited, "inited"); inited = true; // creation of options for (uint i=0;i<_durations.length;i++) { _options.push(pandaFactory.createOption(_durations[i], assetDecimal, IOptionPool(this))); } // first update; update(); } /** * @dev Returns the owner of this contract */ function owner() external override view returns (address) { return _owner; } /** * @dev transfer ownership */ function transferOwnership(address newOwner) external override onlyOwner { require(newOwner != address(0), "zero"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } /** *@dev pooler & buyer pausing */ function pausePooler() external override onlyOwner { _pausePooler(); } function unpausePooler() external override onlyOwner { _unpausePooler(); } function pauseBuyer() external override onlyOwner { _pauseBuyer(); } function unpauseBuyer() external override onlyOwner { _unpauseBuyer(); } /** * @notice check remaining options for the option contract */ function optionsLeft(IOption optionContract) external override view returns (uint256 optionsleft, uint round) { return (optionContract.balanceOf(address(this)), optionContract.getRound()); } /** * @notice buy options via USDT, pool receive premium */ function buy(uint amount, IOption optionContract, uint round) external override whenBuyerNotPaused { // make sure optionContract is in this pool bool optionValid; for (uint i = 0;i< _options.length;i++) { if (_options[i] == optionContract) { optionValid = true; break; } } require(optionValid,"option invalid"); // check if option current round is the given round, we cannot buy previous rounds require (optionContract.getRound() == round, "expired"); // cap amount to remaing options if (optionContract.balanceOf(address(this)) < amount) { amount = optionContract.balanceOf(address(this)); } // calculate premium cost uint premium = premiumCost(amount, optionContract); // transfer premium USDTs to this pool USDTContract.safeTransferFrom(msg.sender, address(this), premium); // transfer options to msg.sender optionContract.safeTransfer(msg.sender, amount); // credit premium to option contract optionContract.addPremium(msg.sender, premium); // log emit Buy(msg.sender, address(optionContract), round, amount, premium); // entropy storage to refund to update() caller entropy.push(block.number); // OPTION PARAMETERS MAINTENANCE // sigma: count sold options _sigmaSoldOptions = _sigmaSoldOptions.add(amount); // other periodical refresh if (block.timestamp > _nextRefresh) { updateSigma(); } // open new round, one caller will get refund for an effective update if (block.timestamp > getNextUpdateTime()) { update(); } } /** * @dev set OPA reward per height */ function setOPAReward(uint256 reward) external onlyOwner { // settle previous rewards updateOPAReward(); // set new block reward OPABlockReward = reward; // log emit OPARewardSet(msg.sender, reward); } /** * @dev convert sigma to index, sigma will be rounded to nearest index */ function _sigmaToIndex() private view returns(uint) { // sigma to index require(sigma >=15 && sigma <=145, "[15,145]"); uint sigmaIndex = sigma / 5; return sigmaIndex; } /** * @notice check option cost for given amount of option */ function premiumCost(uint amount, IOption optionContract) public override view returns(uint) { // expiry check if (block.timestamp >= optionContract.expiryDate()) { return 0; } // rounding to nearest duration uint timediff = optionContract.expiryDate().sub(block.timestamp).add(60); uint duration = timediff.div(120).mul(120); // round to 2min // align duration to [120, 3600] if (duration < 120) { duration = 120; } else if (duration > 3600) { duration = 3600; } // notice the CDF is already multiplied by cdfDataContract.Amplifier() uint cdf = cdfDataContract.CDF(duration, _sigmaToIndex()); // calculate premium for option uint currentPrice = getAssetPrice(); uint strikePrice = optionContract.strikePrice(); // calculate USDT profits based on current price uint realtimeProfits; if (_direction == PoolDirection.CALL) { // @dev convert asset profits to USDT at current price realtimeProfits = _calcProfits(currentPrice, strikePrice, amount) .mul(currentPrice) .div(10 ** uint(optionContract.decimals())); } else { realtimeProfits = _calcProfits(currentPrice, strikePrice, amount); } // price in the realtime profits to avoid arbitrage. // @dev note the price is for 10 ** option decimals return realtimeProfits + amount * currentPrice * cdf / (10 ** uint(optionContract.decimals())) / cdfDataContract.Amplifier(); } /** * @notice list all options */ function listOptions() external override view returns (IOption []memory) { return _options; } /** * @notice get current utilization rate */ function currentUtilizationRate() external override view returns (uint256) { if (collateral > 0) { return _totalPledged().mul(100).div(collateral); } return 0; } /** * @notice get next update time */ function getNextUpdateTime() public override view returns (uint) { uint nextUpdateTime = block.timestamp.add(1 days); for (uint i = 0;i< _options.length;i++) { if (_options[i].expiryDate() < nextUpdateTime) { nextUpdateTime = _options[i].expiryDate(); } } return nextUpdateTime; } /** * @notice set refresh period */ function setRefreshPeriod(uint period) external override { require(period > 0, "postive"); _refreshPeriod = period; } /** * @notice update of options, triggered by anyone periodically */ function update() public override { uint256 startGas = gasleft(); // load chainlink price uint assetPrice = getAssetPrice(); // create a memory copy of array IOption [] memory options = _options; // accumulated manager's USDT revenue uint256 accManagerRevenue; uint256 accManagerAssetRevenue; // settle all options for (uint i = 0;i< options.length;i++) { if (block.timestamp >= options[i].expiryDate()) { // expired (uint256 premium, uint256 asset) = _settleOption(options[i], assetPrice); accManagerRevenue += premium; accManagerAssetRevenue += asset; } else { // mark unexpired by clearning 0 options[i] = IOption(0); } } // calculate supply for a slot after settlement, // notice we must settle options before option reset, otherwise // we cannot get a correct slot supply due to COLLATERAL WRITE DOWN // when multiple options settles at once. uint slotSupply = _slotSupply(assetPrice); for (uint i = 0;i < options.length;i++) { if (options[i] != IOption(0)) { // we only check expiryDate once, it's expensive. // reset option with new slot supply options[i].resetOption(assetPrice, slotSupply); // sigma: count newly issued options _sigmaTotalOptions = _sigmaTotalOptions.add(slotSupply); } } // transfer manager's USDT premium if (accManagerRevenue > 0) { USDTContract.safeTransfer(poolManager, accManagerRevenue); } // transfer manager's asset revenue if (accManagerAssetRevenue > 0) { _sendProfits(payable(poolManager), accManagerAssetRevenue); } // compute gas used until now; // gas usage +STORAGEMOD -STORAGEKILL = -10000 uint needKills = (startGas - gasleft()) / 10000; // maximum 50% refund; needKills = needKills/2 + 1; // entropy limit if (needKills > entropy.length) { needKills = entropy.length; } // refund gas via STORAGEKILL for any caller for (uint i = 0;i<needKills;i++) { entropy.pop(); } } /** * @dev settle option contract * * ASSUMPTION: * if one pooler's token amount keeps unchanged after settlement, then * accmulated premiumShare * (pooler token) * is the share for one pooler. */ function _settleOption(IOption option, uint settlePrice) internal returns (uint256 managerRevenue, uint256 managerAssetRevenue) { uint totalSupply = option.totalSupply(); uint strikePrice = option.strikePrice(); // count total sold options uint totalOptionSold = totalSupply.sub(option.balanceOf(address(this))); // calculate user's total profits, ALREADY MULTIPLIED WITH 99% uint totalProfits = _calcProfits(settlePrice, strikePrice, totalOptionSold); // substract collateral // buyer's profits is pooler's loss if (totalProfits > 0) { // 1% profits belongs to manager managerAssetRevenue = totalProfits.div(99); collateral = collateral.sub(totalProfits).sub(managerAssetRevenue); } // settle preimum dividends uint poolerTotalSupply = poolerTokenContract.totalSupply(); uint totalPremiums = option.totalPremiums(); uint round = option.getRound(); // settle premium share uint roundPremiumShare; if (poolerTotalSupply > 0) { // 1% belongs to platform managerRevenue = totalPremiums.div(100); // 99% belongs to all pooler roundPremiumShare = totalPremiums.sub(managerRevenue) .mul(SHARE_MULTIPLIER) // mul share with SHARE_MULTIPLIER to avert from underflow .div(poolerTotalSupply); } // set the accumulated premiumShare if round > 0 if (round > 0) { roundPremiumShare = roundPremiumShare.add(option.getRoundAccPremiumShare(round-1)); } option.setRoundAccPremiumShare(round, roundPremiumShare); } /** * @dev update accumulated OPA block reward until block */ function updateOPAReward() internal { // skip round changing in the same block if (_lastRewardBlock == block.number) { return; } uint poolerTotalSupply = poolerTokenContract.totalSupply(); // postpone OPA rewarding if there is none pooler if (poolerTotalSupply == 0) { return; } // settle OPA share for [_lastRewardBlock, block.number] uint blocksToReward = block.number.sub(_lastRewardBlock); uint mintedOPA = OPABlockReward.mul(blocksToReward); uint roundOPAShare = mintedOPA.mul(SHARE_MULTIPLIER) .div(poolerTotalSupply); // mark block rewarded; _lastRewardBlock = block.number; // accumulate OPA share _opaAccShares[_currentOPARound] = roundOPAShare.add(_opaAccShares[_currentOPARound-1]); // next round setting _currentOPARound++; } /** * @dev function to update sigma value periodically */ function updateSigma() internal { // sigma: metrics updates hourly if (_sigmaTotalOptions > 0) { uint16 s = sigma; // update sigma uint rate = _sigmaSoldOptions.mul(100).div(_sigmaTotalOptions); // sigma range [15, 145] if (rate > 90 && s < 145) { s += 5; } else if (rate < 50 && s > 15) { s -= 5; } sigma = s; } // new metrics uint sigmaTotalOptions; uint sigmaSoldOptions; // create a memory copy of array IOption [] memory options = _options; // rebuild sold/total metrics for (uint i = 0;i< options.length;i++) { // sum all issued options and sold options uint supply = options[i].totalSupply(); uint sold = supply.sub(options[i].balanceOf(address(this))); sigmaTotalOptions = sigmaTotalOptions.add(supply); sigmaSoldOptions = sigmaSoldOptions.add(sold); } // set back to contract storage _sigmaTotalOptions = sigmaTotalOptions; _sigmaSoldOptions = sigmaSoldOptions; // set next refresh time to at least one hour later _nextRefresh += _refreshPeriod; } /** * @notice adjust sigma manually */ function adjustSigma(uint16 newSigma) external override onlyOwner { require (newSigma % 5 == 0, "needs 5*N"); require (newSigma >= 15 && newSigma <= 145, "[15,145]"); sigma = newSigma; } /** * @notice poolers sum premium USDTs; */ function checkPremium(address account) external override view returns(uint256 premium) { uint accountCollateral = poolerTokenContract.balanceOf(account); premium = _premiumBalance[account]; for (uint i = 0; i < _options.length; i++) { IOption option = _options[i]; uint currentRound = option.getRound(); uint lastSettledRound = option.getSettledRound(account); uint roundPremium = option.getRoundAccPremiumShare(currentRound-1).sub(option.getRoundAccPremiumShare(lastSettledRound)) .mul(accountCollateral) .div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER premium = premium.add(roundPremium); } return (premium); } /** * @notice poolers claim premium USDTs; */ function claimPremium() external override whenPoolerNotPaused { // settle un-distributed premiums in rounds to _premiumBalance; _settlePooler(msg.sender); // premium balance modification uint amountUSDTPremium = _premiumBalance[msg.sender]; delete _premiumBalance[msg.sender]; // zero premium balance // transfer premium USDTContract.safeTransfer(msg.sender, amountUSDTPremium); // log emit PremiumClaim(msg.sender, amountUSDTPremium); } /** * @notice poolers sum unclaimed OPA; */ function checkOPA(address account) external override view returns(uint256 opa) { uint poolerTotalSupply = poolerTokenContract.totalSupply(); uint accountCollateral = poolerTokenContract.balanceOf(account); uint lastSettledOPARound = _settledOPARounds[account]; // poolers OPA reward = settledOPA + unsettledOPA + newMinedOPA uint unsettledOPA = _opaAccShares[_currentOPARound-1].sub(_opaAccShares[lastSettledOPARound]); uint newMinedOPAShare; if (poolerTotalSupply > 0) { uint blocksToReward = block.number.sub(_lastRewardBlock); uint mintedOPA = OPABlockReward.mul(blocksToReward); // OPA share per pooler token newMinedOPAShare = mintedOPA.mul(SHARE_MULTIPLIER) .div(poolerTotalSupply); } return _opaBalance[account] + (unsettledOPA + newMinedOPAShare).mul(accountCollateral) .div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER; } /** * @notice claim OPA; */ function claimOPA() external override whenPoolerNotPaused { // settle un-distributed OPA in rounds to _opaBalance; _settlePooler(msg.sender); // OPA balance modification uint amountOPA = _opaBalance[msg.sender]; delete _opaBalance[msg.sender]; // zero OPA balance // transfer OPA to vesting contract OPAToken.safeTransferFrom(rewardAccount, address(VestingContract), amountOPA); // vest the amount for the sender VestingContract.vest(msg.sender, amountOPA); // log emit OPAClaimed(msg.sender, amountOPA); } /** * @notice settle premium in rounds while pooler token transfers. */ function settlePooler(address account) external override onlyPoolerTokenContract { _settlePooler(account); } /** * @notice settle premium in rounds to _premiumBalance, * settle premium happens before any pooler token exchange such as ERC20-transfer,mint,burn, * and manually claimPremium; * */ function _settlePooler(address account) internal { uint accountCollateral = poolerTokenContract.balanceOf(account); // premium settlement uint premiumBalance = _premiumBalance[account]; for (uint i = 0; i < _options.length; i++) { IOption option = _options[i]; uint lastSettledRound = option.getSettledRound(account); uint newSettledRound = option.getRound() - 1; // premium uint roundPremium = option.getRoundAccPremiumShare(newSettledRound).sub(option.getRoundAccPremiumShare(lastSettledRound)) .mul(accountCollateral) .div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER premiumBalance = premiumBalance.add(roundPremium); // mark new settled round option.setSettledRound(newSettledRound, account); } // log settled premium emit PremiumSettled(msg.sender, accountCollateral, premiumBalance.sub(_premiumBalance[account])); // set back balance to storage _premiumBalance[account] = premiumBalance; // OPA settlement for each pooler token balance change { // update OPA reward snapshot updateOPAReward(); // settle this account uint lastSettledOPARound = _settledOPARounds[account]; uint newSettledOPARound = _currentOPARound - 1; // round OPA uint roundOPA = _opaAccShares[newSettledOPARound].sub(_opaAccShares[lastSettledOPARound]) .mul(accountCollateral) .div(SHARE_MULTIPLIER); // remember to div by SHARE_MULTIPLIER // update OPA balance _opaBalance[account] += roundOPA; // mark new settled OPA round _settledOPARounds[account] = newSettledOPARound; } } /** * @notice net-withdraw amount; */ function NWA() public view override returns (uint) { // get minimum collateral uint minCollateral = _totalPledged() * 100 / maxUtilizationRate; if (minCollateral > collateral) { return 0; } // net withdrawable amount return collateral.sub(minCollateral); } /** * @notice check claimable buyer's profits */ function checkProfits(address account) external override view returns (uint256 profits) { // load from profits balance profits = _profitsBalance[account]; // sum all profits from all options for (uint i = 0; i < _options.length; i++) { profits += checkOptionProfits(_options[i], account); } return profits; } /** * @notice check profits in an option */ function checkOptionProfits(IOption option, address account) internal view returns (uint256 amount) { uint unclaimedRound = option.getUnclaimedProfitsRound(account); if (unclaimedRound == option.getRound()) { return 0; } // accumulate profits in _profitsBalance uint settlePrice = option.getRoundSettlePrice(unclaimedRound); uint strikePrice = option.getRoundStrikePrice(unclaimedRound); uint optionAmount = option.getRoundBalanceOf(unclaimedRound, account); return _calcProfits(settlePrice, strikePrice, optionAmount); } /** * @notice buyers claim option profits */ function claimProfits() external override whenBuyerNotPaused { // settle profits in options for (uint i = 0; i < _options.length; i++) { _settleBuyer(_options[i], msg.sender); } // load and clean profits uint256 accountProfits = _profitsBalance[msg.sender]; delete _profitsBalance[msg.sender]; // send profits _sendProfits(msg.sender, accountProfits); // log emit ProfitsClaim(msg.sender, accountProfits); } /** * @notice settle profits while option token transfers. */ function settleBuyer(address account) external override onlyOptions { _settleBuyer(IOption(msg.sender), account); } /** * @notice settle profits in rounds to _profitsBalance, * settle buyer happens before any option token exchange such as ERC20-transfer,mint,burn, * and manually claimProfits; * */ function _settleBuyer(IOption option, address account) internal { uint unclaimedRound = option.getUnclaimedProfitsRound(account); uint currentRound = option.getRound(); // current round is always unsettled if (unclaimedRound == currentRound) { return; } // accumulate profits in _profitsBalance uint settlePrice = option.getRoundSettlePrice(unclaimedRound); uint strikePrice = option.getRoundStrikePrice(unclaimedRound); uint256 optionAmount = option.getRoundBalanceOf(unclaimedRound, account); uint256 profits = _calcProfits(settlePrice, strikePrice, optionAmount); // add profits to balance; _profitsBalance[account] += profits; // set current round unclaimed option.setUnclaimedProfitsRound(currentRound, account); // log settled profits emit ProfitsSettled(msg.sender, address(option), unclaimedRound, profits); } /** * @notice set pool manager */ function setPoolManager(address poolManager_) external onlyOwner { poolManager = poolManager_; } /** * @notice set updater address */ function setUpdater(address payable updater_) external onlyOwner { updaterAddress = updater_; } /** * @notice set OPA token */ function setOPAToken(IERC20 OPAToken_) external onlyOwner { OPAToken = OPAToken_; } /** * @notice set OPA transfer account */ function setOPARewardAccount(address rewardAccount_) external onlyOwner { rewardAccount = rewardAccount_; } /** * @notice set Vesting contract */ function setVestingContract(IVesting vestingContract_) external onlyOwner { VestingContract = vestingContract_; } /** * @notice set utilization rate by owner */ function setUtilizationRate(uint8 rate) external override onlyOwner { require(rate >=0 && rate <= 100, "[0,100]"); utilizationRate = rate; } /** * @notice set max utilization rate by owner */ function setMaxUtilizationRate(uint8 maxrate) external override onlyOwner { require(maxrate >=0 && maxrate <= 100, "[0,100]"); require(maxrate > utilizationRate, "less than rate"); maxUtilizationRate = maxrate; } /** * @dev get the price for asset with regarding to asset decimals * Example: * for ETH price oracle, this function returns the USDT price for 1 ETH */ function getAssetPrice() public view returns(uint) { (, int latestPrice, , , ) = priceFeed.latestRoundData(); if (latestPrice > 0) { // convert to USDT decimal return uint(latestPrice).mul(10 ** uint256(USDTContract.decimals())) .div(10 ** uint256(priceFeed.decimals())); } return 0; } } /** * @title Implementation of Native Call Option Pool * NativeCallOptionPool Call Option Pool use native currency as collateral and bets * on Chainlink Oracle Price Feed. */ contract NativeCallOptionPool is PandaBase { string private _name; /** * @param priceFeed Chainlink contract for asset price */ constructor(string memory name_, AggregatorV3Interface priceFeed) PandaBase(priceFeed, 18, PoolDirection.CALL) public { _name = name_; // creation of pooler token poolerTokenContract = pandaFactory.createPoolerToken(18, IOptionPool(this)); } /** * @dev Returns the pool of the contract. */ function name() public view override returns (string memory) { return _name; } /** * @notice deposit ethers to this pool directly. */ function deposit() external whenPoolerNotPaused payable { require(msg.value > POOLER_FEE, "0 value"); uint256 value = msg.value.sub(POOLER_FEE); poolerTokenContract.mint(msg.sender, value); collateral = collateral.add(value); // log emit Deposit(msg.sender, value); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(POOLER_FEE); } /** * @notice withdraw the pooled ethers; */ function withdraw(uint amount) external whenPoolerNotPaused payable { require (amount <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded"); require (amount <= NWA(), "collateral exceeded"); require(msg.value >= POOLER_FEE, "0 fee"); // burn pooler token poolerTokenContract.burn(msg.sender, amount); // substract collateral collateral = collateral.sub(amount); // transfer ETH to msg.sender msg.sender.sendValue(amount); // log emit Withdraw(msg.sender, amount); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(msg.value); } /** * @notice sum total collaterals pledged */ function _totalPledged() internal view override returns (uint amount) { for (uint i = 0;i< _options.length;i++) { amount += _options[i].totalSupply(); } } /** * @dev function to calculate option profits */ function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) { // call options get profits due to price rising. if (settlePrice > strikePrice && strikePrice > 0) { // calculate ratio uint ratio = settlePrice.sub(strikePrice) .mul(1e12) // mul by 1e12 here to avoid underflow .div(strikePrice); // calculate ETH profits of this amount uint holderETHProfit = ratio.mul(optionAmount) .div(1e12); // remember to div by 1e12 previous mul-ed return holderETHProfit.mul(99).div(100); } } /** * @dev send profits back to sender's address */ function _sendProfits(address payable account, uint256 amount) internal override { account.sendValue(amount); } /** * @dev get current new option supply */ function _slotSupply(uint) internal view override returns(uint) { return collateral.mul(utilizationRate) .div(100) .div(_options.length); } } /** * @title Implementation of ERC20 Asset Call Option Pool * ERC20 Asset Call Option Pool use ERC20 asset as collateral and bets * on Chainlink Oracle Price Feed. */ contract ERC20CallOptionPool is PandaBase { string private _name; IERC20 public assetContract; /** * @param priceFeed Chainlink contract for asset price * @param assetContract_ ERC20 asset contract address */ constructor(string memory name_, IERC20 assetContract_, AggregatorV3Interface priceFeed) PandaBase(priceFeed, assetContract_.decimals(), PoolDirection.CALL) public { _name = name_; assetContract = assetContract_; poolerTokenContract = pandaFactory.createPoolerToken(assetContract.decimals(), IOptionPool(this)); } /** * @dev Returns the pool of the contract. */ function name() public view override returns (string memory) { return _name; } /** * @notice deposit asset to this pool directly. */ function depositAsset(uint256 amountAsset) external whenPoolerNotPaused payable { require(amountAsset > 0, "0 value"); require(msg.value >= POOLER_FEE, "0 fee"); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(msg.value); assetContract.safeTransferFrom(msg.sender, address(this), amountAsset); poolerTokenContract.mint(msg.sender, amountAsset); collateral = collateral.add(amountAsset); // log emit Deposit(msg.sender, amountAsset); } /** * @notice withdraw the pooled ethers; */ function withdrawAsset(uint amountAsset) external whenPoolerNotPaused payable { require (amountAsset <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded"); require (amountAsset <= NWA(), "collateral exceeded"); require(msg.value >= POOLER_FEE, "0 fee"); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(msg.value); // burn pooler token poolerTokenContract.burn(msg.sender, amountAsset); // substract collateral collateral = collateral.sub(amountAsset); // transfer asset back to msg.sender assetContract.safeTransfer(msg.sender, amountAsset); // log emit Withdraw(msg.sender, amountAsset); } /** * @notice sum total collaterals pledged */ function _totalPledged() internal view override returns (uint amount) { for (uint i = 0;i< _options.length;i++) { amount += _options[i].totalSupply(); } } /** * @dev send profits back to account */ function _sendProfits(address payable account, uint256 amount) internal override { assetContract.safeTransfer(account, amount); } /** * @dev function to calculate option profits */ function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) { // call options get profits due to price rising. if (settlePrice > strikePrice && strikePrice > 0) { // calculate ratio uint ratio = settlePrice.sub(strikePrice) .mul(1e12) // mul by 1e12 here to avoid from underflow .div(strikePrice); // calculate asset profits of this amount uint holderAssetProfit = ratio.mul(optionAmount) .div(1e12); // remember to div by 1e12 previous mul-ed return holderAssetProfit.mul(99).div(100); } } /** * @notice get current new option supply */ function _slotSupply(uint) internal view override returns(uint) { return collateral.mul(utilizationRate) .div(100) .div(_options.length); } } /** * @title Implementation of Put Option Pool * Put Option Pool requires USDT as collateral and * bets on Chainlink Oracle Price Feed of one asset. */ contract PutOptionPool is PandaBase { string private _name; uint private immutable assetPriceUnit; /** * @param priceFeed Chainlink contract for asset price * @param assetDecimal the decimal of the price */ constructor(string memory name_, uint8 assetDecimal, AggregatorV3Interface priceFeed) PandaBase(priceFeed, assetDecimal, PoolDirection.PUT) public { _name = name_; assetPriceUnit = 10 ** uint(assetDecimal); poolerTokenContract = pandaFactory.createPoolerToken(USDTContract.decimals(), IOptionPool(this)); } /** * @dev Returns the pool of the contract. */ function name() public view override returns (string memory) { return _name; } /** * @notice deposit of Tether USDTS, user needs * to approve() to this contract address first, * and call with the given amount. */ function depositUSDT(uint256 amountUSDT) external whenPoolerNotPaused payable { require(amountUSDT > 0, "0 value"); require(msg.value >= POOLER_FEE, "0 fee"); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(msg.value); USDTContract.safeTransferFrom(msg.sender, address(this), amountUSDT); poolerTokenContract.mint(msg.sender, amountUSDT); collateral = collateral.add(amountUSDT); // log emit Deposit(msg.sender, amountUSDT); } /** * @notice withdraw the pooled USDT; */ function withdrawUSDT(uint amountUSDT) external whenPoolerNotPaused payable { require (amountUSDT <= poolerTokenContract.balanceOf(msg.sender), "balance exceeded"); require (amountUSDT <= NWA(), "collateral exceeded"); require (msg.value >= POOLER_FEE, "0 fee"); // transfer POOLER_FEE to updaterAddress updaterAddress.sendValue(msg.value); // burn pooler token poolerTokenContract.burn(msg.sender, amountUSDT); // substract collateral collateral = collateral.sub(amountUSDT); // transfer USDT to msg.sender USDTContract.safeTransfer(msg.sender, amountUSDT); // log emit Withdraw(msg.sender, amountUSDT); } /** * @notice sum total collaterals pledged */ function _totalPledged() internal view override returns (uint) { // sum total collateral in USDT uint total; for (uint i = 0;i< _options.length;i++) { // derive collaterals at issue time total = total.add(_options[i].totalSupply() * _options[i].strikePrice()); } // @dev remember to div with asset price unit total /= assetPriceUnit; return total; } /** * @dev send profits back to account */ function _sendProfits(address payable account, uint256 amount) internal override { USDTContract.safeTransfer(account, amount); } /** * @dev function to calculate option profits */ function _calcProfits(uint settlePrice, uint strikePrice, uint optionAmount) internal view override returns(uint256 profits) { if (settlePrice < strikePrice && strikePrice > 0) { // put option get profits at this round // calculate ratio uint ratio = strikePrice.sub(settlePrice) .mul(1e12) // mul 1e12 to avoid from underflow .div(strikePrice); // holder share uint holderShare = ratio.mul(optionAmount); // convert to USDT profits uint holderUSDTProfit = holderShare.mul(strikePrice) .div(1e12) // remember to div 1e12 previous multipied .div(assetPriceUnit); // remember to div price unit return holderUSDTProfit.mul(99).div(100); } } /** * @notice get current new option supply */ function _slotSupply(uint assetPrice) internal view override returns(uint) { // Formula : (collateral / numOptions) * utilizationRate / 100 / (assetPrice/ price unit) return collateral.mul(utilizationRate) .mul(assetPriceUnit) .div(100) .div(_options.length) .div(assetPrice); } }
create a memory copy of array
IOption [] memory options = _options;
12,715,320
[ 1, 2640, 279, 3778, 1610, 434, 526, 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, 1665, 375, 5378, 3778, 702, 273, 389, 2116, 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 ]
./partial_match/1/0xa22cf004eD5105608b39c48bE688BD9B9026a046/sources/FeePool.sol
* @notice The fees available to be withdrawn by a specific account, priced in currencyKey currency @dev Returns two amounts, one for fees and one for SNX rewards @param currencyKey The currency you want to price the fees in/ Add up the fees Fees & Rewards in fee period [0] are not yet available for withdrawal
function feesAvailable(address account, bytes4 currencyKey) public view returns (uint, uint) { uint[2][FEE_PERIOD_LENGTH] memory userFees = feesByPeriod(account); uint totalFees = 0; uint totalRewards = 0; for (uint i = 1; i < FEE_PERIOD_LENGTH; i++) { totalFees = totalFees.add(userFees[i][0]); totalRewards = totalRewards.add(userFees[i][1]); } synthetix.effectiveValue("XDR", totalFees, currencyKey), totalRewards ); }
4,057,469
[ 1, 1986, 1656, 281, 2319, 358, 506, 598, 9446, 82, 635, 279, 2923, 2236, 16, 6205, 72, 316, 5462, 653, 5462, 225, 2860, 2795, 30980, 16, 1245, 364, 1656, 281, 471, 1245, 364, 14204, 60, 283, 6397, 225, 5462, 653, 1021, 5462, 1846, 2545, 358, 6205, 326, 1656, 281, 316, 19, 1436, 731, 326, 1656, 281, 5782, 281, 473, 534, 359, 14727, 316, 14036, 3879, 306, 20, 65, 854, 486, 4671, 2319, 364, 598, 9446, 287, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1656, 281, 5268, 12, 2867, 2236, 16, 1731, 24, 5462, 653, 13, 203, 3639, 1071, 203, 3639, 1476, 203, 3639, 1135, 261, 11890, 16, 2254, 13, 203, 565, 288, 203, 3639, 2254, 63, 22, 6362, 8090, 41, 67, 28437, 67, 7096, 65, 3778, 729, 2954, 281, 273, 1656, 281, 858, 5027, 12, 4631, 1769, 203, 203, 3639, 2254, 2078, 2954, 281, 273, 374, 31, 203, 3639, 2254, 2078, 17631, 14727, 273, 374, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 404, 31, 277, 411, 478, 9383, 67, 28437, 67, 7096, 31, 277, 27245, 288, 203, 5411, 2078, 2954, 281, 273, 2078, 2954, 281, 18, 1289, 12, 1355, 2954, 281, 63, 77, 6362, 20, 19226, 203, 5411, 2078, 17631, 14727, 273, 2078, 17631, 14727, 18, 1289, 12, 1355, 2954, 281, 63, 77, 6362, 21, 19226, 203, 3639, 289, 203, 203, 5411, 6194, 451, 278, 697, 18, 28894, 620, 2932, 60, 6331, 3113, 2078, 2954, 281, 16, 5462, 653, 3631, 203, 5411, 2078, 17631, 14727, 203, 3639, 11272, 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 ]
pragma solidity ^0.4.4; contract Token { /// @return total amount of tokens function totalSupply() constant returns (uint256 supply) {} /// @param _owner The address from which the balance will be retrieved /// @return The balance function balanceOf(address _owner) constant returns (uint256 balance) {} /// @notice send `_value` token to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _value) returns (bool success) {} /// @notice send `_value` token to `_to` from `_from` on the condition it is approved by `_from` /// @param _from The address of the sender /// @param _to The address of the recipient /// @param _value The amount of token to be transferred /// @return Whether the transfer was successful or not function transferFrom(address _from, address _to, uint256 _value) returns (bool success) {} /// @notice `msg.sender` approves `_addr` to spend `_value` tokens /// @param _spender The address of the account able to transfer the tokens /// @param _value The amount of wei to be approved for transfer /// @return Whether the approval was successful or not function approve(address _spender, uint256 _value) returns (bool success) {} /// @param _owner The address of the account owning tokens /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens allowed to spent function allowance(address _owner, address _spender) constant returns (uint256 remaining) {} event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); } contract StandardToken is Token { function transfer(address _to, uint256 _value) returns (bool success) { if (balances[msg.sender] >= _value && (balances[_to] + _value) > balances[_to] && _value > 0) { balances[msg.sender] -= _value; balances[_to] += _value; Transfer(msg.sender, _to, _value); return true; } else { return false; } } function transferFrom(address _from, address _to, uint256 _value) returns (bool success) { if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to] && _value > 0) { balances[_to] += _value; balances[_from] -= _value; allowed[_from][msg.sender] -= _value; Transfer(_from, _to, _value); return true; } else { return false; } } function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } function approve(address _spender, uint256 _value) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) allowed; uint256 public totalSupply; } contract IAHCToken is StandardToken { string public constant name = "IAHC"; string public constant symbol = "IAHC"; uint8 public constant decimals = 8; uint public constant decimals_multiplier = 100000000; address public constant ESCROW_WALLET = 0x3D7FaD8174dac0df6a0a3B473b9569f7618d07E2; uint public constant icoSupply = 500000000 * decimals_multiplier; //0,5 billion (500,000,000 IAHC coins will be available for purchase (25% of total IAHC) uint public constant icoTokensPrice = 142000; //wei / decimals, base price: 0.0000142 ETH per 1 IAHC uint public constant icoMinCap = 100 ether; uint public constant icoMaxCap = 7000 ether; uint public constant whiteListMinAmount = 0.50 ether; uint public constant preSaleMinAmount = 0.25 ether; uint public constant crowdSaleMinAmount = 0.10 ether; address public icoOwner; uint public icoLeftSupply = icoSupply; //current left tokens to sell during ico uint public icoSoldCap = 0; //current sold value in wei uint public whiteListTime = 1519084800; //20.02.2018 (40% discount) uint public preSaleListTime = 1521590400; //21.03.2018 (28% discount) uint public crowdSaleTime = 1524355200; //22.04.2018 (10% discount) uint public crowdSaleEndTime = 1526947200; //22.05.2018 (0% discount) uint public icoEndTime = 1529712000; //23.06.2018 uint public guarenteedPaybackTime = 1532304000; //23.07.2018 mapping(address => bool) public whiteList; mapping(address => uint) public icoContributions; function IAHCToken(){ icoOwner = msg.sender; balances[icoOwner] = 2000000000 * decimals_multiplier - icoSupply; //froze ico tokens totalSupply = 2000000000 * decimals_multiplier; } modifier onlyOwner() { require(msg.sender == icoOwner); _; } //unfroze tokens if some left unsold from ico function icoEndUnfrozeTokens() public onlyOwner() returns(bool) { require(now >= icoEndTime && icoLeftSupply > 0); balances[icoOwner] += icoLeftSupply; icoLeftSupply = 0; } //if soft cap is not reached - participant can ask ethers back function minCapFail() public { require(now >= icoEndTime && icoSoldCap < icoMinCap); require(icoContributions[msg.sender] > 0 && balances[msg.sender] > 0); uint tokens = balances[msg.sender]; balances[icoOwner] += tokens; balances[msg.sender] -= tokens; uint contribution = icoContributions[msg.sender]; icoContributions[msg.sender] = 0; Transfer(msg.sender, icoOwner, tokens); msg.sender.transfer(contribution); } // for info function getCurrentStageDiscount() public constant returns (uint) { uint discount = 0; if (now >= icoEndTime && now < preSaleListTime) { discount = 40; } else if (now < crowdSaleTime) { discount = 28; } else if (now < crowdSaleEndTime) { discount = 10; } return discount; } function safePayback(address receiver, uint amount) public onlyOwner() { require(now >= guarenteedPaybackTime); require(icoSoldCap < icoMinCap); receiver.transfer(amount); } // count tokens i could buy now function countTokens(uint paid, address sender) public constant returns (uint) { uint discount = 0; if (now < preSaleListTime) { require(whiteList[sender]); require(paid >= whiteListMinAmount); discount = 40; } else if (now < crowdSaleTime) { require(paid >= preSaleMinAmount); discount = 28; } else if (now < crowdSaleEndTime) { require(paid >= crowdSaleMinAmount); discount = 10; } uint tokens = paid / icoTokensPrice; if (discount > 0) { tokens = tokens / (100 - discount) * 100; } return tokens; } // buy tokens if you can function () public payable { contribute(); } function contribute() public payable { require(now >= whiteListTime && now < icoEndTime && icoLeftSupply > 0); uint tokens = countTokens(msg.value, msg.sender); uint payback = 0; if (icoLeftSupply < tokens) { //not enough tokens so we need to return some ethers back payback = msg.value - (msg.value / tokens) * icoLeftSupply; tokens = icoLeftSupply; } uint contribution = msg.value - payback; icoLeftSupply -= tokens; balances[msg.sender] += tokens; icoSoldCap += contribution; icoContributions[msg.sender] += contribution; Transfer(icoOwner, msg.sender, tokens); if (icoSoldCap >= icoMinCap) { ESCROW_WALLET.transfer(this.balance); } if (payback > 0) { msg.sender.transfer(payback); } } //lists function addToWhitelist(address _participant) public onlyOwner() returns(bool) { if (whiteList[_participant]) { return true; } whiteList[_participant] = true; return true; } function removeFromWhitelist(address _participant) public onlyOwner() returns(bool) { if (!whiteList[_participant]) { return true; } whiteList[_participant] = false; return true; } }
22.05.2018 (0% discount)
uint public crowdSaleEndTime = 1526947200;
1,557,141
[ 1, 3787, 18, 6260, 18, 21849, 261, 20, 9, 12137, 13, 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, 2254, 1071, 276, 492, 72, 30746, 25255, 1377, 273, 4711, 5558, 29, 9462, 6976, 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 ]
// File: @openzeppelin/contracts/math/SafeMath.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 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; } } // 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; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.6.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. */ 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; } } // File: @openzeppelin/contracts/utils/Pausable.sol pragma solidity ^0.6.0; /** * @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. */ 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 () internal { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view 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()); } } // File: @openzeppelin/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.6.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]. */ 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/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); } // File: contracts/ISparkleTimestamp.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; // import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; // import "../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol"; // import "../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol"; // import "../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol"; /** * @dev Sparkle Timestamp Contract * @author SparkleMobile Inc. (c) 2019-2020 */ interface ISparkleTimestamp { /** * @dev Add new reward timestamp for address * @param _rewardAddress being added to timestamp collection */ function addTimestamp(address _rewardAddress) external returns(bool); /** * @dev Reset timestamp maturity for loyalty address * @param _rewardAddress to have reward period reset */ function resetTimestamp(address _rewardAddress) external returns(bool); /** * @dev Zero/delete existing loyalty timestamp entry * @param _rewardAddress being requested for timestamp deletion * @notice Test(s) not passed */ function deleteTimestamp(address _rewardAddress) external returns(bool); /** * @dev Get address confirmation for loyalty address * @param _rewardAddress being queried for address information */ function getAddress(address _rewardAddress) external returns(address); /** * @dev Get timestamp of initial joined timestamp for loyalty address * @param _rewardAddress being queried for timestamp information */ function getJoinedTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Get timestamp of last deposit for loyalty address * @param _rewardAddress being queried for timestamp information */ function getDepositTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Get timestamp of reward maturity for loyalty address * @param _rewardAddress being queried for timestamp information */ function getRewardTimestamp(address _rewardAddress) external returns(uint256); /** * @dev Determine if address specified has a timestamp record * @param _rewardAddress being queried for timestamp existance */ function hasTimestamp(address _rewardAddress) external returns(bool); /** * @dev Calculate time remaining in seconds until this address' reward matures * @param _rewardAddress to query remaining time before reward matures */ function getTimeRemaining(address _rewardAddress) external returns(uint256, bool, uint256); /** * @dev Determine if reward is mature for address * @param _rewardAddress Address requesting addition in to loyalty timestamp collection */ function isRewardReady(address _rewardAddress) external returns(bool); /** * @dev Change the stored loyalty controller contract address * @param _newAddress of new loyalty controller contract address */ function setContractAddress(address _newAddress) external; /** * @dev Return the stored authorized controller address * @return Address of loyalty controller contract */ function getContractAddress() external returns(address); /** * @dev Change the stored loyalty time period * @param _newTimePeriod of new reward period (in seconds) */ function setTimePeriod(uint256 _newTimePeriod) external; /** * @dev Return the current loyalty timer period * @return Current stored value of loyalty time period */ function getTimePeriod() external returns(uint256); /** * @dev Event signal: Reset timestamp */ event ResetTimestamp(address _rewardAddress); /** * @dev Event signal: Loyalty contract address waws changed */ event ContractAddressChanged(address indexed _previousAddress, address indexed _newAddress); /** * @dev Event signal: Loyalty reward time period was changed */ event TimePeriodChanged( uint256 indexed _previousTimePeriod, uint256 indexed _newTimePeriod); /** * @dev Event signal: Loyalty reward timestamp was added */ event TimestampAdded( address indexed _newTimestampAddress ); /** * @dev Event signal: Loyalty reward timestamp was removed */ event TimestampDeleted( address indexed _newTimestampAddress ); /** * @dev Event signal: Timestamp for address was reset */ event TimestampReset(address _rewardAddress); } // File: contracts/ISparkleRewardTiers.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; // import '../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol'; // import '../node_modules/openzeppelin-solidity/contracts/ownership/Ownable.sol'; // import '../node_modules/openzeppelin-solidity/contracts/lifecycle/Pausable.sol'; // import '../node_modules/openzeppelin-solidity/contracts/utils/ReentrancyGuard.sol'; /** * @title A contract for managing reward tiers * @author SparkleLoyalty Inc. (c) 2019-2020 */ // interface ISparkleRewardTiers is Ownable, Pausable, ReentrancyGuard { interface ISparkleRewardTiers { /** * @dev Add a new reward tier to the contract for future proofing * @param _index of the new reward tier to add * @param _rate of the added reward tier * @param _price of the added reward tier * @param _enabled status of the added reward tier * @notice Test(s) Need rewrite */ function addTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Update an existing reward tier with new values * @param _index of reward tier to update * @param _rate of the reward tier * @param _price of the reward tier * @param _enabled status of the reward tier * @return (bool) indicating success/failure * @notice Test(s) Need rewrite */ function updateTier(uint256 _index, uint256 _rate, uint256 _price, bool _enabled) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Remove an existing reward tier from list of tiers * @param _index of reward tier to remove * @notice Test(s) Need rewrite */ function deleteTier(uint256 _index) external // view // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Get the rate value of specified tier * @param _index of tier to query * @return specified reward tier rate * @notice Test(s) Need rewrite */ function getRate(uint256 _index) external // view // whenNotPaused returns(uint256); /** * @dev Get price of tier * @param _index of tier to query * @return uint256 indicating tier price * @notice Test(s) Need rewrite */ function getPrice(uint256 _index) external // view // whenNotPaused returns(uint256); /** * @dev Get the enabled status of tier * @param _index of tier to query * @return bool indicating status of tier * @notice Test(s) Need rewrite */ function getEnabled(uint256 _index) external // view // whenNotPaused returns(bool); /** * @dev Withdraw ether that has been sent directly to the contract * @return bool indicating withdraw success * @notice Test(s) Need rewrite */ function withdrawEth() external // onlyOwner // whenNotPaused // nonReentrant returns(bool); /** * @dev Event triggered when a reward tier is deleted * @param _index of tier to deleted */ event TierDeleted(uint256 _index); /** * @dev Event triggered when a reward tier is updated * @param _index of the updated tier * @param _rate of updated tier * @param _price of updated tier * @param _enabled status of updated tier */ event TierUpdated(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); /** * @dev Event triggered when a new reward tier is added * @param _index of the tier added * @param _rate of added tier * @param _price of added tier * @param _enabled status of added tier */ event TierAdded(uint256 _index, uint256 _rate, uint256 _price, bool _enabled); } // File: contracts/SparkleLoyalty.sol /// SWC-103: Floating Pragma pragma solidity 0.6.12; /** * @dev Sparkle Loyalty Rewards * @author SparkleMobile Inc. */ contract SparkleLoyalty is Ownable, Pausable, ReentrancyGuard { /** * @dev Ensure math safety through SafeMath */ using SafeMath for uint256; // Gas to send with certain transations that may cost more in the future due to chain growth uint256 private gasToSendWithTX = 25317; // Base rate APR (5%) factored to 365.2422 gregorian days uint256 private baseRate = 0.00041069 * 10e7; // A full year is 365.2422 gregorian days (5%) // Account data structure struct Account { address _address; // Loyalty reward address uint256 _balance; // Total tokens deposited uint256 _collected; // Total tokens collected uint256 _claimed; // Total succesfull reward claims uint256 _joined; // Total times address has joined uint256 _tier; // Tier index of reward tier bool _isLocked; // Is the account locked } // tokenAddress of erc20 token address address private tokenAddress; // timestampAddress of time stamp contract address address private timestampAddress; // treasuryAddress of token treeasury address address private treasuryAddress; // collectionAddress to receive eth payed for tier upgrades address private collectionAddress; // rewardTiersAddress to resolve reward tier specifications address private tiersAddress; // minProofRequired to deposit of rewards to be eligibile uint256 private minRequired; // maxProofAllowed for deposit to be eligibile uint256 private maxAllowed; // totalTokensClaimed of all rewards awarded uint256 private totalTokensClaimed; // totalTimesClaimed of all successfully claimed rewards uint256 private totalTimesClaimed; // totalActiveAccounts count of all currently active addresses uint256 private totalActiveAccounts; // Accounts mapping of user loyalty records mapping(address => Account) private accounts; /** * @dev Sparkle Loyalty Rewards Program contract .cTor * @param _tokenAddress of token used for proof of loyalty rewards * @param _treasuryAddress of proof of loyalty token reward distribution * @param _collectionAddress of ethereum account to collect tier upgrade eth * @param _tiersAddress of the proof of loyalty tier rewards support contract * @param _timestampAddress of the proof of loyalty timestamp support contract */ constructor(address _tokenAddress, address _treasuryAddress, address _collectionAddress, address _tiersAddress, address _timestampAddress) public Ownable() Pausable() ReentrancyGuard() { // Initialize contract internal addresse(s) from params tokenAddress = _tokenAddress; treasuryAddress = _treasuryAddress; collectionAddress = _collectionAddress; tiersAddress = _tiersAddress; timestampAddress = _timestampAddress; // Initialize minimum/maximum allowed deposit limits minRequired = uint256(1000).mul(10e7); maxAllowed = uint256(250000).mul(10e7); } /** * @dev Deposit additional tokens to a reward address loyalty balance * @param _depositAmount of tokens to deposit into a reward address balance * @return bool indicating the success of the deposit operation (true == success) */ function depositLoyalty(uint _depositAmount) public whenNotPaused nonReentrant returns (bool) { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}1'); // Validate specified value meets minimum requirements require(_depositAmount >= minRequired, 'Minimum required'); // Determine if caller has approved enough allowance for this deposit if(IERC20(tokenAddress).allowance(msg.sender, address(this)) < _depositAmount) { // No, rever informing that deposit amount exceeded allownce amount revert('Exceeds allowance'); } // Obtain a storage instsance of callers account record Account storage loyaltyAccount = accounts[msg.sender]; // Determine if there is an upper deposit cap if(maxAllowed > 0) { // Yes, determine if the deposit amount + current balance exceed max deposit cap if(loyaltyAccount._balance.add(_depositAmount) > maxAllowed || _depositAmount > maxAllowed) { // Yes, revert informing that the maximum deposit cap has been exceeded revert('Exceeds cap'); } } // Determine if the tier selected is enabled if(!ISparkleRewardTiers(tiersAddress).getEnabled(loyaltyAccount._tier)) { // No, then this tier cannot be selected revert('Invalid tier'); } // Determine of transfer from caller has succeeded if(IERC20(tokenAddress).transferFrom(msg.sender, address(this), _depositAmount)) { // Yes, thend determine if the specified address has a timestamp record if(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender)) { // Yes, update callers account balance by deposit amount loyaltyAccount._balance = loyaltyAccount._balance.add(_depositAmount); // Reset the callers reward timestamp _resetTimestamp(msg.sender); // emit DepositLoyaltyEvent(msg.sender, _depositAmount, true); // Return success return true; } // Determine if a timestamp has been added for caller if(!ISparkleTimestamp(timestampAddress).addTimestamp(msg.sender)) { // No, revert indicating there was some kind of error revert('No timestamp created'); } // Prepare loyalty account record loyaltyAccount._address = address(msg.sender); loyaltyAccount._balance = _depositAmount; loyaltyAccount._joined = loyaltyAccount._joined.add(1); // Update global account counter totalActiveAccounts = totalActiveAccounts.add(1); // emit DepositLoyaltyEvent(msg.sender, _depositAmount, false); // Return success return true; } // Return failure return false; } /** * @dev Claim Sparkle Loyalty reward */ function claimLoyaltyReward() public whenNotPaused nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Validate caller has a timestamp and it has matured require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No record'); require(ISparkleTimestamp(timestampAddress).isRewardReady(msg.sender), 'Not mature'); // Obtain the current state of the callers timestamp (uint256 timeRemaining, bool isReady, uint256 rewardDate) = ISparkleTimestamp(timestampAddress).getTimeRemaining(msg.sender); // Determine if the callers reward has matured if(isReady) { // Value not used but throw unused var warning (cleanup) rewardDate = 0; // Yes, then obtain a storage instance of callers account record Account storage loyaltyAccount = accounts[msg.sender]; // Obtain values required for caculations uint256 dayCount = (timeRemaining.div(ISparkleTimestamp(timestampAddress).getTimePeriod())).add(1); uint256 tokenBalance = loyaltyAccount._balance.add(loyaltyAccount._collected); uint256 rewardRate = ISparkleRewardTiers(tiersAddress).getRate(loyaltyAccount._tier); uint256 rewardTotal = baseRate.mul(tokenBalance).mul(rewardRate).mul(dayCount).div(10e7).div(10e7); // Increment collected by reward total loyaltyAccount._collected = loyaltyAccount._collected.add(rewardTotal); // Increment total number of times a reward has been claimed loyaltyAccount._claimed = loyaltyAccount._claimed.add(1); // Incrememtn total number of times rewards have been collected by all totalTimesClaimed = totalTimesClaimed.add(1); // Increment total number of tokens claimed totalTokensClaimed += rewardTotal; // Reset the callers timestamp record _resetTimestamp(msg.sender); // Emit event log to the block chain for future web3 use emit RewardClaimedEvent(msg.sender, rewardTotal); // Return success return true; } // Revert opposed to returning boolean (May or may not return a txreceipt) revert('Failed claim'); } /** * @dev Withdraw the current deposit balance + any earned loyalty rewards */ function withdrawLoyalty() public whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(msg.sender), 'No timestamp2'); // Determine if the account has been locked if(accounts[msg.sender]._isLocked) { // Yes, revert informing that this loyalty account has been locked revert('Locked'); } // Obtain values needed from account record before zeroing uint256 joinCount = accounts[msg.sender]._joined; uint256 collected = accounts[msg.sender]._collected; uint256 deposit = accounts[msg.sender]._balance; bool isLocked = accounts[msg.sender]._isLocked; // Zero out the callers account record Account storage account = accounts[msg.sender]; account._address = address(0x0); account._balance = 0x0; account._collected = 0x0; account._joined = joinCount; account._claimed = 0x0; account._tier = 0x0; // Preserve account lock even after withdraw (account always locked) account._isLocked = isLocked; // Decement the total number of active accounts totalActiveAccounts = totalActiveAccounts.sub(1); // Delete the callers timestamp record _deleteTimestamp(msg.sender); // Determine if transfer from treasury address is a success if(!IERC20(tokenAddress).transferFrom(treasuryAddress, msg.sender, collected)) { // No, revert indicating that the transfer and wisthdraw has failed revert('Withdraw failed'); } // Determine if transfer from contract address is a sucess if(!IERC20(tokenAddress).transfer(msg.sender, deposit)) { // No, revert indicating that the treansfer and withdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyWithdrawnEvent(msg.sender, deposit.add(collected)); } function returnLoyaltyDeposit(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 deposit = accounts[_rewardAddress]._balance; Account storage account = accounts[_rewardAddress]; account._balance = 0x0; // Determine if transfer from contract address is a sucess if(!IERC20(tokenAddress).transfer(_rewardAddress, deposit)) { // No, revert indicating that the treansfer and withdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyDepositWithdrawnEvent(_rewardAddress, deposit); } function returnLoyaltyCollected(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 collected = accounts[_rewardAddress]._collected; Account storage account = accounts[_rewardAddress]; account._collected = 0x0; // Determine if transfer from treasury address is a success if(!IERC20(tokenAddress).transferFrom(treasuryAddress, _rewardAddress, collected)) { // No, revert indicating that the transfer and wisthdraw has failed revert('Withdraw failed'); } // Emit event log to the block chain for future web3 use emit LoyaltyCollectedWithdrawnEvent(_rewardAddress, collected); } function removeLoyaltyAccount(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // validate that caller has a loyalty timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b'); // Validate that reward address is locked require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 joinCount = accounts[_rewardAddress]._joined; Account storage account = accounts[_rewardAddress]; account._address = address(0x0); account._balance = 0x0; account._collected = 0x0; account._joined = joinCount; account._claimed = 0x0; account._tier = 0x0; account._isLocked = false; // Decement the total number of active accounts totalActiveAccounts = totalActiveAccounts.sub(1); // Delete the callers timestamp record _deleteTimestamp(_rewardAddress); emit LoyaltyAccountRemovedEvent(_rewardAddress); } /** * @dev Gets the locked status of the specified address * @param _loyaltyAddress of account * @return (bool) indicating locked status */ function isLocked(address _loyaltyAddress) public view whenNotPaused returns (bool) { return accounts[_loyaltyAddress]._isLocked; } function lockAccount(address _rewardAddress, bool _value) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); require(_rewardAddress != address(0x0), 'Invalid {reward}'); // Validate specified address has timestamp require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timstamp'); // Set the specified address' locked status accounts[_rewardAddress]._isLocked = _value; // Emit event log to the block chain for future web3 use emit LockedAccountEvent(_rewardAddress, _value); } /** * @dev Gets the storage address value of the specified address * @param _loyaltyAddress of account * @return (address) indicating the address stored calls account record */ function getLoyaltyAddress(address _loyaltyAddress) public view whenNotPaused returns(address) { return accounts[_loyaltyAddress]._address; } /** * @dev Get the deposit balance value of specified address * @param _loyaltyAddress of account * @return (uint256) indicating the balance value */ function getDepositBalance(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._balance; } /** * @dev Get the tokens collected by the specified address * @param _loyaltyAddress of account * @return (uint256) indicating the tokens collected */ function getTokensCollected(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._collected; } /** * @dev Get the total balance (deposit + collected) of tokens * @param _loyaltyAddress of account * @return (uint256) indicating total balance */ function getTotalBalance(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._balance.add(accounts[_loyaltyAddress]._collected); } /** * @dev Get the times loyalty has been claimed * @param _loyaltyAddress of account * @return (uint256) indicating total time claimed */ function getTimesClaimed(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._claimed; } /** * @dev Get total number of times joined * @param _loyaltyAddress of account * @return (uint256) */ function getTimesJoined(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._joined; } /** * @dev Get time remaining before reward maturity * @param _loyaltyAddress of account * @return (uint256, bool) Indicating time remaining/past and boolean indicating maturity */ function getTimeRemaining(address _loyaltyAddress) public whenNotPaused returns (uint256, bool, uint256) { (uint256 remaining, bool status, uint256 deposit) = ISparkleTimestamp(timestampAddress).getTimeRemaining(_loyaltyAddress); return (remaining, status, deposit); } /** * @dev Withdraw any ether that has been sent directly to the contract * @param _loyaltyAddress of account * @return Total number of tokens that have been claimed by users * @notice Test(s) Not written */ function getRewardTier(address _loyaltyAddress) public view whenNotPaused returns(uint256) { return accounts[_loyaltyAddress]._tier; } /** * @dev Select reward tier for msg.sender * @param _tierSelected id of the reward tier interested in purchasing * @return (bool) indicating failure/success */ function selectRewardTier(uint256 _tierSelected) public payable whenNotPaused nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address has a timestamp require(accounts[msg.sender]._address == address(msg.sender), 'No timestamp3'); // Validate tier selection require(accounts[msg.sender]._tier != _tierSelected, 'Already selected'); // Validate that ether was sent with the call require(msg.value > 0, 'No ether'); // Determine if the specified rate is > than existing rate if(ISparkleRewardTiers(tiersAddress).getRate(accounts[msg.sender]._tier) >= ISparkleRewardTiers(tiersAddress).getRate(_tierSelected)) { // No, revert indicating failure revert('Invalid tier'); } // Determine if ether transfer for tier upgrade has completed successfully (bool success, ) = address(collectionAddress).call{value: ISparkleRewardTiers(tiersAddress).getPrice(_tierSelected), gas: gasToSendWithTX}(''); require(success, 'Rate unchanged'); // Update callers rate with the new selected rate accounts[msg.sender]._tier = _tierSelected; emit TierSelectedEvent(msg.sender, _tierSelected); // Return success return true; } function getRewardTiersAddress() public view whenNotPaused returns(address) { return tiersAddress; } /** * @dev Set tier collectionm address * @param _newAddress of new collection address * @notice Test(s) not written */ function setRewardTiersAddress(address _newAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address is valid require(_newAddress != address(0), 'Invalid {reward}'); // Set tier rewards contract address tiersAddress = _newAddress; emit TiersAddressChanged(_newAddress); } function getCollectionAddress() public view whenNotPaused returns(address) { return collectionAddress; } /** @notice Test(s) passed * @dev Set tier collectionm address * @param _newAddress of new collection address */ function setCollectionAddress(address _newAddress) public whenNotPaused onlyOwner nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {From}'); // Validate specified address is valid require(_newAddress != address(0), 'Invalid {collection}'); // Set tier collection address collectionAddress = _newAddress; emit CollectionAddressChanged(_newAddress); } function getTreasuryAddress() public view whenNotPaused returns(address) { return treasuryAddress; } /** * @dev Set treasury address * @param _newAddress of the treasury address * @notice Test(s) passed */ function setTreasuryAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Validate specified address require(_newAddress != address(0), "Invalid {treasury}"); // Set current treasury contract address treasuryAddress = _newAddress; emit TreasuryAddressChanged(_newAddress); } function getTimestampAddress() public view whenNotPaused returns(address) { return timestampAddress; } /** * @dev Set the timestamp address * @param _newAddress of timestamp address * @notice Test(s) passed */ function setTimestampAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Set current timestamp contract address timestampAddress = _newAddress; emit TimestampAddressChanged(_newAddress); } function getTokenAddress() public view whenNotPaused returns(address) { return tokenAddress; } /** * @dev Set the loyalty token address * @param _newAddress of the new token address * @notice Test(s) passed */ function setTokenAddress(address _newAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), "Invalid {from}"); // Set current token contract address tokenAddress = _newAddress; emit TokenAddressChangedEvent(_newAddress); } function getSentGasAmount() public view whenNotPaused returns(uint256) { return gasToSendWithTX; } function setSentGasAmount(uint256 _amount) public onlyOwner whenNotPaused { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Set the current minimum deposit allowed gasToSendWithTX = _amount; emit GasSentChanged(_amount); } function getBaseRate() public view whenNotPaused returns(uint256) { return baseRate; } function setBaseRate(uint256 _newRate) public onlyOwner whenNotPaused { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Set the current minimum deposit allowed baseRate = _newRate; emit BaseRateChanged(_newRate); } /** * @dev Set the minimum Proof Of Loyalty amount allowed for deposit * @param _minProof amount for new minimum accepted loyalty reward deposit * @notice _minProof value is multiplied internally by 10e7. Do not multiply before calling! */ function setMinProof(uint256 _minProof) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); // Validate specified minimum is not lower than 1000 tokens require(_minProof >= 1000, 'Invalid amount'); // Set the current minimum deposit allowed minRequired = _minProof.mul(10e7); emit MinProofChanged(minRequired); } event MinProofChanged(uint256); /** * @dev Get the minimum Proof Of Loyalty amount allowed for deposit * @return Amount of tokens required for Proof Of Loyalty Rewards * @notice Test(s) passed */ function getMinProof() public view whenNotPaused returns(uint256) { // Return indicating minimum deposit allowed return minRequired; } /** * @dev Set the maximum Proof Of Loyalty amount allowed for deposit * @param _maxProof amount for new maximum loyalty reward deposit * @notice _maxProof value is multiplied internally by 10e7. Do not multiply before calling! * @notice Smallest maximum value is 1000 + _minProof amount. (Ex: If _minProof == 1000 then smallest _maxProof possible is 2000) */ function setMaxProof(uint256 _maxProof) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0), 'Invalid {from}'); require(_maxProof >= 2000, 'Invalid amount'); // Set allow maximum deposit maxAllowed = _maxProof.mul(10e7); } /** * @dev Get the maximum Proof Of Loyalty amount allowed for deposit * @return Maximum amount of tokens allowed for Proof Of Loyalty deposit * @notice Test(s) passed */ function getMaxProof() public view whenNotPaused returns(uint256) { // Return indicating current allowed maximum deposit return maxAllowed; } /** * @dev Get the total number of tokens claimed by all users * @return Total number of tokens that have been claimed by users * @notice Test(s) Not written */ function getTotalTokensClaimed() public view whenNotPaused returns(uint256) { // Return indicating total number of tokens that have been claimed by all return totalTokensClaimed; } /** * @dev Get total number of times rewards have been claimed for all users * @return Total number of times rewards have been claimed */ function getTotalTimesClaimed() public view whenNotPaused returns(uint256) { // Return indicating total number of tokens that have been claimed by all return totalTimesClaimed; } /** * @dev Withdraw any ether that has been sent directly to the contract */ function withdrawEth(address _toAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_toAddress != address(0x0), 'Invalid {to}'); // Validate there is ether to withdraw require(address(this).balance > 0, 'No ether'); // Determine if ether transfer of stored ether has completed successfully // require(address(_toAddress).call.value(address(this).balance).gas(gasToSendWithTX)(), 'Withdraw failed'); (bool success, ) = address(_toAddress).call{value:address(this).balance, gas: gasToSendWithTX}(''); require(success, 'Withdraw failed'); } /** * @dev Withdraw any ether that has been sent directly to the contract * @param _toAddress to receive any stored token balance */ function withdrawTokens(address _toAddress) public onlyOwner whenNotPaused nonReentrant { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_toAddress != address(0), "Invalid {to}"); // Validate there are tokens to withdraw uint256 balance = IERC20(tokenAddress).balanceOf(address(this)); require(balance != 0, "No tokens"); // Validate the transfer of tokens completed successfully if(IERC20(tokenAddress).transfer(_toAddress, balance)) { emit TokensWithdrawn(_toAddress, balance); } } /** * @dev Override loyalty account tier by contract owner * @param _loyaltyAccount loyalty account address to tier override * @param _tierSelected reward tier to override current tier value * @return (bool) indicating success status */ function overrideRewardTier(address _loyaltyAccount, uint256 _tierSelected) public whenNotPaused onlyOwner nonReentrant returns(bool) { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); require(_loyaltyAccount != address(0x0), 'Invalid {account}'); // Validate specified address has a timestamp require(accounts[_loyaltyAccount]._address == address(_loyaltyAccount), 'No timestamp4'); // Update the specified loyalty address tier reward index accounts[_loyaltyAccount]._tier = _tierSelected; emit RewardTierChanged(_loyaltyAccount, _tierSelected); } /** * @dev Reset the specified loyalty account timestamp * @param _rewardAddress of the loyalty account to perfornm a reset */ function _resetTimestamp(address _rewardAddress) internal { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}'); // Validate specified address require(_rewardAddress != address(0), "Invalid {reward}"); // Reset callers timestamp for specified address require(ISparkleTimestamp(timestampAddress).resetTimestamp(_rewardAddress), 'Reset failed'); emit ResetTimestampEvent(_rewardAddress); } /** * @dev Delete the specified loyalty account timestamp * @param _rewardAddress of the loyalty account to perfornm the delete */ function _deleteTimestamp(address _rewardAddress) internal { // Validate calling address (msg.sender) require(msg.sender != address(0x0), 'Invalid {from}16'); // Validate specified address require(_rewardAddress != address(0), "Invalid {reward}"); // Delete callers timestamp for specified address require(ISparkleTimestamp(timestampAddress).deleteTimestamp(_rewardAddress), 'Delete failed'); emit DeleteTimestampEvent(_rewardAddress); } /** * @dev Event signal: Treasury address updated */ event TreasuryAddressChanged(address); /** * @dev Event signal: Timestamp address updated */ event TimestampAddressChanged(address); /** * @dev Event signal: Token address updated */ event TokenAddressChangedEvent(address); /** * @dev Event signal: Timestamp reset */ event ResetTimestampEvent(address _rewardAddress); /** * @dev Event signal: Timestamp deleted */ event DeleteTimestampEvent(address _rewardAddress); /** * @dev Event signal: Loyalty deposited event */ event DepositLoyaltyEvent(address, uint256, bool); /** * @dev Event signal: Reward claimed successfully for address */ event RewardClaimedEvent(address, uint256); /** * @dev Event signal: Loyalty withdrawn */ event LoyaltyWithdrawnEvent(address, uint256); /** * @dev Event signal: Account locked/unlocked */ event LockedAccountEvent(address _rewardAddress, bool _locked); /** * @dev Event signal: Loyalty deposit balance withdrawn */ event LoyaltyDepositWithdrawnEvent(address, uint256); /** * @dev Event signal: Loyalty collected balance withdrawn */ event LoyaltyCollectedWithdrawnEvent(address, uint256); /** * @dev Event signal: Loyalty account removed */ event LoyaltyAccountRemovedEvent(address); /** * @dev Event signal: Gas sent with call.value amount updated */ event GasSentChanged(uint256); /** * @dev Event signal: Reward tiers address updated */ event TierSelectedEvent(address, uint256); /** * @dev Event signal: Reward tiers address updated */ event TiersAddressChanged(address); /** * @dev Event signal: Reward tier has been updated */ event RewardTierChanged(address, uint256); /** * @dev Event signal: Collection address updated */ event CollectionAddressChanged(address); /** * @dev Event signal: All stored tokens have been removed */ event TokensWithdrawn(address, uint256); /** * @dev Event signal: Apr base rate has been changed */ event BaseRateChanged(uint256); }
Validate calling address (msg.sender) validate that caller has a loyalty timestamp Validate that reward address is locked Decement the total number of active accounts Delete the callers timestamp record
function removeLoyaltyAccount(address _rewardAddress) public whenNotPaused onlyOwner nonReentrant { require(ISparkleTimestamp(timestampAddress).hasTimestamp(_rewardAddress), 'No timestamp2b'); require(accounts[_rewardAddress]._isLocked, 'Lock account first'); uint256 joinCount = accounts[_rewardAddress]._joined; Account storage account = accounts[_rewardAddress]; account._address = address(0x0); account._balance = 0x0; account._collected = 0x0; account._joined = joinCount; account._claimed = 0x0; account._tier = 0x0; account._isLocked = false; totalActiveAccounts = totalActiveAccounts.sub(1); _deleteTimestamp(_rewardAddress); emit LoyaltyAccountRemovedEvent(_rewardAddress); }
6,070,128
[ 1, 4270, 4440, 1758, 261, 3576, 18, 15330, 13, 1954, 716, 4894, 711, 279, 437, 93, 15006, 2858, 3554, 716, 19890, 1758, 353, 8586, 1505, 311, 475, 326, 2078, 1300, 434, 2695, 9484, 2504, 326, 19932, 2858, 1409, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 1206, 1504, 93, 15006, 3032, 12, 2867, 389, 266, 2913, 1887, 13, 203, 225, 1071, 203, 225, 1347, 1248, 28590, 203, 225, 1338, 5541, 203, 225, 1661, 426, 8230, 970, 203, 225, 288, 203, 565, 2583, 12, 5127, 9468, 298, 4921, 12, 5508, 1887, 2934, 5332, 4921, 24899, 266, 2913, 1887, 3631, 296, 2279, 2858, 22, 70, 8284, 203, 565, 2583, 12, 13739, 63, 67, 266, 2913, 1887, 65, 6315, 291, 8966, 16, 296, 2531, 2236, 1122, 8284, 203, 565, 2254, 5034, 1233, 1380, 273, 9484, 63, 67, 266, 2913, 1887, 65, 6315, 5701, 329, 31, 203, 565, 6590, 2502, 2236, 273, 9484, 63, 67, 266, 2913, 1887, 15533, 203, 565, 2236, 6315, 2867, 273, 1758, 12, 20, 92, 20, 1769, 203, 565, 2236, 6315, 12296, 273, 374, 92, 20, 31, 203, 565, 2236, 6315, 14676, 329, 273, 374, 92, 20, 31, 203, 565, 2236, 6315, 5701, 329, 273, 1233, 1380, 31, 203, 565, 2236, 6315, 14784, 329, 273, 374, 92, 20, 31, 203, 565, 2236, 6315, 88, 2453, 273, 374, 92, 20, 31, 203, 565, 2236, 6315, 291, 8966, 273, 629, 31, 203, 565, 2078, 3896, 13971, 273, 2078, 3896, 13971, 18, 1717, 12, 21, 1769, 203, 203, 565, 389, 3733, 4921, 24899, 266, 2913, 1887, 1769, 203, 203, 565, 3626, 3176, 93, 15006, 3032, 10026, 1133, 24899, 266, 2913, 1887, 1769, 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 ]
./partial_match/1/0x9B85A79028d2aa510A01e7125Cdabc5688400a21/sources/contracts/UniversePairVault.sol
collect feeswap add liquidity
if (position.status) { ( , , uint256 fee0, uint256 fee1) = position._burn(0); _collectPerformanceFee(fee0, fee1); _swapAndAddAll(position); }
2,691,889
[ 1, 14676, 1656, 281, 91, 438, 527, 4501, 372, 24237, 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, 309, 261, 3276, 18, 2327, 13, 288, 203, 5411, 261, 269, 269, 2254, 5034, 14036, 20, 16, 2254, 5034, 14036, 21, 13, 273, 1754, 6315, 70, 321, 12, 20, 1769, 203, 5411, 389, 14676, 25024, 14667, 12, 21386, 20, 16, 14036, 21, 1769, 203, 5411, 389, 22270, 1876, 986, 1595, 12, 3276, 1769, 203, 3639, 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 ]
//Address: 0x686e5ac50d9236a9b7406791256e47feddb26aba //Contract name: AutonomousConverter //Balance: 59.501602221273012488 Ether //Verification Date: 5/24/2018 //Transacion Count: 1630 // CODE STARTS HERE /* The MIT License (MIT) Copyright 2017 - 2018, Alchemy Limited, LLC and Smart Contract Solutions. 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. */ pragma solidity ^0.4.21; /** * Reference: https://github.com/OpenZeppelin/zeppelin-solidity/blob/master/contracts/math/SafeMath.sol * * @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; } } /* end SafeMath library */ /// @title Math operation when both numbers has decimal places. /// @notice Use this contract when both numbers has 18 decimal places. contract FixedMath { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint constant internal DECIMALS = 18; uint constant internal DECMULT = 10 ** DECIMALS; /// @notice Multiplication. function fMul(uint x, uint y) internal pure returns (uint) { return (x.mul(y)).div(DECMULT); } /// @notice Division. function fDiv(uint numerator, uint divisor) internal pure returns (uint) { return (numerator.mul(DECMULT)).div(divisor); } /// @notice Square root. /// @dev Reference: https://stackoverflow.com/questions/3766020/binary-search-to-compute-square-root-java function fSqrt(uint n) internal pure returns (uint) { if (n == 0) { return 0; } uint z = n * n; require(z / n == n); uint high = fAdd(n, DECMULT); uint low = 0; while (fSub(high, low) > 1) { uint mid = fAdd(low, high) / 2; if (fSqr(mid) <= n) { low = mid; } else { high = mid; } } return low; } /// @notice Square. function fSqr(uint n) internal pure returns (uint) { return fMul(n, n); } /// @notice Add. function fAdd(uint x, uint y) internal pure returns (uint) { return x.add(y); } /// @notice Sub. function fSub(uint x, uint y) internal pure returns (uint) { return x.sub(y); } } /// @title A formula contract for converter contract Formula is FixedMath { /// @notice Trade in reserve(ETH/MET) and mint new smart tokens /// @param smartTokenSupply Total supply of smart token /// @param reserveTokensSent Amount of token sent by caller /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Smart token minted function returnForMint(uint smartTokenSupply, uint reserveTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint e = reserveTokensSent; uint r = reserveTokenBalance; /// smartToken for mint(T) = S * (sqrt(1 + E/R) - 1) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(s, (fSub(fSqrt(fAdd(DECMULT, fDiv(e, r))), DECMULT)))).mul(METDECMULT)).div(DECMULT); } /// @notice Redeem smart tokens, get back reserve(ETH/MET) token /// @param smartTokenSupply Total supply of smart token /// @param smartTokensSent Smart token sent /// @param reserveTokenBalance Balance of reserve token in the contract /// @return Reserve token redeemed function returnForRedemption(uint smartTokenSupply, uint smartTokensSent, uint reserveTokenBalance) internal pure returns (uint) { uint s = smartTokenSupply; uint t = smartTokensSent; uint r = reserveTokenBalance; /// reserveToken (E) = R * (1 - (1 - T/S)**2) /// DECMULT is same as 1 for values with 18 decimal places return ((fMul(r, (fSub(DECMULT, fSqr(fSub(DECMULT, fDiv(t, s))))))).mul(METDECMULT)).div(DECMULT); } } /// @title Pricer contract to calculate descending price during auction. contract Pricer { using SafeMath for uint; uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; uint public minimumPrice = 33*10**11; uint public minimumPriceInDailyAuction = 1; uint public tentimes; uint public hundredtimes; uint public thousandtimes; uint constant public MULTIPLIER = 1984320568*10**5; /// @notice Pricer constructor, calculate 10, 100 and 1000 times of 0.99. function initPricer() public { uint x = METDECMULT; uint i; /// Calculate 10 times of 0.99 for (i = 0; i < 10; i++) { x = x.mul(99).div(100); } tentimes = x; x = METDECMULT; /// Calculate 100 times of 0.99 using tentimes calculated above. /// tentimes has 18 decimal places and due to this METDECMLT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(tentimes).div(METDECMULT); } hundredtimes = x; x = METDECMULT; /// Calculate 1000 times of 0.99 using hundredtimes calculated above. /// hundredtimes has 18 decimal places and due to this METDECMULT is /// used as divisor. for (i = 0; i < 10; i++) { x = x.mul(hundredtimes).div(METDECMULT); } thousandtimes = x; } /// @notice Price of MET at nth minute out during operational auction /// @param initialPrice The starting price ie last purchase price /// @param _n The number of minutes passed since last purchase /// @return The resulting price function priceAt(uint initialPrice, uint _n) public view returns (uint price) { uint mult = METDECMULT; uint i; uint n = _n; /// If quotient of n/1000 is greater than 0 then calculate multiplier by /// multiplying thousandtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/1000. if (n / 1000 > 0) { for (i = 0; i < n / 1000; i++) { mult = mult.mul(thousandtimes).div(METDECMULT); } n = n % 1000; } /// If quotient of n/100 is greater than 0 then calculate multiplier by /// multiplying hundredtimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/100. if (n / 100 > 0) { for (i = 0; i < n / 100; i++) { mult = mult.mul(hundredtimes).div(METDECMULT); } n = n % 100; } /// If quotient of n/10 is greater than 0 then calculate multiplier by /// multiplying tentimes and mult in a loop which runs quotient times. /// Also assign new value to n which is remainder of n/10. if (n / 10 > 0) { for (i = 0; i < n / 10; i++) { mult = mult.mul(tentimes).div(METDECMULT); } n = n % 10; } /// Calculate multiplier by multiplying 0.99 and mult, repeat it n times. for (i = 0; i < n; i++) { mult = mult.mul(99).div(100); } /// price is calculated as initialPrice multiplied by 0.99 and that too _n times. /// Here mult is METDECMULT multiplied by 0.99 and that too _n times. price = initialPrice.mul(mult).div(METDECMULT); if (price < minimumPriceInDailyAuction) { price = minimumPriceInDailyAuction; } } /// @notice Price of MET at nth minute during initial auction. /// @param lastPurchasePrice The price of MET in last transaction /// @param numTicks The number of minutes passed since last purchase /// @return The resulting price function priceAtInitialAuction(uint lastPurchasePrice, uint numTicks) public view returns (uint price) { /// Price will decrease linearly every minute by the factor of MULTIPLIER. /// If lastPurchasePrice is greater than decrease in price then calculated the price. /// Return minimumPrice, if calculated price is less than minimumPrice. /// If decrease in price is more than lastPurchasePrice then simply return the minimumPrice. if (lastPurchasePrice > MULTIPLIER.mul(numTicks)) { price = lastPurchasePrice.sub(MULTIPLIER.mul(numTicks)); } if (price < minimumPrice) { price = minimumPrice; } } } /// @dev Reference: https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md /// @notice ERC20 standard interface interface ERC20 { function totalSupply() public constant returns (uint256); function balanceOf(address _owner) public constant returns (uint256); function allowance(address _owner, address _spender) public constant returns (uint256); event Transfer(address indexed _from, address indexed _to, uint256 _value); function transfer(address _to, uint256 _value) public returns (bool); function transferFrom(address _from, address _to, uint256 _value) public returns (bool); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function approve(address _spender, uint256 _value) public returns (bool); } /// @title Ownable contract Ownable { address public owner; event OwnershipChanged(address indexed prevOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner); _; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != address(0)); require(_newOwner != owner); emit OwnershipChanged(owner, _newOwner); owner = _newOwner; return true; } } /// @title Owned contract Owned is Ownable { address public newOwner; /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @param _newOwner /// @return true/false function changeOwnership(address _newOwner) public onlyOwner returns (bool) { require(_newOwner != owner); newOwner = _newOwner; return true; } /// @notice Allows the new owner to accept ownership of the contract. /// @return true/false function acceptOwnership() public returns (bool) { require(msg.sender == newOwner); emit OwnershipChanged(owner, newOwner); owner = newOwner; return true; } } /// @title Mintable contract to allow minting and destroy. contract Mintable is Owned { using SafeMath for uint256; event Mint(address indexed _to, uint _value); event Destroy(address indexed _from, uint _value); event Transfer(address indexed _from, address indexed _to, uint256 _value); uint256 internal _totalSupply; mapping(address => uint256) internal _balanceOf; address public autonomousConverter; address public minter; ITokenPorter public tokenPorter; /// @notice init reference of other contract and initial supply /// @param _autonomousConverter /// @param _minter /// @param _initialSupply /// @param _decmult Decimal places function initMintable(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { require(autonomousConverter == 0x0 && _autonomousConverter != 0x0); require(minter == 0x0 && _minter != 0x0); autonomousConverter = _autonomousConverter; minter = _minter; _totalSupply = _initialSupply.mul(_decmult); _balanceOf[_autonomousConverter] = _totalSupply; } function totalSupply() public constant returns (uint256) { return _totalSupply; } function balanceOf(address _owner) public constant returns (uint256) { return _balanceOf[_owner]; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = ITokenPorter(_tokenPorter); return true; } /// @notice allow minter and tokenPorter to mint token and assign to address /// @param _to /// @param _value Amount to be minted function mint(address _to, uint _value) public returns (bool) { require(msg.sender == minter || msg.sender == address(tokenPorter)); _balanceOf[_to] = _balanceOf[_to].add(_value); _totalSupply = _totalSupply.add(_value); emit Mint(_to, _value); emit Transfer(0x0, _to, _value); return true; } /// @notice allow autonomousConverter and tokenPorter to mint token and assign to address /// @param _from /// @param _value Amount to be destroyed function destroy(address _from, uint _value) public returns (bool) { require(msg.sender == autonomousConverter || msg.sender == address(tokenPorter)); _balanceOf[_from] = _balanceOf[_from].sub(_value); _totalSupply = _totalSupply.sub(_value); emit Destroy(_from, _value); emit Transfer(_from, 0x0, _value); return true; } } /// @title Token contract contract Token is ERC20, Mintable { mapping(address => mapping(address => uint256)) internal _allowance; function initToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Provide allowance information function allowance(address _owner, address _spender) public constant returns (uint256) { return _allowance[_owner][_spender]; } /// @notice Transfer tokens from sender to the provided address. /// @param _to Receiver of the tokens /// @param _value Amount of token /// @return true/false function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter); require(_to != address(this)); require(_to != autonomousConverter); Proceeds proceeds = Auctions(minter).proceeds(); require((_to != address(proceeds))); _balanceOf[msg.sender] = _balanceOf[msg.sender].sub(_value); _balanceOf[_to] = _balanceOf[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /// @notice Transfer tokens based on allowance. /// msg.sender must have allowance for spending the tokens from owner ie _from /// @param _from Owner of the tokens /// @param _to Receiver of the tokens /// @param _value Amount of tokens to transfer /// @return true/false function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_to != minter && _from != minter); require(_to != address(this) && _from != address(this)); Proceeds proceeds = Auctions(minter).proceeds(); require(_to != address(proceeds) && _from != address(proceeds)); //AC can accept MET via this function, needed for MetToEth conversion require(_from != autonomousConverter); require(_allowance[_from][msg.sender] >= _value); _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; } /// @notice Approve spender to spend the tokens ie approve allowance /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approve(address _spender, uint256 _value) public returns (bool) { require(_spender != address(this)); _allowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /// @notice Transfer the tokens from sender to all the address provided in the array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public returns (bool) { for (uint i = 0; i < bits.length; i++) { address a = address(bits[i] >> 96); uint amount = bits[i] & ((1 << 96) - 1); if (!transfer(a, amount)) revert(); } return true; } /// @notice Increase allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveMore(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.add(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } /// @notice Decrease allowance of spender /// @param _spender Spender of the tokens /// @param _value Amount of tokens that can be spent by spender /// @return true/false function approveLess(address _spender, uint256 _value) public returns (bool) { uint previous = _allowance[msg.sender][_spender]; uint newAllowance = previous.sub(_value); _allowance[msg.sender][_spender] = newAllowance; emit Approval(msg.sender, _spender, newAllowance); return true; } } /// @title Smart tokens are an intermediate token generated during conversion of MET-ETH contract SmartToken is Mintable { uint constant internal METDECIMALS = 18; uint constant internal METDECMULT = 10 ** METDECIMALS; function initSmartToken(address _autonomousConverter, address _minter, uint _initialSupply) public onlyOwner { initMintable(_autonomousConverter, _minter, _initialSupply, METDECMULT); } } /// @title ERC20 token. Metronome token contract METToken is Token { string public constant name = "Metronome"; string public constant symbol = "MET"; uint8 public constant decimals = 18; bool public transferAllowed; function initMETToken(address _autonomousConverter, address _minter, uint _initialSupply, uint _decmult) public onlyOwner { initToken(_autonomousConverter, _minter, _initialSupply, _decmult); } /// @notice Transferable modifier to allow transfer only after initial auction ended. modifier transferable() { require(transferAllowed); _; } function enableMETTransfers() public returns (bool) { require(!transferAllowed && Auctions(minter).isInitialAuctionEnded()); transferAllowed = true; return true; } /// @notice Transfer tokens from caller to another address /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transfer(address _to, uint256 _value) public transferable returns (bool) { return super.transfer(_to, _value); } /// @notice Transfer tokens from one address to another /// @param _from address The address from which you want to transfer /// @param _to address The address which you want to transfer to /// @param _value uint256 the amout of tokens to be transfered function transferFrom(address _from, address _to, uint256 _value) public transferable returns (bool) { return super.transferFrom(_from, _to, _value); } /// @notice Transfer the token from sender to all the addresses provided in array. /// @dev Left 160 bits are the recipient address and the right 96 bits are the token amount. /// @param bits array of uint /// @return true/false function multiTransfer(uint[] bits) public transferable returns (bool) { return super.multiTransfer(bits); } mapping (address => bytes32) public roots; function setRoot(bytes32 data) public { roots[msg.sender] = data; } function getRoot(address addr) public view returns (bytes32) { return roots[addr]; } function rootsMatch(address a, address b) public view returns (bool) { return roots[a] == roots[b]; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.importMET(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof); } /// @notice export MET tokens from this chain to another chain. /// @param _destChain destination chain address /// @param _destMetronomeAddr address of Metronome contract on the destination chain /// where this MET will be imported. /// @param _destRecipAddr address of account on destination chain /// @param _amount amount /// @param _extraData extra information for future expansion /// @return true/false function export(bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(address(tokenPorter) != 0x0); return tokenPorter.export(msg.sender, _destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData); } struct Sub { uint startTime; uint payPerWeek; uint lastWithdrawTime; } event LogSubscription(address indexed subscriber, address indexed subscribesTo); event LogCancelSubscription(address indexed subscriber, address indexed subscribesTo); mapping (address => mapping (address => Sub)) public subs; /// @notice subscribe for a weekly recurring payment /// @param _startTime Subscription start time. /// @param _payPerWeek weekly payment /// @param _recipient address of beneficiary /// @return true/false function subscribe(uint _startTime, uint _payPerWeek, address _recipient) public returns (bool) { require(_startTime >= block.timestamp); require(_payPerWeek != 0); require(_recipient != 0); subs[msg.sender][_recipient] = Sub(_startTime, _payPerWeek, _startTime); emit LogSubscription(msg.sender, _recipient); return true; } /// @notice cancel a subcription. /// @param _recipient address of beneficiary /// @return true/false function cancelSubscription(address _recipient) public returns (bool) { require(subs[msg.sender][_recipient].startTime != 0); require(subs[msg.sender][_recipient].payPerWeek != 0); subs[msg.sender][_recipient].startTime = 0; subs[msg.sender][_recipient].payPerWeek = 0; subs[msg.sender][_recipient].lastWithdrawTime = 0; emit LogCancelSubscription(msg.sender, _recipient); return true; } /// @notice get subcription details /// @param _owner /// @param _recipient /// @return startTime, payPerWeek, lastWithdrawTime function getSubscription(address _owner, address _recipient) public constant returns (uint startTime, uint payPerWeek, uint lastWithdrawTime) { Sub storage sub = subs[_owner][_recipient]; return ( sub.startTime, sub.payPerWeek, sub.lastWithdrawTime ); } /// @notice caller can withdraw the token from subscribers. /// @param _owner subcriber /// @return true/false function subWithdraw(address _owner) public transferable returns (bool) { require(subWithdrawFor(_owner, msg.sender)); return true; } /// @notice Allow callers to withdraw token in one go from all of its subscribers /// @param _owners array of address of subscribers /// @return number of successful transfer done function multiSubWithdraw(address[] _owners) public returns (uint) { uint n = 0; for (uint i=0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], msg.sender)) { n++; } } return n; } /// @notice Trigger MET token transfers for all pairs of subscribers and beneficiaries /// @dev address at i index in owners and recipients array is subcriber-beneficiary pair. /// @param _owners /// @param _recipients /// @return number of successful transfer done function multiSubWithdrawFor(address[] _owners, address[] _recipients) public returns (uint) { // owners and recipients need 1-to-1 mapping, must be same length require(_owners.length == _recipients.length); uint n = 0; for (uint i = 0; i < _owners.length; i++) { if (subWithdrawFor(_owners[i], _recipients[i])) { n++; } } return n; } function subWithdrawFor(address _from, address _to) internal returns (bool) { Sub storage sub = subs[_from][_to]; if (sub.startTime > 0 && sub.startTime < block.timestamp && sub.payPerWeek > 0) { uint weekElapsed = (now.sub(sub.lastWithdrawTime)).div(7 days); uint amount = weekElapsed.mul(sub.payPerWeek); if (weekElapsed > 0 && _balanceOf[_from] >= amount) { subs[_from][_to].lastWithdrawTime = block.timestamp; _balanceOf[_from] = _balanceOf[_from].sub(amount); _balanceOf[_to] = _balanceOf[_to].add(amount); emit Transfer(_from, _to, amount); return true; } } return false; } } /// @title Autonomous Converter contract for MET <=> ETH exchange contract AutonomousConverter is Formula, Owned { SmartToken public smartToken; METToken public reserveToken; Auctions public auctions; enum WhichToken { Eth, Met } bool internal initialized = false; event LogFundsIn(address indexed from, uint value); event ConvertEthToMet(address indexed from, uint eth, uint met); event ConvertMetToEth(address indexed from, uint eth, uint met); function init(address _reserveToken, address _smartToken, address _auctions) public onlyOwner payable { require(!initialized); auctions = Auctions(_auctions); reserveToken = METToken(_reserveToken); smartToken = SmartToken(_smartToken); initialized = true; } function handleFund() public payable { require(msg.sender == address(auctions.proceeds())); emit LogFundsIn(msg.sender, msg.value); } function getMetBalance() public view returns (uint) { return balanceOf(WhichToken.Met); } function getEthBalance() public view returns (uint) { return balanceOf(WhichToken.Eth); } /// @notice return the expected MET for ETH /// @param _depositAmount ETH. /// @return expected MET value for ETH function getMetForEthResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Eth, _depositAmount); } /// @notice return the expected ETH for MET /// @param _depositAmount MET. /// @return expected ETH value for MET function getEthForMetResult(uint _depositAmount) public view returns (uint256) { return convertingReturn(WhichToken.Met, _depositAmount); } /// @notice send ETH and get MET /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedMet MET retured after conversion function convertEthToMet(uint _mintReturn) public payable returns (uint returnedMet) { returnedMet = convert(WhichToken.Eth, _mintReturn, msg.value); emit ConvertEthToMet(msg.sender, msg.value, returnedMet); } /// @notice send MET and get ETH /// @dev Caller will be required to approve the AutonomousConverter to initiate the transfer /// @param _amount MET amount /// @param _mintReturn execute conversion only if return is equal or more than _mintReturn /// @return returnedEth ETh returned after conversion function convertMetToEth(uint _amount, uint _mintReturn) public returns (uint returnedEth) { returnedEth = convert(WhichToken.Met, _mintReturn, _amount); emit ConvertMetToEth(msg.sender, returnedEth, _amount); } function balanceOf(WhichToken which) internal view returns (uint) { if (which == WhichToken.Eth) return address(this).balance; if (which == WhichToken.Met) return reserveToken.balanceOf(this); revert(); } function convertingReturn(WhichToken whichFrom, uint _depositAmount) internal view returns (uint256) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; } uint reserveTokenBalanceFrom = balanceOf(whichFrom).add(_depositAmount); uint mintRet = returnForMint(smartToken.totalSupply(), _depositAmount, reserveTokenBalanceFrom); uint newSmartTokenSupply = smartToken.totalSupply().add(mintRet); uint reserveTokenBalanceTo = balanceOf(to); return returnForRedemption( newSmartTokenSupply, mintRet, reserveTokenBalanceTo); } function convert(WhichToken whichFrom, uint _minReturn, uint amnt) internal returns (uint) { WhichToken to = WhichToken.Met; if (whichFrom == WhichToken.Met) { to = WhichToken.Eth; require(reserveToken.transferFrom(msg.sender, this, amnt)); } uint mintRet = mint(whichFrom, amnt, 1); return redeem(to, mintRet, _minReturn); } function mint(WhichToken which, uint _depositAmount, uint _minReturn) internal returns (uint256 amount) { require(_minReturn > 0); amount = mintingReturn(which, _depositAmount); require(amount >= _minReturn); require(smartToken.mint(msg.sender, amount)); } function mintingReturn(WhichToken which, uint _depositAmount) internal view returns (uint256) { uint256 smartTokenSupply = smartToken.totalSupply(); uint256 reserveBalance = balanceOf(which); return returnForMint(smartTokenSupply, _depositAmount, reserveBalance); } function redeem(WhichToken which, uint _amount, uint _minReturn) internal returns (uint redeemable) { require(_amount <= smartToken.balanceOf(msg.sender)); require(_minReturn > 0); redeemable = redemptionReturn(which, _amount); require(redeemable >= _minReturn); uint256 reserveBalance = balanceOf(which); require(reserveBalance >= redeemable); uint256 tokenSupply = smartToken.totalSupply(); require(_amount < tokenSupply); smartToken.destroy(msg.sender, _amount); if (which == WhichToken.Eth) { msg.sender.transfer(redeemable); } else { require(reserveToken.transfer(msg.sender, redeemable)); } } function redemptionReturn(WhichToken which, uint smartTokensSent) internal view returns (uint256) { uint smartTokenSupply = smartToken.totalSupply(); uint reserveTokenBalance = balanceOf(which); return returnForRedemption( smartTokenSupply, smartTokensSent, reserveTokenBalance); } } /// @title Proceeds contract contract Proceeds is Owned { using SafeMath for uint256; AutonomousConverter public autonomousConverter; Auctions public auctions; event LogProceedsIn(address indexed from, uint value); event LogClosedAuction(address indexed from, uint value); uint latestAuctionClosed; function initProceeds(address _autonomousConverter, address _auctions) public onlyOwner { require(address(auctions) == 0x0 && _auctions != 0x0); require(address(autonomousConverter) == 0x0 && _autonomousConverter != 0x0); autonomousConverter = AutonomousConverter(_autonomousConverter); auctions = Auctions(_auctions); } function handleFund() public payable { require(msg.sender == address(auctions)); emit LogProceedsIn(msg.sender, msg.value); } /// @notice Forward 0.25% of total ETH balance of proceeds to AutonomousConverter contract function closeAuction() public { uint lastPurchaseTick = auctions.lastPurchaseTick(); uint currentAuction = auctions.currentAuction(); uint val = ((address(this).balance).mul(25)).div(10000); if (val > 0 && (currentAuction > auctions.whichAuction(lastPurchaseTick)) && (latestAuctionClosed < currentAuction)) { latestAuctionClosed = currentAuction; autonomousConverter.handleFund.value(val)(); emit LogClosedAuction(msg.sender, val); } } } /// @title Auction contract. Send ETH to the contract address and buy MET. contract Auctions is Pricer, Owned { using SafeMath for uint256; METToken public token; Proceeds public proceeds; address[] public founders; mapping(address => TokenLocker) public tokenLockers; uint internal constant DAY_IN_SECONDS = 86400; uint internal constant DAY_IN_MINUTES = 1440; uint public genesisTime; uint public lastPurchaseTick; uint public lastPurchasePrice; uint public constant INITIAL_GLOBAL_DAILY_SUPPLY = 2880 * METDECMULT; uint public INITIAL_FOUNDER_SUPPLY = 1999999 * METDECMULT; uint public INITIAL_AC_SUPPLY = 1 * METDECMULT; uint public totalMigratedOut = 0; uint public totalMigratedIn = 0; uint public timeScale = 1; uint public constant INITIAL_SUPPLY = 10000000 * METDECMULT; uint public mintable = INITIAL_SUPPLY; uint public initialAuctionDuration = 7 days; uint public initialAuctionEndTime; uint public dailyAuctionStartTime; uint public constant DAILY_PURCHASE_LIMIT = 1000 ether; mapping (address => uint) internal purchaseInTheAuction; mapping (address => uint) internal lastPurchaseAuction; bool public minted; bool public initialized; uint public globalSupplyAfterPercentageLogic = 52598080 * METDECMULT; uint public constant AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS = 14791; bytes8 public chain = "ETH"; event LogAuctionFundsIn(address indexed sender, uint amount, uint tokens, uint purchasePrice, uint refund); function Auctions() public { mintable = INITIAL_SUPPLY - 2000000 * METDECMULT; } /// @notice Payable function to buy MET in descending price auction function () public payable running { require(msg.value > 0); uint amountForPurchase = msg.value; uint excessAmount; if (currentAuction() > whichAuction(lastPurchaseTick)) { proceeds.closeAuction(); restartAuction(); } if (isInitialAuctionEnded()) { require(now >= dailyAuctionStartTime); if (lastPurchaseAuction[msg.sender] < currentAuction()) { if (amountForPurchase > DAILY_PURCHASE_LIMIT) { excessAmount = amountForPurchase.sub(DAILY_PURCHASE_LIMIT); amountForPurchase = DAILY_PURCHASE_LIMIT; } purchaseInTheAuction[msg.sender] = msg.value; lastPurchaseAuction[msg.sender] = currentAuction(); } else { require(purchaseInTheAuction[msg.sender] < DAILY_PURCHASE_LIMIT); if (purchaseInTheAuction[msg.sender].add(amountForPurchase) > DAILY_PURCHASE_LIMIT) { excessAmount = (purchaseInTheAuction[msg.sender].add(amountForPurchase)).sub(DAILY_PURCHASE_LIMIT); amountForPurchase = amountForPurchase.sub(excessAmount); } purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].add(msg.value); } } uint _currentTick = currentTick(); uint weiPerToken; uint tokens; uint refund; (weiPerToken, tokens, refund) = calcPurchase(amountForPurchase, _currentTick); require(tokens > 0); if (now < initialAuctionEndTime && (token.totalSupply()).add(tokens) >= INITIAL_SUPPLY) { initialAuctionEndTime = now; dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = _currentTick; lastPurchasePrice = weiPerToken; assert(tokens <= mintable); mintable = mintable.sub(tokens); assert(refund <= amountForPurchase); uint ethForProceeds = amountForPurchase.sub(refund); proceeds.handleFund.value(ethForProceeds)(); require(token.mint(msg.sender, tokens)); refund = refund.add(excessAmount); if (refund > 0) { if (purchaseInTheAuction[msg.sender] > 0) { purchaseInTheAuction[msg.sender] = purchaseInTheAuction[msg.sender].sub(refund); } msg.sender.transfer(refund); } emit LogAuctionFundsIn(msg.sender, ethForProceeds, tokens, lastPurchasePrice, refund); } modifier running() { require(isRunning()); _; } function isRunning() public constant returns (bool) { return (block.timestamp >= genesisTime && genesisTime > 0); } /// @notice current tick(minute) of the metronome clock /// @return tick count function currentTick() public view returns(uint) { return whichTick(block.timestamp); } /// @notice current auction /// @return auction count function currentAuction() public view returns(uint) { return whichAuction(currentTick()); } /// @notice tick count at the timestamp t. /// @param t timestamp /// @return tick count function whichTick(uint t) public view returns(uint) { if (genesisTime > t) { revert(); } return (t - genesisTime) * timeScale / 1 minutes; } /// @notice Auction count at given the timestamp t /// @param t timestamp /// @return Auction count function whichAuction(uint t) public view returns(uint) { if (whichTick(dailyAuctionStartTime) > t) { return 0; } else { return ((t - whichTick(dailyAuctionStartTime)) / DAY_IN_MINUTES) + 1; } } /// @notice one single function telling everything about Metronome Auction function heartbeat() public view returns ( bytes8 _chain, address auctionAddr, address convertAddr, address tokenAddr, uint minting, uint totalMET, uint proceedsBal, uint currTick, uint currAuction, uint nextAuctionGMT, uint genesisGMT, uint currentAuctionPrice, uint _dailyMintable, uint _lastPurchasePrice) { _chain = chain; convertAddr = proceeds.autonomousConverter(); tokenAddr = token; auctionAddr = this; totalMET = token.totalSupply(); proceedsBal = address(proceeds).balance; currTick = currentTick(); currAuction = currentAuction(); if (currAuction == 0) { nextAuctionGMT = dailyAuctionStartTime; } else { nextAuctionGMT = (currAuction * DAY_IN_SECONDS) / timeScale + dailyAuctionStartTime; } genesisGMT = genesisTime; currentAuctionPrice = currentPrice(); _dailyMintable = dailyMintable(); minting = currentMintable(); _lastPurchasePrice = lastPurchasePrice; } /// @notice Skip Initialization and minting if we're not the OG Metronome /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract /// @param _genesisTime The block.timestamp when first auction started on OG chain /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment /// @param _chain chain where this contract is being deployed /// @param _initialAuctionEndTime Initial Auction end time in ETH chain. function skipInitBecauseIAmNotOg(address _token, address _proceeds, uint _genesisTime, uint _minimumPrice, uint _startingPrice, uint _timeScale, bytes8 _chain, uint _initialAuctionEndTime) public onlyOwner returns (bool) { require(!minted); require(!initialized); require(_timeScale != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); initPricer(); // minting substitute section token = METToken(_token); proceeds = Proceeds(_proceeds); INITIAL_FOUNDER_SUPPLY = 0; INITIAL_AC_SUPPLY = 0; mintable = 0; // // initial auction substitute section genesisTime = _genesisTime; initialAuctionEndTime = _initialAuctionEndTime; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } chain = _chain; minted = true; initialized = true; return true; } /// @notice Initialize Auctions parameters /// @param _startTime The block.timestamp when first auction starts /// @param _minimumPrice Nobody can buy tokens for less than this price /// @param _startingPrice Start price of MET when first auction starts /// @param _timeScale time scale factor for auction. will be always 1 in live environment function initAuctions(uint _startTime, uint _minimumPrice, uint _startingPrice, uint _timeScale) public onlyOwner returns (bool) { require(minted); require(!initialized); require(_timeScale != 0); initPricer(); if (_startTime > 0) { genesisTime = (_startTime / (1 minutes)) * (1 minutes) + 60; } else { genesisTime = block.timestamp + 60 - (block.timestamp % 60); } initialAuctionEndTime = genesisTime + initialAuctionDuration; // if initialAuctionEndTime is midnight, then daily auction will start immediately // after initial auction. if (initialAuctionEndTime == (initialAuctionEndTime / 1 days) * 1 days) { dailyAuctionStartTime = initialAuctionEndTime; } else { dailyAuctionStartTime = ((initialAuctionEndTime / 1 days) + 1) * 1 days; } lastPurchaseTick = 0; if (_minimumPrice > 0) { minimumPrice = _minimumPrice; } timeScale = _timeScale; if (_startingPrice > 0) { lastPurchasePrice = _startingPrice * 1 ether; } else { lastPurchasePrice = 2 ether; } for (uint i = 0; i < founders.length; i++) { TokenLocker tokenLocker = tokenLockers[founders[i]]; tokenLocker.lockTokenLocker(); } initialized = true; return true; } function createTokenLocker(address _founder, address _token) public onlyOwner { require(_token != 0x0); require(_founder != 0x0); founders.push(_founder); TokenLocker tokenLocker = new TokenLocker(address(this), _token); tokenLockers[_founder] = tokenLocker; tokenLocker.changeOwnership(_founder); } /// @notice Mint initial supply for founder and move to token locker /// @param _founders Left 160 bits are the founder address and the right 96 bits are the token amount. /// @param _token MET token contract address /// @param _proceeds Address of Proceeds contract function mintInitialSupply(uint[] _founders, address _token, address _proceeds, address _autonomousConverter) public onlyOwner returns (bool) { require(!minted); require(_founders.length != 0); require(address(token) == 0x0 && _token != 0x0); require(address(proceeds) == 0x0 && _proceeds != 0x0); require(_autonomousConverter != 0x0); token = METToken(_token); proceeds = Proceeds(_proceeds); // _founders will be minted into individual token lockers uint foundersTotal; for (uint i = 0; i < _founders.length; i++) { address addr = address(_founders[i] >> 96); require(addr != 0x0); uint amount = _founders[i] & ((1 << 96) - 1); require(amount > 0); TokenLocker tokenLocker = tokenLockers[addr]; require(token.mint(address(tokenLocker), amount)); tokenLocker.deposit(addr, amount); foundersTotal = foundersTotal.add(amount); } // reconcile minted total for founders require(foundersTotal == INITIAL_FOUNDER_SUPPLY); // mint a small amount to the AC require(token.mint(_autonomousConverter, INITIAL_AC_SUPPLY)); minted = true; return true; } /// @notice Suspend auction if not started yet function stopEverything() public onlyOwner { if (genesisTime < block.timestamp) { revert(); } genesisTime = genesisTime + 1000 years; initialAuctionEndTime = genesisTime; dailyAuctionStartTime = genesisTime; } /// @notice Return information about initial auction status. function isInitialAuctionEnded() public view returns (bool) { return (initialAuctionEndTime != 0 && (now >= initialAuctionEndTime || token.totalSupply() >= INITIAL_SUPPLY)); } /// @notice Global MET supply function globalMetSupply() public view returns (uint) { uint currAuc = currentAuction(); if (currAuc > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { return globalSupplyAfterPercentageLogic; } else { return INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(currAuc)); } } /// @notice Global MET daily supply. Daily supply is greater of 1) 2880 2)2% of then outstanding supply per year. /// @dev 2% logic will kicks in at 14792th auction. function globalDailySupply() public view returns (uint) { uint dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { uint lastAuctionPurchase = whichAuction(lastPurchaseTick); uint recentAuction = AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS + 1; if (lastAuctionPurchase > recentAuction) { recentAuction = lastAuctionPurchase; } uint totalAuctions = thisAuction - recentAuction; if (totalAuctions > 1) { // derived formula to find close to accurate daily supply when some auction missed. uint factor = 36525 + ((totalAuctions - 1) * 2); dailySupply = (globalSupplyAfterPercentageLogic.mul(2).mul(factor)).div(36525 ** 2); } else { dailySupply = globalSupplyAfterPercentageLogic.mul(2).div(36525); } if (dailySupply < INITIAL_GLOBAL_DAILY_SUPPLY) { dailySupply = INITIAL_GLOBAL_DAILY_SUPPLY; } } return dailySupply; } /// @notice Current price of MET in current auction /// @return weiPerToken function currentPrice() public constant returns (uint weiPerToken) { weiPerToken = calcPriceAt(currentTick()); } /// @notice Daily mintable MET in current auction function dailyMintable() public constant returns (uint) { return nextAuctionSupply(0); } /// @notice Total tokens on this chain function tokensOnThisChain() public view returns (uint) { uint totalSupply = token.totalSupply(); uint currMintable = currentMintable(); return totalSupply.add(currMintable); } /// @notice Current mintable MET in auction function currentMintable() public view returns (uint) { uint currMintable = mintable; uint currAuction = currentAuction(); uint totalAuctions = currAuction.sub(whichAuction(lastPurchaseTick)); if (totalAuctions > 0) { currMintable = mintable.add(nextAuctionSupply(totalAuctions)); } return currMintable; } /// @notice prepare auction when first import is done on a non ETH chain function prepareAuctionForNonOGChain() public { require(msg.sender == address(token.tokenPorter()) || msg.sender == address(token)); require(token.totalSupply() == 0); require(chain != "ETH"); lastPurchaseTick = currentTick(); } /// @notice Find out what the results would be of a prospective purchase /// @param _wei Amount of wei the purchaser will pay /// @param _timestamp Prospective purchase timestamp /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function whatWouldPurchaseDo(uint _wei, uint _timestamp) public constant returns (uint weiPerToken, uint tokens, uint refund) { weiPerToken = calcPriceAt(whichTick(_timestamp)); uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint weiPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(weiPaying); } } /// @notice Return the information about the next auction /// @return _startTime Start time of next auction /// @return _startPrice Start price of MET in next auction /// @return _auctionTokens MET supply in next auction function nextAuction() internal constant returns(uint _startTime, uint _startPrice, uint _auctionTokens) { if (block.timestamp < genesisTime) { _startTime = genesisTime; _startPrice = lastPurchasePrice; _auctionTokens = mintable; return; } uint recentAuction = whichAuction(lastPurchaseTick); uint currAuc = currentAuction(); uint totalAuctions = currAuc - recentAuction; _startTime = dailyAuctionStartTime; if (currAuc > 1) { _startTime = auctionStartTime(currentTick()); } _auctionTokens = nextAuctionSupply(totalAuctions); if (totalAuctions > 1) { _startPrice = lastPurchasePrice / 100 + 1; } else { if (mintable == 0 || totalAuctions == 0) { // Sold out scenario or someone querying projected start price of next auction _startPrice = (lastPurchasePrice * 2) + 1; } else { // Timed out and all tokens not sold. if (currAuc == 1) { // If initial auction timed out then price before start of new auction will touch floor price _startPrice = minimumPrice * 2; } else { // Descending price till end of auction and then multiply by 2 uint tickWhenAuctionEnded = whichTick(_startTime); uint numTick = 0; if (tickWhenAuctionEnded > lastPurchaseTick) { numTick = tickWhenAuctionEnded - lastPurchaseTick; } _startPrice = priceAt(lastPurchasePrice, numTick) * 2; } } } } /// @notice Calculate results of a purchase /// @param _wei Amount of wei the purchaser will pay /// @param _t Prospective purchase tick /// @return weiPerToken expected MET token rate /// @return tokens Expected token for a prospective purchase /// @return refund Wei refund the purchaser will get if amount is excess and MET supply is less function calcPurchase(uint _wei, uint _t) internal view returns (uint weiPerToken, uint tokens, uint refund) { require(_t >= lastPurchaseTick); uint numTicks = _t - lastPurchaseTick; if (isInitialAuctionEnded()) { weiPerToken = priceAt(lastPurchasePrice, numTicks); } else { weiPerToken = priceAtInitialAuction(lastPurchasePrice, numTicks); } uint calctokens = METDECMULT.mul(_wei).div(weiPerToken); tokens = calctokens; if (calctokens > mintable) { tokens = mintable; uint ethPaying = mintable.mul(weiPerToken).div(METDECMULT); refund = _wei.sub(ethPaying); } } /// @notice MET supply for next Auction also considering carry forward met. /// @param totalAuctionMissed auction count when no purchase done. function nextAuctionSupply(uint totalAuctionMissed) internal view returns (uint supply) { uint thisAuction = currentAuction(); uint tokensHere = token.totalSupply().add(mintable); supply = INITIAL_GLOBAL_DAILY_SUPPLY; uint dailySupplyAtLastPurchase; if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { supply = globalDailySupply(); if (totalAuctionMissed > 1) { dailySupplyAtLastPurchase = globalSupplyAfterPercentageLogic.mul(2).div(36525); supply = dailySupplyAtLastPurchase.add(supply).mul(totalAuctionMissed).div(2); } supply = (supply.mul(tokensHere)).div(globalSupplyAfterPercentageLogic); } else { if (totalAuctionMissed > 1) { supply = supply.mul(totalAuctionMissed); } uint previousGlobalMetSupply = INITIAL_SUPPLY.add(INITIAL_GLOBAL_DAILY_SUPPLY.mul(whichAuction(lastPurchaseTick))); supply = (supply.mul(tokensHere)).div(previousGlobalMetSupply); } } /// @notice price at a number of minutes out in Initial auction and daily auction /// @param _tick Metronome tick /// @return weiPerToken function calcPriceAt(uint _tick) internal constant returns (uint weiPerToken) { uint recentAuction = whichAuction(lastPurchaseTick); uint totalAuctions = whichAuction(_tick).sub(recentAuction); uint prevPrice; uint numTicks = 0; // Auction is sold out and metronome clock is in same auction if (mintable == 0 && totalAuctions == 0) { return lastPurchasePrice; } // Metronome has missed one auction ie no purchase in last auction if (totalAuctions > 1) { prevPrice = lastPurchasePrice / 100 + 1; numTicks = numTicksSinceAuctionStart(_tick); } else if (totalAuctions == 1) { // Metronome clock is in new auction, next auction // previous auction sold out if (mintable == 0) { prevPrice = lastPurchasePrice * 2; } else { // previous auctions timed out // first daily auction if (whichAuction(_tick) == 1) { prevPrice = minimumPrice * 2; } else { prevPrice = priceAt(lastPurchasePrice, numTicksTillAuctionStart(_tick)) * 2; } } numTicks = numTicksSinceAuctionStart(_tick); } else { //Auction is running prevPrice = lastPurchasePrice; numTicks = _tick - lastPurchaseTick; } require(numTicks >= 0); if (isInitialAuctionEnded()) { weiPerToken = priceAt(prevPrice, numTicks); } else { weiPerToken = priceAtInitialAuction(prevPrice, numTicks); } } /// @notice Calculate number of ticks elapsed between auction start time and given tick. /// @param _tick Given metronome tick function numTicksSinceAuctionStart(uint _tick) private view returns (uint ) { uint currentAuctionStartTime = auctionStartTime(_tick); return _tick - whichTick(currentAuctionStartTime); } /// @notice Calculate number of ticks elapsed between lastPurchaseTick and auctions start time of given tick. /// @param _tick Given metronome tick function numTicksTillAuctionStart(uint _tick) private view returns (uint) { uint currentAuctionStartTime = auctionStartTime(_tick); return whichTick(currentAuctionStartTime) - lastPurchaseTick; } /// @notice First calculate the auction which contains the given tick and then calculate /// auction start time of given tick. /// @param _tick Metronome tick function auctionStartTime(uint _tick) private view returns (uint) { return ((whichAuction(_tick)) * 1 days) / timeScale + dailyAuctionStartTime - 1 days; } /// @notice start the next day's auction function restartAuction() private { uint time; uint price; uint auctionTokens; (time, price, auctionTokens) = nextAuction(); uint thisAuction = currentAuction(); if (thisAuction > AUCTION_WHEN_PERCENTAGE_LOGIC_STARTS) { globalSupplyAfterPercentageLogic = globalSupplyAfterPercentageLogic.add(globalDailySupply()); } mintable = mintable.add(auctionTokens); lastPurchasePrice = price; lastPurchaseTick = whichTick(time); } } /// @title This contract serves as a locker for a founder's tokens contract TokenLocker is Ownable { using SafeMath for uint; uint internal constant QUARTER = 91 days + 450 minutes; Auctions public auctions; METToken public token; bool public locked = false; uint public deposited; uint public lastWithdrawTime; uint public quarterlyWithdrawable; event Withdrawn(address indexed who, uint amount); event Deposited(address indexed who, uint amount); modifier onlyAuction() { require(msg.sender == address(auctions)); _; } modifier preLock() { require(!locked); _; } modifier postLock() { require(locked); _; } /// @notice Constructor to initialize TokenLocker contract. /// @param _auctions Address of auctions contract /// @param _token Address of METToken contract function TokenLocker(address _auctions, address _token) public { require(_auctions != 0x0); require(_token != 0x0); auctions = Auctions(_auctions); token = METToken(_token); } /// @notice If auctions is initialized, call to this function will result in /// locking of deposited tokens and further deposit of tokens will not be allowed. function lockTokenLocker() public onlyAuction { require(auctions.initialAuctionEndTime() != 0); require(auctions.initialAuctionEndTime() >= auctions.genesisTime()); locked = true; } /// @notice It will deposit tokens into the locker for given beneficiary. /// @param beneficiary Address of the beneficiary, whose tokens are being locked. /// @param amount Amount of tokens being locked function deposit (address beneficiary, uint amount ) public onlyAuction preLock { uint totalBalance = token.balanceOf(this); require(totalBalance.sub(deposited) >= amount); deposited = deposited.add(amount); emit Deposited(beneficiary, amount); } /// @notice This function will allow token withdraw from locker. /// 25% of total deposited tokens can be withdrawn after initial auction end. /// Remaining 75% can be withdrawn in equal amount over 12 quarters. function withdraw() public onlyOwner postLock { require(deposited > 0); uint withdrawable = 0; uint withdrawTime = auctions.initialAuctionEndTime(); if (lastWithdrawTime == 0 && auctions.isInitialAuctionEnded()) { withdrawable = withdrawable.add((deposited.mul(25)).div(100)); quarterlyWithdrawable = (deposited.sub(withdrawable)).div(12); lastWithdrawTime = withdrawTime; } require(lastWithdrawTime != 0); if (now >= lastWithdrawTime.add(QUARTER)) { uint daysSinceLastWithdraw = now.sub(lastWithdrawTime); uint totalQuarters = daysSinceLastWithdraw.div(QUARTER); require(totalQuarters > 0); withdrawable = withdrawable.add(quarterlyWithdrawable.mul(totalQuarters)); if (now >= withdrawTime.add(QUARTER.mul(12))) { withdrawable = deposited; } lastWithdrawTime = lastWithdrawTime.add(totalQuarters.mul(QUARTER)); } if (withdrawable > 0) { deposited = deposited.sub(withdrawable); token.transfer(msg.sender, withdrawable); emit Withdrawn(msg.sender, withdrawable); } } } /// @title Interface for TokenPorter contract. /// Define events and functions for TokenPorter contract interface ITokenPorter { event ExportOnChainClaimedReceiptLog(address indexed destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amount); event ExportReceiptLog(bytes8 destinationChain, address destinationMetronomeAddr, address indexed destinationRecipientAddr, uint amountToBurn, uint fee, bytes extraData, uint currentTick, uint indexed burnSequence, bytes32 indexed currentBurnHash, bytes32 prevBurnHash, uint dailyMintable, uint[] supplyOnAllChains, uint genesisTime, uint blockTimestamp, uint dailyAuctionStartTime); event ImportReceiptLog(address indexed destinationRecipientAddr, uint amountImported, uint fee, bytes extraData, uint currentTick, uint indexed importSequence, bytes32 indexed currentHash, bytes32 prevHash, uint dailyMintable, uint blockTimestamp, address caller); function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool); function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool); } /// @title This contract will provide export functionality for tokens. contract TokenPorter is ITokenPorter, Owned { using SafeMath for uint; Auctions public auctions; METToken public token; Validator public validator; ChainLedger public chainLedger; uint public burnSequence = 1; uint public importSequence = 1; bytes32[] public exportedBurns; uint[] public supplyOnAllChains = new uint[](6); /// @notice mapping that tracks valid destination chains for export mapping(bytes8 => address) public destinationChains; /// @notice Initialize TokenPorter contract. /// @param _tokenAddr Address of metToken contract /// @param _auctionsAddr Address of auctions contract function initTokenPorter(address _tokenAddr, address _auctionsAddr) public onlyOwner { require(_tokenAddr != 0x0); require(_auctionsAddr != 0x0); auctions = Auctions(_auctionsAddr); token = METToken(_tokenAddr); } /// @notice set address of validator contract /// @param _validator address of validator contract function setValidator(address _validator) public onlyOwner returns (bool) { require(_validator != 0x0); validator = Validator(_validator); return true; } /// @notice set address of chainLedger contract /// @param _chainLedger address of chainLedger contract function setChainLedger(address _chainLedger) public onlyOwner returns (bool) { require(_chainLedger != 0x0); chainLedger = ChainLedger(_chainLedger); return true; } /// @notice only owner can add destination chains /// @param _chainName string of destination blockchain name /// @param _contractAddress address of destination MET token to import to function addDestinationChain(bytes8 _chainName, address _contractAddress) public onlyOwner returns (bool) { require(_chainName != 0 && _contractAddress != address(0)); destinationChains[_chainName] = _contractAddress; return true; } /// @notice only owner can remove destination chains /// @param _chainName string of destination blockchain name function removeDestinationChain(bytes8 _chainName) public onlyOwner returns (bool) { require(_chainName != 0); require(destinationChains[_chainName] != address(0)); destinationChains[_chainName] = address(0); return true; } /// @notice holds claims from users that have exported on-chain /// @param key is address of destination MET token contract /// @param subKey is address of users account that burned their original MET token mapping (address => mapping(address => uint)) public claimables; /// @notice destination MET token contract calls claimReceivables to record burned /// tokens have been minted in new chain /// @param recipients array of addresses of each user that has exported from /// original chain. These can be generated by ExportReceiptLog function claimReceivables(address[] recipients) public returns (uint) { require(recipients.length > 0); uint total; for (uint i = 0; i < recipients.length; i++) { address recipient = recipients[i]; uint amountBurned = claimables[msg.sender][recipient]; if (amountBurned > 0) { claimables[msg.sender][recipient] = 0; emit ExportOnChainClaimedReceiptLog(msg.sender, recipient, amountBurned); total = total.add(1); } } return total; } /// @notice import MET tokens from another chain to this chain. /// @param _destinationChain destination chain name /// @param _addresses _addresses[0] is destMetronomeAddr and _addresses[1] is recipientAddr /// @param _extraData extra information for import /// @param _burnHashes _burnHashes[0] is previous burnHash, _burnHashes[1] is current burnHash /// @param _supplyOnAllChains MET supply on all supported chains /// @param _importData _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee /// _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, _importData[5] is _dailyMintable /// _importData[6] is _burnSequence, _importData[7] is _dailyAuctionStartTime /// @param _proof proof /// @return true/false function importMET(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChains, uint[] _importData, bytes _proof) public returns (bool) { require(msg.sender == address(token)); require(_importData.length == 8); require(_addresses.length == 2); require(_burnHashes.length == 2); require(validator.isReceiptClaimable(_originChain, _destinationChain, _addresses, _extraData, _burnHashes, _supplyOnAllChains, _importData, _proof)); validator.claimHash(_burnHashes[1]); require(_destinationChain == auctions.chain()); uint amountToImport = _importData[1].add(_importData[2]); require(amountToImport.add(token.totalSupply()) <= auctions.globalMetSupply()); require(_addresses[0] == address(token)); if (_importData[1] == 0) { return false; } if (importSequence == 1 && token.totalSupply() == 0) { auctions.prepareAuctionForNonOGChain(); } token.mint(_addresses[1], _importData[1]); emit ImportReceiptLog(_addresses[1], _importData[1], _importData[2], _extraData, auctions.currentTick(), importSequence, _burnHashes[1], _burnHashes[0], auctions.dailyMintable(), now, msg.sender); importSequence++; chainLedger.registerImport(_originChain, _destinationChain, _importData[1]); return true; } /// @notice Export MET tokens from this chain to another chain. /// @param tokenOwner Owner of the token, whose tokens are being exported. /// @param _destChain Destination chain for exported tokens /// @param _destMetronomeAddr Metronome address on destination chain /// @param _destRecipAddr Recipient address on the destination chain /// @param _amount Amount of token being exported /// @param _extraData Extra data for this export /// @return boolean true/false based on the outcome of export function export(address tokenOwner, bytes8 _destChain, address _destMetronomeAddr, address _destRecipAddr, uint _amount, uint _fee, bytes _extraData) public returns (bool) { require(msg.sender == address(token)); require(_destChain != 0x0 && _destMetronomeAddr != 0x0 && _destRecipAddr != 0x0 && _amount != 0); require(destinationChains[_destChain] == _destMetronomeAddr); require(token.balanceOf(tokenOwner) >= _amount.add(_fee)); token.destroy(tokenOwner, _amount.add(_fee)); uint dailyMintable = auctions.dailyMintable(); uint currentTick = auctions.currentTick(); if (burnSequence == 1) { exportedBurns.push(keccak256(uint8(0))); } if (_destChain == auctions.chain()) { claimables[_destMetronomeAddr][_destRecipAddr] = claimables[_destMetronomeAddr][_destRecipAddr].add(_amount); } uint blockTime = block.timestamp; bytes32 currentBurn = keccak256( blockTime, auctions.chain(), _destChain, _destMetronomeAddr, _destRecipAddr, _amount, currentTick, auctions.genesisTime(), dailyMintable, token.totalSupply(), _extraData, exportedBurns[burnSequence - 1]); exportedBurns.push(currentBurn); supplyOnAllChains[0] = token.totalSupply(); emit ExportReceiptLog(_destChain, _destMetronomeAddr, _destRecipAddr, _amount, _fee, _extraData, currentTick, burnSequence, currentBurn, exportedBurns[burnSequence - 1], dailyMintable, supplyOnAllChains, auctions.genesisTime(), blockTime, auctions.dailyAuctionStartTime()); burnSequence = burnSequence + 1; chainLedger.registerExport(auctions.chain(), _destChain, _amount); return true; } } contract ChainLedger is Owned { using SafeMath for uint; mapping (bytes8 => uint) public balance; mapping (bytes8 => bool) public validChain; bytes8[] public chains; address public tokenPorter; Auctions public auctions; event LogRegisterChain(address indexed caller, bytes8 indexed chain, uint supply, bool outcome); event LogRegisterExport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); event LogRegisterImport(address indexed caller, bytes8 indexed originChain, bytes8 indexed destChain, uint amount); function initChainLedger(address _tokenPorter, address _auctionsAddr) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); require(_auctionsAddr != 0x0); tokenPorter = _tokenPorter; auctions = Auctions(_auctionsAddr); return true; } function registerChain(bytes8 chain, uint supply) public onlyOwner returns (bool) { require(!validChain[chain]); validChain[chain] = true; chains.push(chain); balance[chain] = supply; emit LogRegisterChain(msg.sender, chain, supply, true); } function registerExport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); require(balance[originChain] >= amount); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterExport(msg.sender, originChain, destChain, amount); } function registerImport(bytes8 originChain, bytes8 destChain, uint amount) public { require(msg.sender == tokenPorter || msg.sender == owner); require(validChain[originChain] && validChain[destChain]); balance[originChain] = balance[originChain].sub(amount); balance[destChain] = balance[destChain].add(amount); emit LogRegisterImport(msg.sender, originChain, destChain, amount); } } contract Validator is Owned { mapping (bytes32 => mapping (address => bool)) public hashAttestations; mapping (address => bool) public isValidator; mapping (address => uint8) public validatorNum; address[] public validators; address public metToken; address public tokenPorter; mapping (bytes32 => bool) public hashClaimed; uint8 public threshold = 2; event LogAttestation(bytes32 indexed hash, address indexed who, bool isValid); /// @param _validator1 first validator /// @param _validator2 second validator /// @param _validator3 third validator function initValidator(address _validator1, address _validator2, address _validator3) public onlyOwner { // Clear old validators. Validators can be updated multiple times for (uint8 i = 0; i < validators.length; i++) { delete isValidator[validators[i]]; delete validatorNum[validators[i]]; } delete validators; validators.push(_validator1); validators.push(_validator2); validators.push(_validator3); // TODO: This will be NA, Bloq and a third party (escrow or company) at launch, // and should be scripted into deploy isValidator[_validator1] = true; isValidator[_validator2] = true; isValidator[_validator3] = true; validatorNum[_validator1] = 0; validatorNum[_validator2] = 1; validatorNum[_validator3] = 2; } /// @notice set address of token porter /// @param _tokenPorter address of token porter function setTokenPorter(address _tokenPorter) public onlyOwner returns (bool) { require(_tokenPorter != 0x0); tokenPorter = _tokenPorter; return true; } function validateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = true; emit LogAttestation(hash, msg.sender, true); } function invalidateHash(bytes32 hash) public { require(isValidator[msg.sender]); hashAttestations[hash][msg.sender] = false; emit LogAttestation(hash, msg.sender, false); } function hashClaimable(bytes32 hash) public view returns(bool) { if (hashClaimed[hash]) { return false; } uint8 count = 0; for (uint8 i = 0; i < validators.length; i++) { if (hashAttestations[hash][validators[i]]) { count++;} } if (count >= threshold) { return true; } return false; } function claimHash(bytes32 hash) public { require(msg.sender == tokenPorter); require(hashClaimable(hash)); hashClaimed[hash] = true; } function isReceiptClaimable(bytes8 _originChain, bytes8 _destinationChain, address[] _addresses, bytes _extraData, bytes32[] _burnHashes, uint[] _supplyOnAllChain, uint[] _importData, bytes _proof) public view returns(bool) { // We want to validate that these hash to the provided hash as a safety check, // then we want to know if the hash is Claimable. // Due to stack too deep error and limitation in using number of local // variables we have to use uint array here. // _importData[0] is _blockTimestamp, _importData[1] is _amount, _importData[2] is _fee, // _importData[3] is _burnedAtTick, _importData[4] is _genesisTime, // _importData[5] is _dailyMintable, _importData[6] is _burnSequence, // _addresses[0] is _destMetronomeAddr and _addresses[1] is _recipAddr require(_burnHashes[1] == keccak256(_importData[0], _originChain, _destinationChain, _addresses[0], _addresses[1], _importData[1], _importData[3], _importData[4], _importData[5], _supplyOnAllChain[0], _extraData, _burnHashes[0])); if (hashClaimable(_burnHashes[1])) { return true; } return false; } }
* @title SafeMath @dev Math operations with safety checks that throw on error/
library SafeMath { The MIT License (MIT) pragma solidity ^0.4.21; 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 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) { uint256 c = a / b; 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; } }
1,844,235
[ 1, 9890, 10477, 225, 2361, 5295, 598, 24179, 4271, 716, 604, 603, 555, 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, 12083, 14060, 10477, 288, 203, 203, 203, 203, 565, 1021, 490, 1285, 16832, 261, 6068, 13, 203, 683, 9454, 18035, 560, 3602, 20, 18, 24, 18, 5340, 31, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 14064, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 69, 422, 374, 13, 288, 203, 5411, 327, 374, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 1815, 12, 71, 342, 279, 422, 324, 1769, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 3739, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 342, 324, 31, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 1815, 12, 70, 1648, 279, 1769, 203, 3639, 327, 279, 300, 324, 31, 203, 565, 289, 203, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 2 ]
./full_match/42/0xaD81A91c0b96d5e6F859B129529FEC40b527576D/sources/bid.sol
Modifiers are a convenient way to validate inputs to functions. `onlyBefore` is applied to `bid` below: The new function body is the modifier's body where `_` is replaced by the old function body.
modifier onlyBefore(uint _time) { require(block.timestamp < _time); _; }
9,568,009
[ 1, 11948, 854, 279, 26375, 4031, 358, 1954, 4540, 358, 4186, 18, 1375, 3700, 4649, 68, 353, 6754, 358, 1375, 19773, 68, 5712, 30, 1021, 394, 445, 1417, 353, 326, 9606, 1807, 1417, 1625, 1375, 67, 68, 353, 8089, 635, 326, 1592, 445, 1417, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 9606, 1338, 4649, 12, 11890, 389, 957, 13, 288, 2583, 12, 2629, 18, 5508, 411, 389, 957, 1769, 389, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.11; // File: @laborx/solidity-shared-lib/contracts/ERC20Interface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Defines an interface for EIP20 token smart contract contract ERC20Interface { event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed from, address indexed spender, uint256 value); string public symbol; function decimals() public view returns (uint8); function totalSupply() public view returns (uint256 supply); function balanceOf(address _owner) public view returns (uint256 balance); function transfer(address _to, uint256 _value) public returns (bool success); 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 view returns (uint256 remaining); } // File: contracts/assets/ChronoBankAssetChainableInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankAssetChainableInterface { function assetType() public pure returns (bytes32); function getPreviousAsset() public view returns (ChronoBankAssetChainableInterface); function getNextAsset() public view returns (ChronoBankAssetChainableInterface); function getChainedAssets() public view returns (bytes32[] _types, address[] _assets); function getAssetByType(bytes32 _assetType) public view returns (address); function chainAssets(ChronoBankAssetChainableInterface[] _assets) external returns (bool); function __chainAssetsFromIdx(ChronoBankAssetChainableInterface[] _assets, uint _startFromIdx) external returns (bool); function finalizeAssetChaining() public; } // File: contracts/assets/ChronoBankAssetUtils.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; library ChronoBankAssetUtils { uint constant ASSETS_CHAIN_MAX_LENGTH = 20; function getChainedAssets(ChronoBankAssetChainableInterface _asset) public view returns (bytes32[] _types, address[] _assets) { bytes32[] memory _tempTypes = new bytes32[](ASSETS_CHAIN_MAX_LENGTH); address[] memory _tempAssets = new address[](ASSETS_CHAIN_MAX_LENGTH); ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); uint _counter = 0; do { _tempTypes[_counter] = _next.assetType(); _tempAssets[_counter] = address(_next); _counter += 1; _next = _next.getNextAsset(); } while (address(_next) != 0x0); _types = new bytes32[](_counter); _assets = new address[](_counter); for (uint _assetIdx = 0; _assetIdx < _counter; ++_assetIdx) { _types[_assetIdx] = _tempTypes[_assetIdx]; _assets[_assetIdx] = _tempAssets[_assetIdx]; } } function getAssetByType(ChronoBankAssetChainableInterface _asset, bytes32 _assetType) public view returns (address) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (_next.assetType() == _assetType) { return address(_next); } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function containsAssetInChain(ChronoBankAssetChainableInterface _asset, address _checkAsset) public view returns (bool) { ChronoBankAssetChainableInterface _next = getHeadAsset(_asset); do { if (address(_next) == _checkAsset) { return true; } _next = _next.getNextAsset(); } while (address(_next) != 0x0); } function getHeadAsset(ChronoBankAssetChainableInterface _asset) public view returns (ChronoBankAssetChainableInterface) { ChronoBankAssetChainableInterface _head = _asset; ChronoBankAssetChainableInterface _previousAsset; do { _previousAsset = _head.getPreviousAsset(); if (address(_previousAsset) == 0x0) { return _head; } _head = _previousAsset; } while (true); } } // File: @laborx/solidity-eventshistory-lib/contracts/EventsHistorySourceAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title EventsHistory Source Adapter. */ contract EventsHistorySourceAdapter { // It is address of MultiEventsHistory caller assuming we are inside of delegate call. function _self() internal view returns (address) { return msg.sender; } } // File: @laborx/solidity-eventshistory-lib/contracts/MultiEventsHistoryAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /** * @title General MultiEventsHistory user. */ contract MultiEventsHistoryAdapter is EventsHistorySourceAdapter { address internal localEventsHistory; event ErrorCode(address indexed self, uint errorCode); function getEventsHistory() public view returns (address) { address _eventsHistory = localEventsHistory; return _eventsHistory != 0x0 ? _eventsHistory : this; } function emitErrorCode(uint _errorCode) public { emit ErrorCode(_self(), _errorCode); } function _setEventsHistory(address _eventsHistory) internal returns (bool) { localEventsHistory = _eventsHistory; return true; } function _emitErrorCode(uint _errorCode) internal returns (uint) { MultiEventsHistoryAdapter(getEventsHistory()).emitErrorCode(_errorCode); return _errorCode; } } // File: contracts/ChronoBankPlatformEmitter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; /// @title ChronoBank Platform Emitter. /// /// Contains all the original event emitting function definitions and events. /// In case of new events needed later, additional emitters can be developed. /// All the functions is meant to be called using delegatecall. contract ChronoBankPlatformEmitter is MultiEventsHistoryAdapter { event Transfer(address indexed from, address indexed to, bytes32 indexed symbol, uint value, string reference); event Issue(bytes32 indexed symbol, uint value, address indexed by); event Revoke(bytes32 indexed symbol, uint value, address indexed by); event RevokeExternal(bytes32 indexed symbol, uint value, address indexed by, string externalReference); event OwnershipChange(address indexed from, address indexed to, bytes32 indexed symbol); event Approve(address indexed from, address indexed spender, bytes32 indexed symbol, uint value); event Recovery(address indexed from, address indexed to, address by); function emitTransfer(address _from, address _to, bytes32 _symbol, uint _value, string _reference) public { emit Transfer(_from, _to, _symbol, _value, _reference); } function emitIssue(bytes32 _symbol, uint _value, address _by) public { emit Issue(_symbol, _value, _by); } function emitRevoke(bytes32 _symbol, uint _value, address _by) public { emit Revoke(_symbol, _value, _by); } function emitRevokeExternal(bytes32 _symbol, uint _value, address _by, string _externalReference) public { emit RevokeExternal(_symbol, _value, _by, _externalReference); } function emitOwnershipChange(address _from, address _to, bytes32 _symbol) public { emit OwnershipChange(_from, _to, _symbol); } function emitApprove(address _from, address _spender, bytes32 _symbol, uint _value) public { emit Approve(_from, _spender, _symbol, _value); } function emitRecovery(address _from, address _to, address _by) public { emit Recovery(_from, _to, _by); } } // File: contracts/ChronoBankPlatformInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; contract ChronoBankPlatformInterface is ChronoBankPlatformEmitter { mapping(bytes32 => address) public proxies; function symbols(uint _idx) public view returns (bytes32); function symbolsCount() public view returns (uint); function isCreated(bytes32 _symbol) public view returns(bool); function isOwner(address _owner, bytes32 _symbol) public view returns(bool); function owner(bytes32 _symbol) public view returns(address); function setProxy(address _address, bytes32 _symbol) public returns(uint errorCode); function name(bytes32 _symbol) public view returns(string); function totalSupply(bytes32 _symbol) public view returns(uint); function balanceOf(address _holder, bytes32 _symbol) public view returns(uint); function allowance(address _from, address _spender, bytes32 _symbol) public view returns(uint); function baseUnit(bytes32 _symbol) public view returns(uint8); function description(bytes32 _symbol) public view returns(string); function isReissuable(bytes32 _symbol) public view returns(bool); function blockNumber(bytes32 _symbol) public view returns (uint); function proxyTransferWithReference(address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyTransferFromWithReference(address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender) public returns(uint errorCode); function proxyApprove(address _spender, uint _value, bytes32 _symbol, address _sender) public returns(uint errorCode); function issueAsset(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber) public returns(uint errorCode); function issueAssetWithInitialReceiver(bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account) public returns(uint errorCode); function reissueAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public returns (uint); function revokeAsset(bytes32 _symbol, uint _value) public returns(uint errorCode); function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint); function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool); function isDesignatedAssetManager(address _account, bytes32 _symbol) public view returns (bool); function changeOwnership(bytes32 _symbol, address _newOwner) public returns(uint errorCode); } // File: contracts/ChronoBankAssetInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetInterface { function __transferWithReference(address _to, uint _value, string _reference, address _sender) public returns (bool); function __transferFromWithReference(address _from, address _to, uint _value, string _reference, address _sender) public returns (bool); function __approve(address _spender, uint _value, address _sender) public returns(bool); function __process(bytes /*_data*/, address /*_sender*/) public payable { revert("ASSET_PROCESS_NOT_SUPPORTED"); } } // File: contracts/ChronoBankAssetProxy.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ERC20 is ERC20Interface {} contract ChronoBankAsset is ChronoBankAssetInterface {} /// @title ChronoBank Asset Proxy. /// /// Proxy implements ERC20 interface and acts as a gateway to a single platform asset. /// Proxy adds symbol and caller(sender) when forwarding requests to platform. /// Every request that is made by caller first sent to the specific asset implementation /// contract, which then calls back to be forwarded onto platform. /// /// Calls flow: Caller -> /// Proxy.func(...) -> /// Asset.__func(..., Caller.address) -> /// Proxy.__func(..., Caller.address) -> /// Platform.proxyFunc(..., symbol, Caller.address) /// /// Asset implementation contract is mutable, but each user have an option to stick with /// old implementation, through explicit decision made in timely manner, if he doesn't agree /// with new rules. /// Each user have a possibility to upgrade to latest asset contract implementation, without the /// possibility to rollback. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankAssetProxy is ERC20 { /// @dev Supports ChronoBankPlatform ability to return error codes from methods uint constant OK = 1; /// @dev Assigned platform, immutable. ChronoBankPlatform public chronoBankPlatform; /// @dev Assigned symbol, immutable. bytes32 public smbl; /// @dev Assigned name, immutable. string public name; /// @dev Assigned symbol (from ERC20 standard), immutable string public symbol; /// @notice Sets platform address, assigns symbol and name. /// Can be set only once. /// @param _chronoBankPlatform platform contract address. /// @param _symbol assigned symbol. /// @param _name assigned name. /// @return success. function init(ChronoBankPlatform _chronoBankPlatform, string _symbol, string _name) public returns (bool) { if (address(chronoBankPlatform) != 0x0) { return false; } chronoBankPlatform = _chronoBankPlatform; symbol = _symbol; smbl = stringToBytes32(_symbol); name = _name; return true; } function stringToBytes32(string memory source) public pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @dev Only platform is allowed to call. modifier onlyChronoBankPlatform { if (msg.sender == address(chronoBankPlatform)) { _; } } /// @dev Only current asset owner is allowed to call. modifier onlyAssetOwner { if (chronoBankPlatform.isOwner(msg.sender, smbl)) { _; } } /// @dev Returns asset implementation contract for current caller. /// @return asset implementation contract. function _getAsset() internal view returns (ChronoBankAsset) { return ChronoBankAsset(getVersionFor(msg.sender)); } /// @notice Returns asset total supply. /// @return asset total supply. function totalSupply() public view returns (uint) { return chronoBankPlatform.totalSupply(smbl); } /// @notice Returns asset balance for a particular holder. /// @param _owner holder address. /// @return holder balance. function balanceOf(address _owner) public view returns (uint) { return chronoBankPlatform.balanceOf(_owner, smbl); } /// @notice Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @return holder to spender allowance. function allowance(address _from, address _spender) public view returns (uint) { return chronoBankPlatform.allowance(_from, _spender, smbl); } /// @notice Returns asset decimals. /// @return asset decimals. function decimals() public view returns (uint8) { return chronoBankPlatform.baseUnit(smbl); } /// @notice Transfers asset balance from the caller to specified receiver. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transfer(address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, ""); } } /// @notice Transfers asset balance from the caller to specified receiver adding specified comment. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @return success. function transferWithReference(address _to, uint _value, string _reference) public returns (bool) { if (_to != 0x0) { return _transferWithReference(_to, _value, _reference); } } /// @notice Resolves asset implementation contract for the caller and forwards there arguments along with /// the caller address. /// @return success. function _transferWithReference(address _to, uint _value, string _reference) internal returns (bool) { return _getAsset().__transferWithReference(_to, _value, _reference, msg.sender); } /// @notice Performs transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferWithReference( address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferWithReference(_to, _value, smbl, _reference, _sender) == OK; } /// @notice Performs allowance transfer of asset balance between holders. /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @return success. function transferFrom(address _from, address _to, uint _value) public returns (bool) { if (_to != 0x0) { return _getAsset().__transferFromWithReference(_from, _to, _value, "", msg.sender); } } /// @notice Performs allowance transfer call on the platform by the name of specified sender. /// /// Can only be called by asset implementation contract assigned to sender. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _reference transfer comment to be included in a platform's Transfer event. /// @param _sender initial caller. /// /// @return success. function __transferFromWithReference( address _from, address _to, uint _value, string _reference, address _sender ) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyTransferFromWithReference(_from, _to, _value, smbl, _reference, _sender) == OK; } /// @notice Sets asset spending allowance for a specified spender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @return success. function approve(address _spender, uint _value) public returns (bool) { if (_spender != 0x0) { return _getAsset().__approve(_spender, _value, msg.sender); } } /// @notice Performs allowance setting call on the platform by the name of specified sender. /// Can only be called by asset implementation contract assigned to sender. /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _sender initial caller. /// @return success. function __approve(address _spender, uint _value, address _sender) onlyAccess(_sender) public returns (bool) { return chronoBankPlatform.proxyApprove(_spender, _value, smbl, _sender) == OK; } /// @notice Emits ERC20 Transfer event on this contract. /// Can only be, and, called by assigned platform when asset transfer happens. function emitTransfer(address _from, address _to, uint _value) onlyChronoBankPlatform public { emit Transfer(_from, _to, _value); } /// @notice Emits ERC20 Approval event on this contract. /// Can only be, and, called by assigned platform when asset allowance set happens. function emitApprove(address _from, address _spender, uint _value) onlyChronoBankPlatform public { emit Approval(_from, _spender, _value); } /// @notice Resolves asset implementation contract for the caller and forwards there transaction data, /// along with the value. This allows for proxy interface growth. function () public payable { _getAsset().__process.value(msg.value)(msg.data, msg.sender); } /// @dev Indicates an upgrade freeze-time start, and the next asset implementation contract. event UpgradeProposal(address newVersion); /// @dev Current asset implementation contract address. address latestVersion; /// @dev Proposed next asset implementation contract address. address pendingVersion; /// @dev Upgrade freeze-time start. uint pendingVersionTimestamp; /// @dev Timespan for users to review the new implementation and make decision. uint constant UPGRADE_FREEZE_TIME = 3 days; /// @dev Asset implementation contract address that user decided to stick with. /// 0x0 means that user uses latest version. mapping(address => address) userOptOutVersion; /// @dev Only asset implementation contract assigned to sender is allowed to call. modifier onlyAccess(address _sender) { address _versionFor = getVersionFor(_sender); if (msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender) ) { _; } } /// @notice Returns asset implementation contract address assigned to sender. /// @param _sender sender address. /// @return asset implementation contract address. function getVersionFor(address _sender) public view returns (address) { return userOptOutVersion[_sender] == 0 ? latestVersion : userOptOutVersion[_sender]; } /// @notice Returns current asset implementation contract address. /// @return asset implementation contract address. function getLatestVersion() public view returns (address) { return latestVersion; } /// @notice Returns proposed next asset implementation contract address. /// @return asset implementation contract address. function getPendingVersion() public view returns (address) { return pendingVersion; } /// @notice Returns upgrade freeze-time start. /// @return freeze-time start. function getPendingVersionTimestamp() public view returns (uint) { return pendingVersionTimestamp; } /// @notice Propose next asset implementation contract address. /// Can only be called by current asset owner. /// Note: freeze-time should not be applied for the initial setup. /// @param _newVersion asset implementation contract address. /// @return success. function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { // Should not already be in the upgrading process. if (pendingVersion != 0x0) { return false; } // New version address should be other than 0x0. if (_newVersion == 0x0) { return false; } // Don't apply freeze-time for the initial setup. if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; } /// @notice Cancel the pending upgrade process. /// Can only be called by current asset owner. /// @return success. function purgeUpgrade() public onlyAssetOwner returns (bool) { if (pendingVersion == 0x0) { return false; } delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Finalize an upgrade process setting new asset implementation contract address. /// Can only be called after an upgrade freeze-time. /// @return success. function commitUpgrade() public returns (bool) { if (pendingVersion == 0x0) { return false; } if (pendingVersionTimestamp + UPGRADE_FREEZE_TIME > now) { return false; } latestVersion = pendingVersion; delete pendingVersion; delete pendingVersionTimestamp; return true; } /// @notice Disagree with proposed upgrade, and stick with current asset implementation /// until further explicit agreement to upgrade. /// @return success. function optOut() public returns (bool) { if (userOptOutVersion[msg.sender] != 0x0) { return false; } userOptOutVersion[msg.sender] = latestVersion; return true; } /// @notice Implicitly agree to upgrade to current and future asset implementation upgrades, /// until further explicit disagreement. /// @return success. function optIn() public returns (bool) { delete userOptOutVersion[msg.sender]; return true; } } // File: @laborx/solidity-shared-lib/contracts/Owned.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; /// @title Owned contract with safe ownership pass. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract Owned { event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); address public contractOwner; address public pendingContractOwner; modifier onlyContractOwner { if (msg.sender == contractOwner) { _; } } constructor() public { contractOwner = msg.sender; } /// @notice Prepares ownership pass. /// Can only be called by current owner. /// @param _to address of the next owner. /// @return success. function changeContractOwnership(address _to) public onlyContractOwner returns (bool) { if (_to == 0x0) { return false; } pendingContractOwner = _to; return true; } /// @notice Finalize ownership pass. /// Can only be called by pending owner. /// @return success. function claimContractOwnership() public returns (bool) { if (msg.sender != pendingContractOwner) { return false; } emit OwnershipTransferred(contractOwner, pendingContractOwner); contractOwner = pendingContractOwner; delete pendingContractOwner; return true; } /// @notice 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 onlyContractOwner returns (bool) { if (newOwner == 0x0) { return false; } emit OwnershipTransferred(contractOwner, newOwner); contractOwner = newOwner; delete pendingContractOwner; return true; } /// @notice Allows the current owner to transfer control of the contract to a newOwner. /// @dev Backward compatibility only. /// @param newOwner The address to transfer ownership to. function transferContractOwnership(address newOwner) public returns (bool) { return transferOwnership(newOwner); } /// @notice Withdraw given tokens from contract to owner. /// This method is only allowed for contact owner. function withdrawTokens(address[] tokens) public onlyContractOwner { address _contractOwner = contractOwner; for (uint i = 0; i < tokens.length; i++) { ERC20Interface token = ERC20Interface(tokens[i]); uint balance = token.balanceOf(this); if (balance > 0) { token.transfer(_contractOwner, balance); } } } /// @notice Withdraw ether from contract to owner. /// This method is only allowed for contact owner. function withdrawEther() public onlyContractOwner { uint balance = address(this).balance; if (balance > 0) { contractOwner.transfer(balance); } } /// @notice Transfers ether to another address. /// Allowed only for contract owners. /// @param _to recepient address /// @param _value wei to transfer; must be less or equal to total balance on the contract function transferEther(address _to, uint256 _value) public onlyContractOwner { require(_to != 0x0, "INVALID_ETHER_RECEPIENT_ADDRESS"); if (_value > address(this).balance) { revert("INVALID_VALUE_TO_TRANSFER_ETHER"); } _to.transfer(_value); } } // File: @laborx/solidity-storage-lib/contracts/Storage.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract Manager { function isAllowed(address _actor, bytes32 _role) public view returns (bool); function hasAccess(address _actor) public view returns (bool); } contract Storage is Owned { struct Crate { mapping(bytes32 => uint) uints; mapping(bytes32 => address) addresses; mapping(bytes32 => bool) bools; mapping(bytes32 => int) ints; mapping(bytes32 => uint8) uint8s; mapping(bytes32 => bytes32) bytes32s; mapping(bytes32 => AddressUInt8) addressUInt8s; mapping(bytes32 => string) strings; } struct AddressUInt8 { address _address; uint8 _uint8; } mapping(bytes32 => Crate) internal crates; Manager public manager; modifier onlyAllowed(bytes32 _role) { if (!(msg.sender == address(this) || manager.isAllowed(msg.sender, _role))) { revert("STORAGE_FAILED_TO_ACCESS_PROTECTED_FUNCTION"); } _; } function setManager(Manager _manager) external onlyContractOwner returns (bool) { manager = _manager; return true; } function setUInt(bytes32 _crate, bytes32 _key, uint _value) public onlyAllowed(_crate) { _setUInt(_crate, _key, _value); } function _setUInt(bytes32 _crate, bytes32 _key, uint _value) internal { crates[_crate].uints[_key] = _value; } function getUInt(bytes32 _crate, bytes32 _key) public view returns (uint) { return crates[_crate].uints[_key]; } function setAddress(bytes32 _crate, bytes32 _key, address _value) public onlyAllowed(_crate) { _setAddress(_crate, _key, _value); } function _setAddress(bytes32 _crate, bytes32 _key, address _value) internal { crates[_crate].addresses[_key] = _value; } function getAddress(bytes32 _crate, bytes32 _key) public view returns (address) { return crates[_crate].addresses[_key]; } function setBool(bytes32 _crate, bytes32 _key, bool _value) public onlyAllowed(_crate) { _setBool(_crate, _key, _value); } function _setBool(bytes32 _crate, bytes32 _key, bool _value) internal { crates[_crate].bools[_key] = _value; } function getBool(bytes32 _crate, bytes32 _key) public view returns (bool) { return crates[_crate].bools[_key]; } function setInt(bytes32 _crate, bytes32 _key, int _value) public onlyAllowed(_crate) { _setInt(_crate, _key, _value); } function _setInt(bytes32 _crate, bytes32 _key, int _value) internal { crates[_crate].ints[_key] = _value; } function getInt(bytes32 _crate, bytes32 _key) public view returns (int) { return crates[_crate].ints[_key]; } function setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) public onlyAllowed(_crate) { _setUInt8(_crate, _key, _value); } function _setUInt8(bytes32 _crate, bytes32 _key, uint8 _value) internal { crates[_crate].uint8s[_key] = _value; } function getUInt8(bytes32 _crate, bytes32 _key) public view returns (uint8) { return crates[_crate].uint8s[_key]; } function setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) public onlyAllowed(_crate) { _setBytes32(_crate, _key, _value); } function _setBytes32(bytes32 _crate, bytes32 _key, bytes32 _value) internal { crates[_crate].bytes32s[_key] = _value; } function getBytes32(bytes32 _crate, bytes32 _key) public view returns (bytes32) { return crates[_crate].bytes32s[_key]; } function setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) public onlyAllowed(_crate) { _setAddressUInt8(_crate, _key, _value, _value2); } function _setAddressUInt8(bytes32 _crate, bytes32 _key, address _value, uint8 _value2) internal { crates[_crate].addressUInt8s[_key] = AddressUInt8(_value, _value2); } function getAddressUInt8(bytes32 _crate, bytes32 _key) public view returns (address, uint8) { return (crates[_crate].addressUInt8s[_key]._address, crates[_crate].addressUInt8s[_key]._uint8); } function setString(bytes32 _crate, bytes32 _key, string _value) public onlyAllowed(_crate) { _setString(_crate, _key, _value); } function _setString(bytes32 _crate, bytes32 _key, string _value) internal { crates[_crate].strings[_key] = _value; } function getString(bytes32 _crate, bytes32 _key) public view returns (string) { return crates[_crate].strings[_key]; } } // File: @laborx/solidity-storage-lib/contracts/StorageInterface.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; library StorageInterface { struct Config { Storage store; bytes32 crate; } struct UInt { bytes32 id; } struct UInt8 { bytes32 id; } struct Int { bytes32 id; } struct Address { bytes32 id; } struct Bool { bytes32 id; } struct Bytes32 { bytes32 id; } struct String { bytes32 id; } struct Mapping { bytes32 id; } struct StringMapping { String id; } struct UIntBoolMapping { Bool innerMapping; } struct UIntUIntMapping { Mapping innerMapping; } struct UIntBytes32Mapping { Mapping innerMapping; } struct UIntAddressMapping { Mapping innerMapping; } struct UIntEnumMapping { Mapping innerMapping; } struct AddressBoolMapping { Mapping innerMapping; } struct AddressUInt8Mapping { bytes32 id; } struct AddressUIntMapping { Mapping innerMapping; } struct AddressBytes32Mapping { Mapping innerMapping; } struct AddressAddressMapping { Mapping innerMapping; } struct Bytes32UIntMapping { Mapping innerMapping; } struct Bytes32UInt8Mapping { UInt8 innerMapping; } struct Bytes32BoolMapping { Bool innerMapping; } struct Bytes32Bytes32Mapping { Mapping innerMapping; } struct Bytes32AddressMapping { Mapping innerMapping; } struct Bytes32UIntBoolMapping { Bool innerMapping; } struct AddressAddressUInt8Mapping { Mapping innerMapping; } struct AddressAddressUIntMapping { Mapping innerMapping; } struct AddressUIntUIntMapping { Mapping innerMapping; } struct AddressUIntUInt8Mapping { Mapping innerMapping; } struct AddressBytes32Bytes32Mapping { Mapping innerMapping; } struct AddressBytes4BoolMapping { Mapping innerMapping; } struct AddressBytes4Bytes32Mapping { Mapping innerMapping; } struct UIntAddressUIntMapping { Mapping innerMapping; } struct UIntAddressAddressMapping { Mapping innerMapping; } struct UIntAddressBoolMapping { Mapping innerMapping; } struct UIntUIntAddressMapping { Mapping innerMapping; } struct UIntUIntBytes32Mapping { Mapping innerMapping; } struct UIntUIntUIntMapping { Mapping innerMapping; } struct Bytes32UIntUIntMapping { Mapping innerMapping; } struct AddressUIntUIntUIntMapping { Mapping innerMapping; } struct AddressUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntUIntUIntUIntStructAddressUInt8Mapping { AddressUInt8Mapping innerMapping; } struct AddressUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct AddressUIntUIntUIntAddressUInt8Mapping { Mapping innerMapping; } struct UIntAddressAddressBoolMapping { Bool innerMapping; } struct UIntUIntUIntBytes32Mapping { Mapping innerMapping; } struct Bytes32UIntUIntUIntMapping { Mapping innerMapping; } bytes32 constant SET_IDENTIFIER = "set"; struct Set { UInt count; Mapping indexes; Mapping values; } struct AddressesSet { Set innerSet; } struct CounterSet { Set innerSet; } bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; struct OrderedSet { UInt count; Bytes32 first; Bytes32 last; Mapping nextValues; Mapping previousValues; } struct OrderedUIntSet { OrderedSet innerSet; } struct OrderedAddressesSet { OrderedSet innerSet; } struct Bytes32SetMapping { Set innerMapping; } struct AddressesSetMapping { Bytes32SetMapping innerMapping; } struct UIntSetMapping { Bytes32SetMapping innerMapping; } struct Bytes32OrderedSetMapping { OrderedSet innerMapping; } struct UIntOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } struct AddressOrderedSetMapping { Bytes32OrderedSetMapping innerMapping; } // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert(); } } function init(Config storage self, Storage _store, bytes32 _crate) internal { self.store = _store; self.crate = _crate; } function init(UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(Config storage self, UInt storage item, uint _value) internal { self.store.setUInt(self.crate, item.id, _value); } function set(Config storage self, UInt storage item, bytes32 _salt, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, UInt8 storage item, uint8 _value) internal { self.store.setUInt8(self.crate, item.id, _value); } function set(Config storage self, UInt8 storage item, bytes32 _salt, uint8 _value) internal { self.store.setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Int storage item, int _value) internal { self.store.setInt(self.crate, item.id, _value); } function set(Config storage self, Int storage item, bytes32 _salt, int _value) internal { self.store.setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Address storage item, address _value) internal { self.store.setAddress(self.crate, item.id, _value); } function set(Config storage self, Address storage item, bytes32 _salt, address _value) internal { self.store.setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bool storage item, bool _value) internal { self.store.setBool(self.crate, item.id, _value); } function set(Config storage self, Bool storage item, bytes32 _salt, bool _value) internal { self.store.setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Bytes32 storage item, bytes32 _value) internal { self.store.setBytes32(self.crate, item.id, _value); } function set(Config storage self, Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, String storage item, string _value) internal { self.store.setString(self.crate, item.id, _value); } function set(Config storage self, String storage item, bytes32 _salt, string _value) internal { self.store.setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(Config storage self, Mapping storage item, uint _key, uint _value) internal { self.store.setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _value) internal { self.store.setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(Config storage self, StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(Config storage self, AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { self.store.setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(Config storage self, UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(Config storage self, Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(Config storage self, AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(Config storage self, AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(Config storage self, AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(Config storage self, Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(Config storage self, AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(Config storage self, OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(Config storage self, OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(Config storage self, OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(Config storage self, Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(Config storage self, Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(Config storage self, AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(Config storage self, Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(Config storage self, AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(Config storage self, OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(Config storage self, Set storage source, Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(Config storage self, AddressesSet storage source, AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(Config storage self, CounterSet storage source, CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(Config storage self, UInt storage item) internal view returns (uint) { return self.store.getUInt(self.crate, item.id); } function get(Config storage self, UInt storage item, bytes32 salt) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, UInt8 storage item) internal view returns (uint8) { return self.store.getUInt8(self.crate, item.id); } function get(Config storage self, UInt8 storage item, bytes32 salt) internal view returns (uint8) { return self.store.getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Int storage item) internal view returns (int) { return self.store.getInt(self.crate, item.id); } function get(Config storage self, Int storage item, bytes32 salt) internal view returns (int) { return self.store.getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Address storage item) internal view returns (address) { return self.store.getAddress(self.crate, item.id); } function get(Config storage self, Address storage item, bytes32 salt) internal view returns (address) { return self.store.getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bool storage item) internal view returns (bool) { return self.store.getBool(self.crate, item.id); } function get(Config storage self, Bool storage item, bytes32 salt) internal view returns (bool) { return self.store.getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Bytes32 storage item) internal view returns (bytes32) { return self.store.getBytes32(self.crate, item.id); } function get(Config storage self, Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, String storage item) internal view returns (string) { return self.store.getString(self.crate, item.id); } function get(Config storage self, String storage item, bytes32 salt) internal view returns (string) { return self.store.getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(Config storage self, Mapping storage item, uint _key) internal view returns (uint) { return self.store.getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key) internal view returns (bytes32) { return self.store.getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(Config storage self, AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return self.store.getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(Config storage self, Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(Config storage self, Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(Config storage self, AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(Config storage self, UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(Config storage self, Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(Config storage self, AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(Config storage self, UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(Config storage self, UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(Config storage self, AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(Config storage self, AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(Config storage self, AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(Config storage self, AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(Config storage self, AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(Config storage self, AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(Config storage self, AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(Config storage self, AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(Config storage self, Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(Config storage self, AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(Config storage self, Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(Config storage self, AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(Config storage self, Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(Config storage self, AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(Config storage self, Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(Config storage self, Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(Config storage self, OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(Config storage self, OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(Config storage self, Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(Config storage self, Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(Config storage self, AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(Config storage self, CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(Config storage self, Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(Config storage self, Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(Config storage self, AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(Config storage self, CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(Config storage self, Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(Config storage self, AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(Config storage self, UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(Config storage self, OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(Config storage self, OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(Config storage self, OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(Config storage self, Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /** @title Structure to incapsulate and organize iteration through different kinds of collections */ struct Iterator { uint limit; uint valuesLeft; bytes32 currentValue; bytes32 anchorKey; } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(Config storage self, OrderedSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(Config storage self, OrderedUIntSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit) internal view returns (Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(Config storage self, OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(Config storage self, OrderedSet storage item) internal view returns (Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(Config storage self, OrderedSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(Config storage self, OrderedUIntSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, OrderedAddressesSet storage item) internal view returns (Iterator) { return listIterator(self, item.innerSet); } function listIterator(Config storage self, OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(Config storage self, Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(Config storage self, AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (Iterator) { return Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(Config storage self, OrderedSet storage item, Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(Config storage self, OrderedUIntSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, OrderedAddressesSet storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(Config storage self, Bytes32OrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, UIntOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(Config storage self, AddressOrderedSetMapping storage item, Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-storage-lib/contracts/StorageContractAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageContractAdapter { StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { StorageInterface.init(store, _store, _crate); } } // File: @laborx/solidity-storage-lib/contracts/StorageInterfaceContract.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageInterfaceContract is StorageContractAdapter, Storage { bytes32 constant SET_IDENTIFIER = "set"; bytes32 constant ORDERED_SET_IDENTIFIER = "ordered_set"; // Can't use modifier due to a Solidity bug. function sanityCheck(bytes32 _currentId, bytes32 _newId) internal pure { if (_currentId != 0 || _newId == 0) { revert("STORAGE_INTERFACE_CONTRACT_SANITY_CHECK_FAILED"); } } function init(StorageInterface.Config storage self, bytes32 _crate) internal { self.crate = _crate; } function init(StorageInterface.UInt8 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.UInt storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Int storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Address storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bool storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Bytes32 storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.String storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.StringMapping storage self, bytes32 _id) internal { init(self.id, _id); } function init(StorageInterface.UIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntEnumMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntAddressAddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntUIntUIntBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUInt8Mapping storage self, bytes32 _id) internal { sanityCheck(self.id, _id); self.id = _id; } function init(StorageInterface.AddressUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressBytes4Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UInt8Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32BoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32Bytes32Mapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32AddressMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32UIntBoolMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Set storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "count"))); init(self.indexes, keccak256(abi.encodePacked(_id, "indexes"))); init(self.values, keccak256(abi.encodePacked(_id, "values"))); } function init(StorageInterface.AddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.CounterSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedSet storage self, bytes32 _id) internal { init(self.count, keccak256(abi.encodePacked(_id, "uint/count"))); init(self.first, keccak256(abi.encodePacked(_id, "uint/first"))); init(self.last, keccak256(abi.encodePacked(_id, "uint/last"))); init(self.nextValues, keccak256(abi.encodePacked(_id, "uint/next"))); init(self.previousValues, keccak256(abi.encodePacked(_id, "uint/prev"))); } function init(StorageInterface.OrderedUIntSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.OrderedAddressesSet storage self, bytes32 _id) internal { init(self.innerSet, _id); } function init(StorageInterface.Bytes32SetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressesSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.Bytes32OrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.UIntOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } function init(StorageInterface.AddressOrderedSetMapping storage self, bytes32 _id) internal { init(self.innerMapping, _id); } /** `set` operation */ function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, uint _value) internal { _setUInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 _salt, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, uint8 _value) internal { _setUInt8(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 _salt, uint8 _value) internal { _setUInt8(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, int _value) internal { _setInt(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 _salt, int _value) internal { _setInt(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, address _value) internal { _setAddress(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 _salt, address _value) internal { _setAddress(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bool _value) internal { _setBool(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _salt, bool _value) internal { _setBool(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _value) internal { _setBytes32(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 _salt, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, string _value) internal { _setString(self.crate, item.id, _value); } function set(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 _salt, string _value) internal { _setString(self.crate, keccak256(abi.encodePacked(item.id, _salt)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key, uint _value) internal { _setUInt(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _value) internal { _setBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value); } function set(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key, string _value) internal { set(self, item.id, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key, address _value1, uint8 _value2) internal { _setAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key)), _value1, _value2); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bytes32 _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3, bool _value) internal { set(self, item, keccak256(abi.encodePacked(_key, _key2, _key3)), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key, uint8 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key, bool _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key, bytes32 _value) internal { set(self, item.innerMapping, _key, _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key, address _value) internal { set(self, item.innerMapping, _key, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2, bool _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key, bool _value) internal { set(self, item.innerMapping, bytes32(_key), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _value); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2, uint8 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), _key2, _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2, address _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), _value); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3, uint _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5, address _value, uint8 _value2) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), _value, _value2); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5, uint8 _value) internal { set(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)), bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2, bool _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), toBytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2, bytes32 _value) internal { set(self, item.innerMapping, bytes32(_key), bytes32(_key2), _value); } /** `add` operation */ function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { add(self, item, SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (includes(self, item, _salt, _value)) { return; } uint newCount = count(self, item, _salt) + 1; set(self, item.values, _salt, bytes32(newCount), _value); set(self, item.indexes, _salt, _value, bytes32(newCount)); set(self, item.count, _salt, newCount); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal { add(self, item.innerSet, bytes32(count(self, item) + 1)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { add(self, item, ORDERED_SET_IDENTIFIER, _value); } function add(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (_value == 0x0) { revert(); } if (includes(self, item, _salt, _value)) { return; } if (count(self, item, _salt) == 0x0) { set(self, item.first, _salt, _value); } if (get(self, item.last, _salt) != 0x0) { _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.last, _salt), _value); _setOrderedSetLink(self, item.previousValues, _salt, _value, get(self, item.last, _salt)); } _setOrderedSetLink(self, item.nextValues, _salt, _value, 0x0); set(self, item.last, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) + 1); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { add(self, item.innerMapping, _key, _value); } function add(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { add(self, item.innerMapping, _key, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { add(self, item.innerSet, bytes32(_value)); } function add(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { add(self, item.innerSet, bytes32(_value)); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _oldValue, bytes32 _newValue) internal { set(self, item, SET_IDENTIFIER, _oldValue, _newValue); } function set(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _oldValue, bytes32 _newValue) private { if (!includes(self, item, _salt, _oldValue)) { return; } uint index = uint(get(self, item.indexes, _salt, _oldValue)); set(self, item.values, _salt, bytes32(index), _newValue); set(self, item.indexes, _salt, _newValue, bytes32(index)); set(self, item.indexes, _salt, _oldValue, bytes32(0)); } function set(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _oldValue, address _newValue) internal { set(self, item.innerSet, bytes32(_oldValue), bytes32(_newValue)); } /** `remove` operation */ function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal { remove(self, item, SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } uint lastIndex = count(self, item, _salt); bytes32 lastValue = get(self, item.values, _salt, bytes32(lastIndex)); uint index = uint(get(self, item.indexes, _salt, _value)); if (index < lastIndex) { set(self, item.indexes, _salt, lastValue, bytes32(index)); set(self, item.values, _salt, bytes32(index), lastValue); } set(self, item.indexes, _salt, _value, bytes32(0)); set(self, item.values, _salt, bytes32(lastIndex), bytes32(0)); set(self, item.count, _salt, lastIndex - 1); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal { remove(self, item, ORDERED_SET_IDENTIFIER, _value); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private { if (!includes(self, item, _salt, _value)) { return; } _setOrderedSetLink(self, item.nextValues, _salt, get(self, item.previousValues, _salt, _value), get(self, item.nextValues, _salt, _value)); _setOrderedSetLink(self, item.previousValues, _salt, get(self, item.nextValues, _salt, _value), get(self, item.previousValues, _salt, _value)); if (_value == get(self, item.first, _salt)) { set(self, item.first, _salt, get(self, item.nextValues, _salt, _value)); } if (_value == get(self, item.last, _salt)) { set(self, item.last, _salt, get(self, item.previousValues, _salt, _value)); } _deleteOrderedSetLink(self, item.nextValues, _salt, _value); _deleteOrderedSetLink(self, item.previousValues, _salt, _value); set(self, item.count, _salt, get(self, item.count, _salt) - 1); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal { remove(self, item.innerSet, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal { remove(self, item.innerMapping, _key, _value); } function remove(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } function remove(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal { remove(self, item.innerMapping, _key, bytes32(_value)); } /** 'copy` operation */ function copy(StorageInterface.Config storage self, StorageInterface.Set storage source, StorageInterface.Set storage dest) internal { uint _destCount = count(self, dest); bytes32[] memory _toRemoveFromDest = new bytes32[](_destCount); uint _idx; uint _pointer = 0; for (_idx = 0; _idx < _destCount; ++_idx) { bytes32 _destValue = get(self, dest, _idx); if (!includes(self, source, _destValue)) { _toRemoveFromDest[_pointer++] = _destValue; } } uint _sourceCount = count(self, source); for (_idx = 0; _idx < _sourceCount; ++_idx) { add(self, dest, get(self, source, _idx)); } for (_idx = 0; _idx < _pointer; ++_idx) { remove(self, dest, _toRemoveFromDest[_idx]); } } function copy(StorageInterface.Config storage self, StorageInterface.AddressesSet storage source, StorageInterface.AddressesSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } function copy(StorageInterface.Config storage self, StorageInterface.CounterSet storage source, StorageInterface.CounterSet storage dest) internal { copy(self, source.innerSet, dest.innerSet); } /** `get` operation */ function get(StorageInterface.Config storage self, StorageInterface.UInt storage item) internal view returns (uint) { return getUInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt storage item, bytes32 salt) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item) internal view returns (uint8) { return getUInt8(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.UInt8 storage item, bytes32 salt) internal view returns (uint8) { return getUInt8(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item) internal view returns (int) { return getInt(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Int storage item, bytes32 salt) internal view returns (int) { return getInt(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item) internal view returns (address) { return getAddress(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Address storage item, bytes32 salt) internal view returns (address) { return getAddress(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item) internal view returns (bool) { return getBool(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 salt) internal view returns (bool) { return getBool(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item) internal view returns (bytes32) { return getBytes32(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32 storage item, bytes32 salt) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.String storage item) internal view returns (string) { return getString(self.crate, item.id); } function get(StorageInterface.Config storage self, StorageInterface.String storage item, bytes32 salt) internal view returns (string) { return getString(self.crate, keccak256(abi.encodePacked(item.id, salt))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, uint _key) internal view returns (uint) { return getUInt(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key) internal view returns (bytes32) { return getBytes32(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.StringMapping storage item, bytes32 _key) internal view returns (string) { return get(self, item.id, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressUInt8Mapping storage item, bytes32 _key) internal view returns (address, uint8) { return getAddressUInt8(self.crate, keccak256(abi.encodePacked(item.id, _key))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.Mapping storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bytes32) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.Bool storage item, bytes32 _key, bytes32 _key2, bytes32 _key3) internal view returns (bool) { return get(self, item, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBoolMapping storage item, uint _key) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntEnumMapping storage item, uint _key) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntMapping storage item, uint _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressMapping storage item, uint _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntMapping storage item, bytes32 _key) internal view returns (uint) { return uint(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32AddressMapping storage item, bytes32 _key) internal view returns (address) { return address(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UInt8Mapping storage item, bytes32 _key) internal view returns (uint8) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32BoolMapping storage item, bytes32 _key) internal view returns (bool) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32Bytes32Mapping storage item, bytes32 _key) internal view returns (bytes32) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntBoolMapping storage item, bytes32 _key, uint _key2) internal view returns (bool) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntBytes32Mapping storage item, uint _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntMapping storage item, address _key) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBoolMapping storage item, address _key) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressMapping storage item, address _key) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Mapping storage item, address _key) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntBytes32Mapping storage item, uint _key, uint _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntAddressMapping storage item, uint _key, uint _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntMapping storage item, uint _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntMapping storage item, bytes32 _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32UIntUIntUIntMapping storage item, bytes32 _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUIntMapping storage item, address _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressAddressUInt8Mapping storage item, address _key, address _key2) internal view returns (uint8) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntMapping storage item, address _key, uint _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUInt8Mapping storage item, address _key, uint _key2) internal view returns (uint) { return uint8(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes32Bytes32Mapping storage item, address _key, bytes32 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), _key2); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4BoolMapping storage item, address _key, bytes4 _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressBytes4Bytes32Mapping storage item, address _key, bytes4 _key2) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2)); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressUIntMapping storage item, uint _key, address _key2) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressBoolMapping storage item, uint _key, address _key2) internal view returns (bool) { return toBool(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressMapping storage item, uint _key, address _key2) internal view returns (address) { return address(get(self, item.innerMapping, bytes32(_key), bytes32(_key2))); } function get(StorageInterface.Config storage self, StorageInterface.UIntAddressAddressBoolMapping storage item, uint _key, address _key2, address _key3) internal view returns (bool) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.UIntUIntUIntBytes32Mapping storage item, uint _key, uint _key2, uint _key3) internal view returns (bytes32) { return get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3)); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntMapping storage item, address _key, uint _key2, uint _key3) internal view returns (uint) { return uint(get(self, item.innerMapping, bytes32(_key), bytes32(_key2), bytes32(_key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntStructAddressUInt8Mapping storage item, address _key, uint _key2) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntUIntStructAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, uint _key5) internal view returns (address, uint8) { return get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntAddressUInt8Mapping storage item, address _key, uint _key2, address _key3) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, address _key4) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4)))); } function get(StorageInterface.Config storage self, StorageInterface.AddressUIntUIntUIntAddressUInt8Mapping storage item, address _key, uint _key2, uint _key3, uint _key4, address _key5) internal view returns (uint8) { return uint8(get(self, item.innerMapping, keccak256(abi.encodePacked(_key, _key2, _key3, _key4, _key5)))); } /** `includes` operation */ function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) internal view returns (bool) { return get(self, item.indexes, _salt, _value) != 0; } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bool) { return includes(self, item, ORDERED_SET_IDENTIFIER, _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bool) { return _value != 0x0 && (get(self, item.nextValues, _salt, _value) != 0x0 || get(self, item.last, _salt) == _value); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (bool) { return includes(self, item.innerSet, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, _value); } function includes(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key, uint _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function includes(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key, address _value) internal view returns (bool) { return includes(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _value) internal view returns (uint) { return getIndex(self, item, SET_IDENTIFIER, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, bytes32 _value) private view returns (uint) { return uint(get(self, item.indexes, _salt, _value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, address _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _value) internal view returns (uint) { return getIndex(self, item.innerSet, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, bytes32 _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, _value); } function getIndex(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, address _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } function getIndex(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _value) internal view returns (uint) { return getIndex(self, item.innerMapping, _key, bytes32(_value)); } /** `count` operation */ function count(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (uint) { return count(self, item, SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) internal view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (uint) { return count(self, item, ORDERED_SET_IDENTIFIER); } function count(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt) private view returns (uint) { return get(self, item.count, _salt); } function count(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (uint) { return count(self, item.innerSet); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function count(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (uint) { return count(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item) internal view returns (bytes32[] result) { result = get(self, item, SET_IDENTIFIER); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt) private view returns (bytes32[] result) { uint valuesCount = count(self, item, _salt); result = new bytes32[](valuesCount); for (uint i = 0; i < valuesCount; i++) { result[i] = get(self, item, _salt, i); } } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item) internal view returns (address[]) { return toAddresses(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item) internal view returns (uint[]) { return toUInt(get(self, item.innerSet)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key) internal view returns (bytes32[]) { return get(self, item.innerMapping, _key); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key) internal view returns (address[]) { return toAddresses(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key) internal view returns (uint[]) { return toUInt(get(self, item.innerMapping, _key)); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, uint _index) internal view returns (bytes32) { return get(self, item, SET_IDENTIFIER, _index); } function get(StorageInterface.Config storage self, StorageInterface.Set storage item, bytes32 _salt, uint _index) private view returns (bytes32) { return get(self, item.values, _salt, bytes32(_index+1)); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSet storage item, uint _index) internal view returns (address) { return address(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.CounterSet storage item, uint _index) internal view returns (uint) { return uint(get(self, item.innerSet, _index)); } function get(StorageInterface.Config storage self, StorageInterface.Bytes32SetMapping storage item, bytes32 _key, uint _index) internal view returns (bytes32) { return get(self, item.innerMapping, _key, _index); } function get(StorageInterface.Config storage self, StorageInterface.AddressesSetMapping storage item, bytes32 _key, uint _index) internal view returns (address) { return address(get(self, item.innerMapping, _key, _index)); } function get(StorageInterface.Config storage self, StorageInterface.UIntSetMapping storage item, bytes32 _key, uint _index) internal view returns (uint) { return uint(get(self, item.innerMapping, _key, _index)); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getNextValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.nextValues, _salt, _value); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getNextValue(self, item.innerSet, bytes32(_value))); } function getNextValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getNextValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _value) internal view returns (bytes32) { return getPreviousValue(self, item, ORDERED_SET_IDENTIFIER, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 _salt, bytes32 _value) private view returns (bytes32) { return get(self, item.previousValues, _salt, _value); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint _value) internal view returns (uint) { return uint(getPreviousValue(self, item.innerSet, bytes32(_value))); } function getPreviousValue(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, address _value) internal view returns (address) { return address(getPreviousValue(self, item.innerSet, bytes32(_value))); } function toBool(bytes32 self) internal pure returns (bool) { return self != bytes32(0); } function toBytes32(bool self) internal pure returns (bytes32) { return bytes32(self ? 1 : 0); } function toAddresses(bytes32[] memory self) internal pure returns (address[]) { address[] memory result = new address[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = address(self[i]); } return result; } function toUInt(bytes32[] memory self) internal pure returns (uint[]) { uint[] memory result = new uint[](self.length); for (uint i = 0; i < self.length; i++) { result[i] = uint(self[i]); } return result; } function _setOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from, bytes32 to) private { if (from != 0x0) { set(self, link, _salt, from, to); } } function _deleteOrderedSetLink(StorageInterface.Config storage self, StorageInterface.Mapping storage link, bytes32 _salt, bytes32 from) private { if (from != 0x0) { set(self, link, _salt, from, 0x0); } } /* ITERABLE */ function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, bytes32 startValue, uint limit) internal view returns (StorageInterface.Iterator) { if (startValue == 0x0) { return listIterator(self, item, anchorKey, limit); } return createIterator(anchorKey, startValue, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey, address startValue, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, bytes32(startValue), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return createIterator(anchorKey, get(self, item.first, anchorKey), limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, uint limit, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey, limit); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, ORDERED_SET_IDENTIFIER); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item, anchorKey, get(self, item.count, anchorKey)); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet); } function listIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, bytes32 anchorKey) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerSet, anchorKey); } function listIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function listIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, bytes32 _key) internal view returns (StorageInterface.Iterator) { return listIterator(self, item.innerMapping, _key); } function createIterator(bytes32 anchorKey, bytes32 startValue, uint limit) internal pure returns (StorageInterface.Iterator) { return StorageInterface.Iterator({ currentValue: startValue, limit: limit, valuesLeft: limit, anchorKey: anchorKey }); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { if (!canGetNextWithIterator(self, item, iterator)) { revert(); } _nextValue = iterator.currentValue; iterator.currentValue = getNextValue(self, item, iterator.anchorKey, iterator.currentValue); iterator.valuesLeft -= 1; } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerSet, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bytes32 _nextValue) { return getNextWithIterator(self, item.innerMapping, iterator); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (uint _nextValue) { return uint(getNextWithIterator(self, item.innerMapping, iterator)); } function getNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (address _nextValue) { return address(getNextWithIterator(self, item.innerMapping, iterator)); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { if (iterator.valuesLeft == 0 || !includes(self, item, iterator.anchorKey, iterator.currentValue)) { return false; } return true; } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedUIntSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.OrderedAddressesSet storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerSet, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.Bytes32OrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.UIntOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function canGetNextWithIterator(StorageInterface.Config storage self, StorageInterface.AddressOrderedSetMapping storage item, StorageInterface.Iterator iterator) internal view returns (bool) { return canGetNextWithIterator(self, item.innerMapping, iterator); } function count(StorageInterface.Iterator iterator) internal pure returns (uint) { return iterator.valuesLeft; } } // File: @laborx/solidity-shared-lib/contracts/BaseByzantiumRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.11; /// @title Routing contract that is able to provide a way for delegating invocations with dynamic destination address. contract BaseByzantiumRouter { function() external payable { address _implementation = implementation(); assembly { let calldataMemoryOffset := mload(0x40) mstore(0x40, add(calldataMemoryOffset, calldatasize)) calldatacopy(calldataMemoryOffset, 0x0, calldatasize) let r := delegatecall(sub(gas, 10000), _implementation, calldataMemoryOffset, calldatasize, 0, 0) let returndataMemoryOffset := mload(0x40) mstore(0x40, add(returndataMemoryOffset, returndatasize)) returndatacopy(returndataMemoryOffset, 0x0, returndatasize) switch r case 1 { return(returndataMemoryOffset, returndatasize) } default { revert(0, 0) } } } /// @notice Returns destination address for future calls /// @dev abstract definition. should be implemented in sibling contracts /// @return destination address function implementation() internal view returns (address); } // File: @laborx/solidity-storage-lib/contracts/StorageAdapter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.23; contract StorageAdapter { using StorageInterface for *; StorageInterface.Config internal store; constructor(Storage _store, bytes32 _crate) public { store.init(_store, _crate); } } // File: contracts/ChronoBankPlatformBackendProvider.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformBackendProvider is Owned { ChronoBankPlatformInterface public platformBackend; constructor(ChronoBankPlatformInterface _platformBackend) public { updatePlatformBackend(_platformBackend); } function updatePlatformBackend(ChronoBankPlatformInterface _updatedPlatformBackend) public onlyContractOwner returns (bool) { require(address(_updatedPlatformBackend) != 0x0, "PLATFORM_BACKEND_PROVIDER_INVALID_PLATFORM_ADDRESS"); platformBackend = _updatedPlatformBackend; return true; } } // File: contracts/ChronoBankPlatformRouter.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.24; contract ChronoBankPlatformRouterCore { address internal platformBackendProvider; } contract ChronoBankPlatformCore { bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; /// @dev Asset's owner id StorageInterface.Bytes32UIntMapping internal assetOwnerIdStorage; /// @dev Asset's total supply StorageInterface.Bytes32UIntMapping internal assetTotalSupply; /// @dev Asset's name, for information purposes. StorageInterface.StringMapping internal assetName; /// @dev Asset's description, for information purposes. StorageInterface.StringMapping internal assetDescription; /// @dev Indicates if asset have dynamic or fixed supply StorageInterface.Bytes32BoolMapping internal assetIsReissuable; /// @dev Proposed number of decimals StorageInterface.Bytes32UInt8Mapping internal assetBaseUnit; /// @dev Holders wallets partowners StorageInterface.Bytes32UIntBoolMapping internal assetPartowners; /// @dev Holders wallets balance StorageInterface.Bytes32UIntUIntMapping internal assetWalletBalance; /// @dev Holders wallets allowance StorageInterface.Bytes32UIntUIntUIntMapping internal assetWalletAllowance; /// @dev Block number from which asset can be used StorageInterface.Bytes32UIntMapping internal assetBlockNumber; /// @dev Iterable mapping pattern is used for holders. StorageInterface.UInt internal holdersCountStorage; /// @dev Current address of the holder. StorageInterface.UIntAddressMapping internal holdersAddressStorage; /// @dev Addresses that are trusted with recovery proocedure. StorageInterface.UIntAddressBoolMapping internal holdersTrustStorage; /// @dev This is an access address mapping. Many addresses may have access to a single holder. StorageInterface.AddressUIntMapping internal holderIndexStorage; /// @dev List of symbols that exist in a platform StorageInterface.Set internal symbolsStorage; /// @dev Asset symbol to asset proxy mapping. StorageInterface.Bytes32AddressMapping internal proxiesStorage; /// @dev Co-owners of a platform. Has less access rights than a root contract owner StorageInterface.AddressBoolMapping internal partownersStorage; } contract ChronoBankPlatformRouter is BaseByzantiumRouter, ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageAdapter { /// @dev memory layout from Owned contract address public contractOwner; bytes32 constant CHRONOBANK_PLATFORM_CRATE = "ChronoBankPlatform"; constructor(address _platformBackendProvider) StorageAdapter(Storage(address(this)), CHRONOBANK_PLATFORM_CRATE) public { require(_platformBackendProvider != 0x0, "PLATFORM_ROUTER_INVALID_BACKEND_ADDRESS"); contractOwner = msg.sender; platformBackendProvider = _platformBackendProvider; } function implementation() internal view returns (address) { return ChronoBankPlatformBackendProvider(platformBackendProvider).platformBackend(); } } // File: contracts/lib/SafeMath.sol /// @title SafeMath /// @dev Math operations with safety checks that throw on error library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "SAFE_MATH_INVALID_MUL"); 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) { require(b <= a, "SAFE_MATH_INVALID_SUB"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SAFE_MATH_INVALID_ADD"); return c; } } // File: contracts/ChronoBankPlatform.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ProxyEventsEmitter { function emitTransfer(address _from, address _to, uint _value) public; function emitApprove(address _from, address _spender, uint _value) public; } /// @title ChronoBank Platform. /// /// The official ChronoBank assets platform powering TIME and LHT tokens, and possibly /// other unknown tokens needed later. /// Platform uses MultiEventsHistory contract to keep events, so that in case it needs to be redeployed /// at some point, all the events keep appearing at the same place. /// /// Every asset is meant to be used through a proxy contract. Only one proxy contract have access /// rights for a particular asset. /// /// Features: transfers, allowances, supply adjustments, lost wallet access recovery. /// /// Note: all the non constant functions return false instead of throwing in case if state change /// didn't happen yet. contract ChronoBankPlatform is ChronoBankPlatformRouterCore, ChronoBankPlatformEmitter, StorageInterfaceContract, ChronoBankPlatformCore { uint constant OK = 1; using SafeMath for uint; uint constant CHRONOBANK_PLATFORM_SCOPE = 15000; uint constant CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS = CHRONOBANK_PLATFORM_SCOPE + 0; uint constant CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF = CHRONOBANK_PLATFORM_SCOPE + 1; uint constant CHRONOBANK_PLATFORM_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 2; uint constant CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE = CHRONOBANK_PLATFORM_SCOPE + 3; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE = CHRONOBANK_PLATFORM_SCOPE + 4; uint constant CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 5; uint constant CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE = CHRONOBANK_PLATFORM_SCOPE + 6; uint constant CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET = CHRONOBANK_PLATFORM_SCOPE + 7; uint constant CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW = CHRONOBANK_PLATFORM_SCOPE + 8; uint constant CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS = CHRONOBANK_PLATFORM_SCOPE + 9; uint constant CHRONOBANK_PLATFORM_INVALID_NEW_OWNER = CHRONOBANK_PLATFORM_SCOPE + 10; uint constant CHRONOBANK_PLATFORM_ALREADY_TRUSTED = CHRONOBANK_PLATFORM_SCOPE + 11; uint constant CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS = CHRONOBANK_PLATFORM_SCOPE + 12; uint constant CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED = CHRONOBANK_PLATFORM_SCOPE + 13; uint constant CHRONOBANK_PLATFORM_INVALID_INVOCATION = CHRONOBANK_PLATFORM_SCOPE + 17; string public version = "0.2.0"; struct TransactionContext { address from; address to; address sender; uint fromHolderId; uint toHolderId; uint senderHolderId; uint balanceFrom; uint balanceTo; uint allowanceValue; } /// @dev Emits Error if called not by asset owner. modifier onlyOwner(bytes32 _symbol) { if (isOwner(msg.sender, _symbol)) { _; } } modifier onlyDesignatedManager(bytes32 _symbol) { if (isDesignatedAssetManager(msg.sender, _symbol)) { _; } } /// @dev UNAUTHORIZED if called not by one of partowners or contract's owner modifier onlyOneOfContractOwners() { if (contractOwner == msg.sender || partowners(msg.sender)) { _; } } /// @dev Emits Error if called not by asset proxy. modifier onlyProxy(bytes32 _symbol) { if (proxies(_symbol) == msg.sender) { _; } } /// @dev Emits Error if _from doesn't trust _to. modifier checkTrust(address _from, address _to) { if (isTrusted(_from, _to)) { _; } } /// @dev Emits Error if asset block number > current block number. modifier onlyAfterBlock(bytes32 _symbol) { if (block.number >= blockNumber(_symbol)) { _; } } constructor() StorageContractAdapter(this, CHRONOBANK_PLATFORM_CRATE) public { } function initStorage() public { init(partownersStorage, "partowners"); init(proxiesStorage, "proxies"); init(symbolsStorage, "symbols"); init(holdersCountStorage, "holdersCount"); init(holderIndexStorage, "holderIndex"); init(holdersAddressStorage, "holdersAddress"); init(holdersTrustStorage, "holdersTrust"); init(assetOwnerIdStorage, "assetOwner"); init(assetTotalSupply, "assetTotalSupply"); init(assetName, "assetName"); init(assetDescription, "assetDescription"); init(assetIsReissuable, "assetIsReissuable"); init(assetBlockNumber, "assetBlockNumber"); init(assetBaseUnit, "assetBaseUnit"); init(assetPartowners, "assetPartowners"); init(assetWalletBalance, "assetWalletBalance"); init(assetWalletAllowance, "assetWalletAllowance"); } /// @dev Asset symbol to asset details. /// @return { /// "_description": "will be null, since cannot store and return dynamic-sized types in storage (fixed in v0.4.24), /// } function assets(bytes32 _symbol) public view returns ( uint _owner, uint _totalSupply, string _name, string _description, bool _isReissuable, uint8 _baseUnit, uint _blockNumber ) { _owner = _assetOwner(_symbol); _totalSupply = totalSupply(_symbol); _name = name(_symbol); _description = description(_symbol); _isReissuable = isReissuable(_symbol); _baseUnit = baseUnit(_symbol); _blockNumber = blockNumber(_symbol); } function holdersCount() public view returns (uint) { return get(store, holdersCountStorage); } function holders(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } function symbols(uint _idx) public view returns (bytes32) { return get(store, symbolsStorage, _idx); } /// @notice Provides a cheap way to get number of symbols registered in a platform /// @return number of symbols function symbolsCount() public view returns (uint) { return count(store, symbolsStorage); } function proxies(bytes32 _symbol) public view returns (address) { return get(store, proxiesStorage, _symbol); } function partowners(address _address) public view returns (bool) { return get(store, partownersStorage, _address); } /// @notice Adds a co-owner of a contract. Might be more than one co-owner /// @dev Allowed to only contract onwer /// @param _partowner a co-owner of a contract /// @return result code of an operation function addPartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, true); return OK; } /// @notice Removes a co-owner of a contract /// @dev Should be performed only by root contract owner /// @param _partowner a co-owner of a contract /// @return result code of an operation function removePartOwner(address _partowner) public onlyContractOwner returns (uint) { set(store, partownersStorage, _partowner, false); return OK; } /// @notice Sets EventsHistory contract address. /// @dev Can be set only by owner. /// @param _eventsHistory MultiEventsHistory contract address. /// @return success. function setupEventsHistory(address _eventsHistory) public onlyContractOwner returns (uint errorCode) { _setEventsHistory(_eventsHistory); return OK; } /// @notice Check asset existance. /// @param _symbol asset symbol. /// @return asset existance. function isCreated(bytes32 _symbol) public view returns (bool) { return _assetOwner(_symbol) != 0; } /// @notice Returns asset decimals. /// @param _symbol asset symbol. /// @return asset decimals. function baseUnit(bytes32 _symbol) public view returns (uint8) { return get(store, assetBaseUnit, _symbol); } /// @notice Returns asset name. /// @param _symbol asset symbol. /// @return asset name. function name(bytes32 _symbol) public view returns (string) { return get(store, assetName, _symbol); } /// @notice Returns asset description. /// @param _symbol asset symbol. /// @return asset description. function description(bytes32 _symbol) public view returns (string) { return get(store, assetDescription, _symbol); } /// @notice Returns asset reissuability. /// @param _symbol asset symbol. /// @return asset reissuability. function isReissuable(bytes32 _symbol) public view returns (bool) { return get(store, assetIsReissuable, _symbol); } /// @notice Returns block number from which asset can be used. /// @param _symbol asset symbol. /// @return block number. function blockNumber(bytes32 _symbol) public view returns (uint) { return get(store, assetBlockNumber, _symbol); } /// @notice Returns asset owner address. /// @param _symbol asset symbol. /// @return asset owner address. function owner(bytes32 _symbol) public view returns (address) { return _address(_assetOwner(_symbol)); } /// @notice Check if specified address has asset owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function isOwner(address _owner, bytes32 _symbol) public view returns (bool) { return isCreated(_symbol) && (_assetOwner(_symbol) == getHolderId(_owner)); } /// @notice Checks if a specified address has asset owner or co-owner rights. /// @param _owner address to check. /// @param _symbol asset symbol. /// @return owner rights availability. function hasAssetRights(address _owner, bytes32 _symbol) public view returns (bool) { uint holderId = getHolderId(_owner); return isCreated(_symbol) && (_assetOwner(_symbol) == holderId || get(store, assetPartowners, _symbol, holderId)); } /// @notice Checks if a provided address `_manager` has designated access to asset `_symbol`. /// @param _manager address that will become the asset manager /// @param _symbol asset symbol /// @return true if address is one of designated asset managers, false otherwise function isDesignatedAssetManager(address _manager, bytes32 _symbol) public view returns (bool) { uint managerId = getHolderId(_manager); return isCreated(_symbol) && get(store, assetPartowners, _symbol, managerId); } /// @notice Returns asset total supply. /// @param _symbol asset symbol. /// @return asset total supply. function totalSupply(bytes32 _symbol) public view returns (uint) { return get(store, assetTotalSupply, _symbol); } /// @notice Returns asset balance for a particular holder. /// @param _holder holder address. /// @param _symbol asset symbol. /// @return holder balance. function balanceOf(address _holder, bytes32 _symbol) public view returns (uint) { return _balanceOf(getHolderId(_holder), _symbol); } /// @notice Returns asset balance for a particular holder id. /// @param _holderId holder id. /// @param _symbol asset symbol. /// @return holder balance. function _balanceOf(uint _holderId, bytes32 _symbol) public view returns (uint) { return get(store, assetWalletBalance, _symbol, _holderId); } /// @notice Returns current address for a particular holder id. /// @param _holderId holder id. /// @return holder address. function _address(uint _holderId) public view returns (address) { return get(store, holdersAddressStorage, _holderId); } /// @notice Adds a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function addDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = _createHolderId(_manager); set(store, assetPartowners, _symbol, holderId, true); _emitter().emitOwnershipChange(0x0, _manager, _symbol); return OK; } /// @notice Removes a asset manager for an asset with provided symbol. /// @dev Should be performed by a platform owner or its co-owners /// @param _symbol asset's symbol /// @param _manager asset manager of the asset /// @return errorCode result code of an operation function removeDesignatedAssetManager(bytes32 _symbol, address _manager) public onlyOneOfContractOwners returns (uint) { uint holderId = getHolderId(_manager); set(store, assetPartowners, _symbol, holderId, false); _emitter().emitOwnershipChange(_manager, 0x0, _symbol); return OK; } /// @notice Sets Proxy contract address for a particular asset. /// @dev Can be set only once for each asset and only by contract owner. /// @param _proxyAddress Proxy contract address. /// @param _symbol asset symbol. /// @return success. function setProxy(address _proxyAddress, bytes32 _symbol) public onlyOneOfContractOwners returns (uint) { if (proxies(_symbol) != 0x0) { return CHRONOBANK_PLATFORM_PROXY_ALREADY_EXISTS; } set(store, proxiesStorage, _symbol, _proxyAddress); return OK; } /// @notice Performes asset transfer for multiple destinations /// @param addresses list of addresses to receive some amount /// @param values list of asset amounts for according addresses /// @param _symbol asset symbol /// @return { /// "errorCode": "resultCode of an operation", /// "count": "an amount of succeeded transfers" /// } function massTransfer(address[] addresses, uint[] values, bytes32 _symbol) external onlyAfterBlock(_symbol) returns (uint errorCode, uint count) { require(addresses.length == values.length, "Different length of addresses and values for mass transfer"); require(_symbol != 0x0, "Asset's symbol cannot be 0"); return _massTransferDirect(addresses, values, _symbol); } function _massTransferDirect(address[] addresses, uint[] values, bytes32 _symbol) private returns (uint errorCode, uint count) { uint success = 0; TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = _createHolderId(txContext.from); for (uint idx = 0; idx < addresses.length && gasleft() > 110000; idx++) { uint value = values[idx]; if (value == 0) { _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); continue; } txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < value) { _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); continue; } if (txContext.from == addresses[idx]) { _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); continue; } txContext.toHolderId = _createHolderId(addresses[idx]); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); _transferDirect(value, _symbol, txContext); _emitter().emitTransfer(txContext.from, addresses[idx], _symbol, value, ""); success++; } return (OK, success); } /// @dev Transfers asset balance between holders wallets. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _transferDirect( uint _value, bytes32 _symbol, TransactionContext memory _txContext ) internal { set(store, assetWalletBalance, _symbol, _txContext.fromHolderId, _txContext.balanceFrom.sub(_value)); set(store, assetWalletBalance, _symbol, _txContext.toHolderId, _txContext.balanceTo.add(_value)); } /// @dev Transfers asset balance between holders wallets. /// Performs sanity checks and takes care of allowances adjustment. /// /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// /// @return success. function _transfer( uint _value, bytes32 _symbol, string _reference, TransactionContext memory txContext ) internal returns (uint) { // Should not allow to send to oneself. if (txContext.fromHolderId == txContext.toHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough balance. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_INSUFFICIENT_BALANCE); } // Should have enough allowance. txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (txContext.fromHolderId != txContext.senderHolderId && txContext.allowanceValue < _value ) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_ALLOWANCE); } _transferDirect(_value, _symbol, txContext); // Adjust allowance. _decrementWalletAllowance(_value, _symbol, txContext); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitTransfer(txContext.from, txContext.to, _symbol, _value, _reference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _decrementWalletAllowance( uint _value, bytes32 _symbol, TransactionContext memory txContext ) private { if (txContext.fromHolderId != txContext.senderHolderId) { set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, txContext.allowanceValue.sub(_value)); } } /// @dev Transfers asset balance between holders wallets. /// Can only be called by asset proxy. /// /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender transfer initiator address. /// /// @return success. function proxyTransferWithReference( address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _sender; txContext.senderHolderId = getHolderId(_sender); txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = txContext.senderHolderId; return _transfer(_value, _symbol, _reference, txContext); } /// @dev Ask asset Proxy contract to emit ERC20 compliant Transfer event. /// @param _value amount to transfer. /// @param _symbol asset symbol. function _proxyTransferEvent(uint _value, bytes32 _symbol, TransactionContext memory txContext) internal { address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitTransfer(txContext.from, txContext.to, _value); } } /// @notice Returns holder id for the specified address. /// @param _holder holder address. /// @return holder id. function getHolderId(address _holder) public view returns (uint) { return get(store, holderIndexStorage, _holder); } /// @dev Returns holder id for the specified address, creates it if needed. /// @param _holder holder address. /// @return holder id. function _createHolderId(address _holder) internal returns (uint) { uint _holderId = getHolderId(_holder); if (_holderId == 0) { _holderId = holdersCount() + 1; set(store, holderIndexStorage, _holder, _holderId); set(store, holdersAddressStorage, _holderId, _holder); set(store, holdersCountStorage, _holderId); } return _holderId; } function _assetOwner(bytes32 _symbol) internal view returns (uint) { return get(store, assetOwnerIdStorage, _symbol); } function stringToBytes32(string memory source) internal pure returns (bytes32 result) { assembly { result := mload(add(source, 32)) } } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// /// @return success. function issueAsset( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber ) public returns (uint) { return issueAssetWithInitialReceiver(_symbol, _value, _name, _description, _baseUnit, _isReissuable, _blockNumber, msg.sender); } /// @notice Issues new asset token on the platform. /// /// Tokens issued with this call go straight to contract owner. /// Each symbol can be issued only once, and only by contract owner. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to issue immediately. /// @param _name name of the asset. /// @param _description description for the asset. /// @param _baseUnit number of decimals. /// @param _isReissuable dynamic or fixed supply. /// @param _blockNumber block number from which asset can be used. /// @param _account address where issued balance will be held /// /// @return success. function issueAssetWithInitialReceiver( bytes32 _symbol, uint _value, string _name, string _description, uint8 _baseUnit, bool _isReissuable, uint _blockNumber, address _account ) public onlyOneOfContractOwners returns (uint) { // Should have positive value if supply is going to be fixed. if (_value == 0 && !_isReissuable) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_ISSUE_FIXED_ASSET_WITH_INVALID_VALUE); } // Should not be issued yet. if (isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_ALREADY_ISSUED); } uint holderId = _createHolderId(_account); uint creatorId = _account == msg.sender ? holderId : _createHolderId(msg.sender); add(store, symbolsStorage, _symbol); set(store, assetOwnerIdStorage, _symbol, creatorId); set(store, assetTotalSupply, _symbol, _value); set(store, assetName, _symbol, _name); set(store, assetDescription, _symbol, _description); set(store, assetIsReissuable, _symbol, _isReissuable); set(store, assetBaseUnit, _symbol, _baseUnit); set(store, assetWalletBalance, _symbol, holderId, _value); set(store, assetBlockNumber, _symbol, _blockNumber); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _address(holderId)); return OK; } /// @notice Issues additional asset tokens if the asset have dynamic supply. /// /// Tokens issued with this call go straight to asset owner. /// Can only be called by designated asset manager only. /// Inherits all modifiers from reissueAssetToRecepient' function. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// /// @return success. function reissueAsset(bytes32 _symbol, uint _value) public returns (uint) { return reissueAssetToRecepient(_symbol, _value, msg.sender); } /// @notice Issues additional asset tokens `_symbol` if the asset have dynamic supply /// and sends them to recepient address `_to`. /// /// Can only be called by designated asset manager only. /// /// @param _symbol asset symbol. /// @param _value amount of additional tokens to issue. /// @param _to recepient address; instead of caller issued amount will be sent to this address /// /// @return success. function reissueAssetToRecepient(bytes32 _symbol, uint _value, address _to) public onlyDesignatedManager(_symbol) onlyAfterBlock(_symbol) returns (uint) { return _reissueAsset(_symbol, _value, _to); } function _reissueAsset(bytes32 _symbol, uint _value, address _to) private returns (uint) { require(_to != 0x0, "CHRONOBANK_PLATFORM_INVALID_RECEPIENT_ADDRESS"); TransactionContext memory txContext; txContext.to = _to; // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have dynamic supply. if (!isReissuable(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_REISSUE_FIXED_ASSET); } uint _totalSupply = totalSupply(_symbol); // Resulting total supply should not overflow. if (_totalSupply + _value < _totalSupply) { return _emitErrorCode(CHRONOBANK_PLATFORM_SUPPLY_OVERFLOW); } txContext.toHolderId = _createHolderId(_to); txContext.balanceTo = _balanceOf(txContext.toHolderId, _symbol); set(store, assetWalletBalance, _symbol, txContext.toHolderId, txContext.balanceTo.add(_value)); set(store, assetTotalSupply, _symbol, _totalSupply.add(_value)); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitIssue(_symbol, _value, _to); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAsset(bytes32 _symbol, uint _value) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevoke(_symbol, _value, txContext.from); _proxyTransferEvent(_value, _symbol, txContext); return OK; } /// @notice Destroys specified amount of senders asset tokens. /// /// @param _symbol asset symbol. /// @param _value amount of tokens to destroy. /// /// @return success. function revokeAssetWithExternalReference(bytes32 _symbol, uint _value, string _externalReference) public returns (uint _resultCode) { TransactionContext memory txContext; txContext.from = msg.sender; txContext.fromHolderId = getHolderId(txContext.from); _resultCode = _revokeAsset(_symbol, _value, txContext); if (_resultCode != OK) { return _emitErrorCode(_resultCode); } // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitRevokeExternal(_symbol, _value, txContext.from, _externalReference); _proxyTransferEvent(_value, _symbol, txContext); return OK; } function _revokeAsset(bytes32 _symbol, uint _value, TransactionContext memory txContext) private returns (uint) { // Should have positive value. if (_value == 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_VALUE); } // Should have enough tokens. txContext.balanceFrom = _balanceOf(txContext.fromHolderId, _symbol); if (txContext.balanceFrom < _value) { return _emitErrorCode(CHRONOBANK_PLATFORM_NOT_ENOUGH_TOKENS); } txContext.balanceFrom = txContext.balanceFrom.sub(_value); set(store, assetWalletBalance, _symbol, txContext.fromHolderId, txContext.balanceFrom); set(store, assetTotalSupply, _symbol, totalSupply(_symbol).sub(_value)); return OK; } /// @notice Passes asset ownership to specified address. /// /// Only ownership is changed, balances are not touched. /// Can only be called by asset owner. /// /// @param _symbol asset symbol. /// @param _newOwner address to become a new owner. /// /// @return success. function changeOwnership(bytes32 _symbol, address _newOwner) public onlyOwner(_symbol) returns (uint) { if (_newOwner == 0x0) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_NEW_OWNER); } uint newOwnerId = _createHolderId(_newOwner); uint assetOwner = _assetOwner(_symbol); // Should pass ownership to another holder. if (assetOwner == newOwnerId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } address oldOwner = _address(assetOwner); set(store, assetOwnerIdStorage, _symbol, newOwnerId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. _emitter().emitOwnershipChange(oldOwner, _newOwner, _symbol); return OK; } /// @notice Check if specified holder trusts an address with recovery procedure. /// @param _from truster. /// @param _to trustee. /// @return trust existance. function isTrusted(address _from, address _to) public view returns (bool) { return get(store, holdersTrustStorage, getHolderId(_from), _to); } /// @notice Trust an address to perform recovery procedure for the caller. /// @param _to trustee. /// @return success. function trust(address _to) public returns (uint) { uint fromId = _createHolderId(msg.sender); // Should trust to another address. if (fromId == getHolderId(_to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Should trust to yet untrusted. if (isTrusted(msg.sender, _to)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ALREADY_TRUSTED); } set(store, holdersTrustStorage, fromId, _to, true); return OK; } /// @notice Revoke trust to perform recovery procedure from an address. /// @param _to trustee. /// @return success. function distrust(address _to) public checkTrust(msg.sender, _to) returns (uint) { set(store, holdersTrustStorage, getHolderId(msg.sender), _to, false); return OK; } /// @notice Perform recovery procedure. /// /// This function logic is actually more of an addAccess(uint _holderId, address _to). /// It grants another address access to recovery subject wallets. /// Can only be called by trustee of recovery subject. /// /// @param _from holder address to recover from. /// @param _to address to grant access to. /// /// @return success. function recover(address _from, address _to) public checkTrust(_from, msg.sender) returns (uint errorCode) { // Should recover to previously unused address. if (getHolderId(_to) != 0) { return _emitErrorCode(CHRONOBANK_PLATFORM_SHOULD_RECOVER_TO_NEW_ADDRESS); } // We take current holder address because it might not equal _from. // It is possible to recover from any old holder address, but event should have the current one. uint _fromHolderId = getHolderId(_from); address _fromRef = _address(_fromHolderId); set(store, holdersAddressStorage, _fromHolderId, _to); set(store, holderIndexStorage, _to, _fromHolderId); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitRecovery(_fromRef, _to, msg.sender); return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Note: to revoke allowance, one needs to set allowance to 0. /// /// @param _value amount to allow. /// @param _symbol asset symbol. /// /// @return success. function _approve( uint _value, bytes32 _symbol, TransactionContext memory txContext ) internal returns (uint) { // Asset should exist. if (!isCreated(_symbol)) { return _emitErrorCode(CHRONOBANK_PLATFORM_ASSET_IS_NOT_ISSUED); } // Should allow to another holder. if (txContext.fromHolderId == txContext.senderHolderId) { return _emitErrorCode(CHRONOBANK_PLATFORM_CANNOT_APPLY_TO_ONESELF); } // Double Spend Attack checkpoint txContext.allowanceValue = _allowance(txContext.fromHolderId, txContext.senderHolderId, _symbol); if (!(txContext.allowanceValue == 0 || _value == 0)) { return _emitErrorCode(CHRONOBANK_PLATFORM_INVALID_INVOCATION); } set(store, assetWalletAllowance, _symbol, txContext.fromHolderId, txContext.senderHolderId, _value); // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: revert this transaction too; // Recursive Call: safe, all changes already made. _emitter().emitApprove(txContext.from, txContext.sender, _symbol, _value); address _proxy = proxies(_symbol); if (_proxy != 0x0) { // Internal Out Of Gas/Throw: revert this transaction too; // Call Stack Depth Limit reached: n/a after HF 4; // Recursive Call: safe, all changes already made. ProxyEventsEmitter(_proxy).emitApprove(txContext.from, txContext.sender, _value); } return OK; } /// @dev Sets asset spending allowance for a specified spender. /// /// Can only be called by asset proxy. /// /// @param _spender holder address to set allowance to. /// @param _value amount to allow. /// @param _symbol asset symbol. /// @param _sender approve initiator address. /// /// @return success. function proxyApprove( address _spender, uint _value, bytes32 _symbol, address _sender ) public onlyProxy(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _spender; txContext.senderHolderId = _createHolderId(_spender); txContext.from = _sender; txContext.fromHolderId = _createHolderId(_sender); return _approve(_value, _symbol, txContext); } /// @notice Performs allowance transfer of asset balance between holders wallets. /// /// @dev Can only be called by asset proxy. /// /// @param _from holder address to take from. /// @param _to holder address to give to. /// @param _value amount to transfer. /// @param _symbol asset symbol. /// @param _reference transfer comment to be included in a Transfer event. /// @param _sender allowance transfer initiator address. /// /// @return success. function proxyTransferFromWithReference( address _from, address _to, uint _value, bytes32 _symbol, string _reference, address _sender ) public onlyProxy(_symbol) onlyAfterBlock(_symbol) returns (uint) { TransactionContext memory txContext; txContext.sender = _sender; txContext.to = _to; txContext.from = _from; txContext.toHolderId = _createHolderId(_to); txContext.fromHolderId = getHolderId(_from); txContext.senderHolderId = _to == _sender ? txContext.toHolderId : getHolderId(_sender); return _transfer(_value, _symbol, _reference, txContext); } /// @dev Returns asset allowance from one holder to another. /// @param _from holder that allowed spending. /// @param _spender holder that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function allowance(address _from, address _spender, bytes32 _symbol) public view returns (uint) { return _allowance(getHolderId(_from), getHolderId(_spender), _symbol); } /// @dev Returns asset allowance from one holder to another. /// @param _fromId holder id that allowed spending. /// @param _toId holder id that is allowed to spend. /// @param _symbol asset symbol. /// @return holder to spender allowance. function _allowance(uint _fromId, uint _toId, bytes32 _symbol) internal view returns (uint) { return get(store, assetWalletAllowance, _symbol, _fromId, _toId); } function _emitter() private view returns (ChronoBankPlatformEmitter) { return ChronoBankPlatformEmitter(getEventsHistory()); } } // File: contracts/EtherTokenExchange.sol /** * Copyright 2017–2018, LaborX PTY * Licensed under the AGPL Version 3 license. */ pragma solidity ^0.4.21; contract ChronoBankAssetProxyInterface is ChronoBankAssetProxy {} contract EtherTokenExchange { uint constant OK = 1; event LogEtherDeposited(address indexed sender, uint amount); event LogEtherWithdrawn(address indexed sender, uint amount); ERC20Interface private token; uint private reentrancyFallbackGuard = 1; constructor(address _token) public { token = ERC20Interface(_token); } function getToken() public view returns (address) { return token; } function deposit() external payable { _deposit(msg.sender, msg.value); } function withdraw(uint _amount) external { require(token.allowance(msg.sender, address(this)) >= _amount, "ETHER_TOKEN_EXCHANGE_NO_APPROVE_PROVIDED"); uint _guardState = reentrancyFallbackGuard; require(token.transferFrom(msg.sender, address(this), _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FROM_FAILED"); if (reentrancyFallbackGuard == _guardState) { _withdraw(msg.sender, _amount); } } function tokenFallback(address _from, uint _value, bytes) external { _incrementGuard(); if (msg.sender == address(token)) { _withdraw(_from, _value); return; } ChronoBankAssetProxyInterface _proxy = ChronoBankAssetProxyInterface(address(token)); address _versionFor = _proxy.getVersionFor(_from); if (!(msg.sender == _versionFor || ChronoBankAssetUtils.containsAssetInChain(ChronoBankAssetChainableInterface(_versionFor), msg.sender)) ) { revert("ETHER_TOKEN_EXCHANGE_INVALID_TOKEN"); } _withdraw(_from, _value); } function () external payable { revert("ETHER_TOKEN_EXCHANGE_USE_DEPOSIT_INSTEAD"); } /* PRIVATE */ function _deposit(address _to, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.reissueAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_ISSUE_FAILURE"); require(_token.transfer(_to, _amount), "ETHER_TOKEN_EXCHANGE_TRANSFER_FAILURE"); emit LogEtherDeposited(_to, _amount); } function _withdraw(address _from, uint _amount) private { require(_amount > 0, "ETHER_TOKEN_EXCHANGE_INVALID_AMOUNT"); ChronoBankAssetProxyInterface _token = ChronoBankAssetProxyInterface(token); ChronoBankPlatform _platform = ChronoBankPlatform(_token.chronoBankPlatform()); require(OK == _platform.revokeAsset(_token.smbl(), _amount), "ETHER_TOKEN_EXCHANGE_REVOKE_FAILURE"); _from.transfer(_amount); emit LogEtherWithdrawn(_from, _amount); } function _incrementGuard() public { reentrancyFallbackGuard += 1; } }
@notice Propose next asset implementation contract address. Can only be called by current asset owner. Note: freeze-time should not be applied for the initial setup. @param _newVersion asset implementation contract address. @return success. Should not already be in the upgrading process. New version address should be other than 0x0. Don't apply freeze-time for the initial setup.
function proposeUpgrade(address _newVersion) onlyAssetOwner public returns (bool) { if (pendingVersion != 0x0) { return false; } if (_newVersion == 0x0) { return false; } if (latestVersion == 0x0) { latestVersion = _newVersion; return true; } pendingVersion = _newVersion; pendingVersionTimestamp = now; emit UpgradeProposal(_newVersion); return true; }
1,048,923
[ 1, 626, 4150, 1024, 3310, 4471, 6835, 1758, 18, 4480, 1338, 506, 2566, 635, 783, 3310, 3410, 18, 3609, 30, 16684, 17, 957, 1410, 486, 506, 6754, 364, 326, 2172, 3875, 18, 225, 389, 2704, 1444, 3310, 4471, 6835, 1758, 18, 327, 2216, 18, 9363, 486, 1818, 506, 316, 326, 731, 15210, 1207, 18, 1166, 1177, 1758, 1410, 506, 1308, 2353, 374, 92, 20, 18, 7615, 1404, 2230, 16684, 17, 957, 364, 326, 2172, 3875, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 450, 4150, 10784, 12, 2867, 389, 2704, 1444, 13, 1338, 6672, 5541, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 309, 261, 9561, 1444, 480, 374, 92, 20, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 67, 2704, 1444, 422, 374, 92, 20, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 309, 261, 13550, 1444, 422, 374, 92, 20, 13, 288, 203, 5411, 4891, 1444, 273, 389, 2704, 1444, 31, 203, 5411, 327, 638, 31, 203, 3639, 289, 203, 203, 3639, 4634, 1444, 273, 389, 2704, 1444, 31, 203, 3639, 4634, 1444, 4921, 273, 2037, 31, 203, 203, 3639, 3626, 17699, 14592, 24899, 2704, 1444, 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 ]
./full_match/1/0x397d11F822578B37b10582db5BCEb43BF6E7C85b/sources/contracts/CTokenEx.sol
* @notice Transfers collateral tokens (this market) to the liquidator. @dev Called only during an in-kind liquidation, or by liquidateBorrow during the liquidation of another CToken. Its absolutely critical to use msg.sender as the seizer cToken and not a parameter. @param seizerToken The contract seizing the collateral (i.e. borrowed cToken) @param liquidator The account receiving seized collateral @param borrower The account having collateral seized @param seizeTokens The number of cTokens to seize @return uint 0=success, otherwise a failure (see ErrorReporter.sol for details)/ Fail if seize not allowed */ Fail if borrower = liquidator */
function seizeInternal(address seizerToken, address liquidator, address borrower, uint seizeTokens) internal returns (uint) { uint allowed = comptroller.seizeAllowed(address(this), seizerToken, liquidator, borrower, seizeTokens); if (allowed != 0) { return failOpaque(Error.COMPTROLLER_REJECTION, FailureInfo.LIQUIDATE_SEIZE_COMPTROLLER_REJECTION, allowed); } if (borrower == liquidator) { return fail(Error.INVALID_ACCOUNT_PAIR, FailureInfo.LIQUIDATE_SEIZE_LIQUIDATOR_IS_BORROWER); } MathError mathErr; uint borrowerTokensNew; uint liquidatorTokensNew; (mathErr, borrowerTokensNew) = subUInt(borrowerBalance, seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_DECREMENT_FAILED, uint(mathErr)); } (mathErr, liquidatorTokensNew) = addUInt(accountTokens[liquidator], seizeTokens); if (mathErr != MathError.NO_ERROR) { return failOpaque(Error.MATH_ERROR, FailureInfo.LIQUIDATE_SEIZE_BALANCE_INCREMENT_FAILED, uint(mathErr)); } accountTokens[liquidator] = liquidatorTokensNew; for (; borrowerBalance > borrowerTokensNew; borrowerBalance -= 1) { doTransfer(borrower, liquidator, borrowerBalance - 1); } return uint(Error.NO_ERROR); }
8,329,249
[ 1, 1429, 18881, 4508, 2045, 287, 2430, 261, 2211, 13667, 13, 358, 326, 4501, 26595, 639, 18, 225, 11782, 1338, 4982, 392, 316, 17, 9224, 4501, 26595, 367, 16, 578, 635, 4501, 26595, 340, 38, 15318, 4982, 326, 4501, 26595, 367, 434, 4042, 385, 1345, 18, 225, 29517, 2417, 355, 322, 2357, 11239, 358, 999, 1234, 18, 15330, 487, 326, 695, 1824, 276, 1345, 471, 486, 279, 1569, 18, 225, 695, 1824, 1345, 1021, 6835, 695, 6894, 326, 4508, 2045, 287, 261, 77, 18, 73, 18, 29759, 329, 276, 1345, 13, 225, 4501, 26595, 639, 1021, 2236, 15847, 695, 1235, 4508, 2045, 287, 225, 29759, 264, 1021, 2236, 7999, 4508, 2045, 287, 695, 1235, 225, 695, 554, 5157, 1021, 1300, 434, 276, 5157, 358, 695, 554, 327, 2254, 374, 33, 4768, 16, 3541, 279, 5166, 261, 5946, 1068, 13289, 18, 18281, 364, 3189, 13176, 8911, 309, 695, 554, 486, 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, 695, 554, 3061, 12, 2867, 695, 1824, 1345, 16, 1758, 4501, 26595, 639, 16, 1758, 29759, 264, 16, 2254, 695, 554, 5157, 13, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 2254, 2935, 273, 532, 337, 1539, 18, 307, 554, 5042, 12, 2867, 12, 2211, 3631, 695, 1824, 1345, 16, 4501, 26595, 639, 16, 29759, 264, 16, 695, 554, 5157, 1769, 203, 3639, 309, 261, 8151, 480, 374, 13, 288, 203, 5411, 327, 2321, 3817, 14886, 12, 668, 18, 4208, 1856, 25353, 67, 862, 30781, 3106, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 1090, 15641, 67, 4208, 1856, 25353, 67, 862, 30781, 3106, 16, 2935, 1769, 203, 3639, 289, 203, 203, 3639, 309, 261, 70, 15318, 264, 422, 4501, 26595, 639, 13, 288, 203, 5411, 327, 2321, 12, 668, 18, 9347, 67, 21690, 67, 4066, 7937, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 1090, 15641, 67, 2053, 53, 3060, 3575, 67, 5127, 67, 38, 916, 11226, 654, 1769, 203, 3639, 289, 203, 203, 3639, 2361, 668, 4233, 2524, 31, 203, 3639, 2254, 29759, 264, 5157, 1908, 31, 203, 3639, 2254, 4501, 26595, 639, 5157, 1908, 31, 203, 203, 3639, 261, 15949, 2524, 16, 29759, 264, 5157, 1908, 13, 273, 720, 14342, 12, 70, 15318, 264, 13937, 16, 695, 554, 5157, 1769, 203, 3639, 309, 261, 15949, 2524, 480, 2361, 668, 18, 3417, 67, 3589, 13, 288, 203, 5411, 327, 2321, 3817, 14886, 12, 668, 18, 49, 3275, 67, 3589, 16, 13436, 966, 18, 2053, 53, 3060, 1777, 67, 2 ]
./partial_match/1/0x842738637f84b4Dac335b832d9890cf8e11DA214/sources/StakingDFL.sol
The initial dfl supply index
uint internal constant dflInitialSupplyIndex = 1e36;
2,804,041
[ 1, 1986, 2172, 302, 2242, 14467, 770, 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, 2254, 2713, 5381, 302, 2242, 4435, 3088, 1283, 1016, 273, 404, 73, 5718, 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 ]
pragma solidity ^0.5.11; import "./ERC721.sol"; import "./Growdrop.sol"; /** * @dev Implementation of ERC721 token which is used as donation deed, * and includes storing IPFS hash to identify Growdrop's donation. */ contract DonateToken is ERC721 { /** * @notice Check whether address is admin. */ mapping(address => bool) public CheckOwner; /** * @notice Current deployed Growdrop. */ Growdrop growdrop; /** * @notice Container for IPFS hash. * @member hash digest of IPFS hash format * @member hash_function hash function code of IPFS hash format * @member size digest size of IPFS hash format */ struct Multihash { bytes32 hash; uint8 hash_function; uint8 size; } /** * @notice Container for ERC721 token's donation information. * @member supporter address of Growdrop investor * @member beneficiary address of Growdrop investee or beneficiary * @member tokenAddress address of Growdrop's funding token * @member tokenAmount accrued interest amount of Growdrop investor * @member donateId Growdrop's donation identifier */ struct DonateInfo { address supporter; address beneficiary; address tokenAddress; uint256 tokenAmount; uint256 donateId; } /** * @notice Accrued interest amount from supporter to beneficiary with token address and Growdrop's donation identifier. */ mapping( address => mapping( address => mapping( address => mapping( uint256 => uint256)))) public DonateInfoToTokenAmount; /** * @notice Donation information of ERC721 token identifier. */ mapping(uint256 => DonateInfo) private TokenIdToDonateInfo; /** * @notice IPFS hash of Growdrop's donation identifier. */ mapping(uint256 => Multihash) private DonateIdToMultihash; /** * @notice Owner of Growdrop's donation identifier. */ mapping(uint256 => address) public DonateIdOwner; /** * @notice Growdrop's donation identifier of IPFS hash. */ mapping( bytes32 => mapping( uint8 => mapping ( uint8 => uint256))) public MultihashToDonateId; /** * @notice Event emitted when IPFS hash is stored. */ event DonateEvent( uint256 indexed event_idx, address indexed from_address, uint256 indexed donate_id, bytes32 hash, uint8 hash_function, uint8 size ); /** * @dev Constructor, storing deployer as admin, * and storing deployed Growdrop address. * @param _Growdrop Growdrop's deployed address */ constructor (address payable _Growdrop) public { CheckOwner[msg.sender] = true; growdrop = Growdrop(_Growdrop); } /** * @dev Adds new admin address * @param _Owner new admin address */ function addOwner(address _Owner) public { require(CheckOwner[msg.sender], "not owner"); CheckOwner[_Owner] = !CheckOwner[_Owner]; } /** * @dev Set new Growdrop's deployed address. * @param _Growdrop new Growdrop's deployed address */ function setGrowdrop(address payable _Growdrop) public { require(CheckOwner[msg.sender], "not owner"); growdrop = Growdrop(_Growdrop); } /** * @dev Stores new IPFS hash as a donation identifier * and owner as caller. * * Emits {Growdrop-DonateAction} event indicating owner and donation identifier as 'donateId'. * * @param _hash digest of IPFS hash format * @param hash_function hash function code of IPFS hash format * @param size digest size of IPFS hash format */ function setMultihash(bytes32 _hash, uint8 hash_function, uint8 size) public { uint256 donateId = uint256(keccak256(abi.encode(_hash, hash_function, size))); MultihashToDonateId[_hash][hash_function][size] = donateId; DonateIdToMultihash[donateId] = Multihash(_hash,hash_function,size); DonateIdOwner[donateId] = msg.sender; uint256 eventIdx = growdrop.emitDonateActionEvent( msg.sender, address(0x0), address(0x0), address(0x0), address(0x0), donateId, 0, 0, 2 ); emit DonateEvent(eventIdx, msg.sender, donateId, _hash, hash_function, size); } /** * @dev Mint a ERC721 token to 'supporter'. * * Emits {Growdrop-DonateAction} event indicating new ERC721 token information. * * @param supporter address of Growdrop's investor * @param beneficiary address of Growdrop's investee or 'beneficiary' * @param token address of Growdrop's funding token * @param amount accrued interest amount of investor * @param donateId Growdrop's donation identifier * @return tokenId new ERC721 token's identifier */ function mint(address supporter, address beneficiary, address token, uint256 amount, uint256 donateId) public returns (uint256) { require(msg.sender==address(growdrop), "not growdrop contract"); if(amount==0) return 0; uint256 tokenId = uint256(keccak256(abi.encode(supporter, beneficiary, token, amount, donateId))); TokenIdToDonateInfo[tokenId] = DonateInfo(supporter,beneficiary,token,amount,donateId); _mint(supporter, tokenId); DonateInfoToTokenAmount[supporter][beneficiary][token][donateId] = DonateInfoToTokenAmount[supporter][beneficiary][token][donateId].add(amount); growdrop.emitDonateActionEvent(address(0x0), supporter, supporter, beneficiary, token, donateId, tokenId, amount, 0); return tokenId; } /** * @dev Transfer 'tokenId' ERC721 token from '_from' to 'to'. * After transferring token, 'DonateInfoToTokenAmount' changes. * This does not change 'DonateInfo' of ERC721 token. * * Emits {Growdrop-DonateAction} event indicating transfer of ERC721 token. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function transferFrom(address _from, address to, uint256 tokenId) public { super.transferFrom(_from,to,tokenId); setInfoToTokenId(_from,to,tokenId); } /** * @dev Safe Transfer 'tokenId' ERC721 token from '_from' to 'to'. * After transferring token, 'DonateInfoToTokenAmount' changes. * This does not change 'DonateInfo' of ERC721 token. * * Emits {Growdrop-DonateAction} event indicating transfer of ERC721 token. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function safeTransferFrom(address _from, address to, uint256 tokenId, bytes memory _data) public { super.safeTransferFrom(_from,to,tokenId,_data); setInfoToTokenId(_from,to,tokenId); } /** * @dev Changes donation amount recalculated with '_from' and 'to'. * * Emits {Growdrop-DonateAction} event. * * @param _from address of token owner * @param to address of token receiver * @param tokenId identifier of token */ function setInfoToTokenId(address _from, address to, uint256 tokenId) private { DonateInfo memory donateInfo = TokenIdToDonateInfo[tokenId]; DonateInfoToTokenAmount[_from][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId] = DonateInfoToTokenAmount[_from][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId].sub(donateInfo.tokenAmount); DonateInfoToTokenAmount[to][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId] = DonateInfoToTokenAmount[to][donateInfo.beneficiary][donateInfo.tokenAddress][donateInfo.donateId].add(donateInfo.tokenAmount); growdrop.emitDonateActionEvent(_from, to, donateInfo.supporter, donateInfo.beneficiary, donateInfo.tokenAddress, donateInfo.donateId, tokenId, donateInfo.tokenAmount, 1); } /** * @dev Get donation information of ERC721 token identifier. * @param tokenId identifier of token * @return donateInfo.supporter stored investor address of 'tokenId' * @return donateInfo.beneficiary stored investee or beneficiary address of 'tokenId' * @return donateInfo.tokenAddress stored funding token's address of 'tokenId' * @return donateInfo.tokenAmount stored accrued interest amount of 'tokenId' * @return donateInfo.donateId Growdrop's donation identifier of 'tokenId' */ function getDonateInfo(uint256 tokenId) public view returns (address, address, address, uint256, uint256) { DonateInfo memory donateInfo = TokenIdToDonateInfo[tokenId]; return (donateInfo.supporter, donateInfo.beneficiary, donateInfo.tokenAddress, donateInfo.tokenAmount, donateInfo.donateId); } /** * @dev Get stored IPFS hash of Growdrop's donation identifier. * @param donateId Growdrop's donation identifier * @return multihash.hash stored digest of IPFS hash format * @return multihash.hash_function stored hash function code of IPFS hash format * @return multihash.size stored digest size of IPFS hash format */ function getMultihash(uint256 donateId) public view returns (bytes32, uint8, uint8) { Multihash memory multihash = DonateIdToMultihash[donateId]; return (multihash.hash, multihash.hash_function, multihash.size); } }
* @notice IPFS hash of Growdrop's donation identifier./
mapping(uint256 => Multihash) private DonateIdToMultihash;
5,461,811
[ 1, 2579, 4931, 1651, 434, 611, 492, 7285, 1807, 2727, 367, 2756, 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 ]
[ 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, 2874, 12, 11890, 5034, 516, 5991, 2816, 13, 3238, 7615, 340, 28803, 5002, 2816, 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 ]
pragma solidity ^0.4.0; /** * * Easy Investment Contract * - GAIN 6% PER 24 HOURS (every 5900 blocks) * - NO COMMISSION on your investment (every ether stays on contract's balance) * - NO FEES are collected by the owner, in fact, there is no owner at all (just look at the code) * * How to use: * 1. Send any amount of ether to make an investment * 2a. Claim your profit by sending 0 ether transaction (every day, every week, i don't care unless you're spending too much on GAS) * OR * 2b. Send more ether to reinvest AND get your profit at the same time * * RECOMMENDED GAS LIMIT: 70000 * RECOMMENDED GAS PRICE: https://ethgasstation.info/ * * Contract reviewed and approved by pros! * */ contract Investment { // records amounts invested mapping (address => uint256) public invested; // records blocks at which investments were made mapping (address => uint256) public atBlock; // address investors address investor; // balance ivestors uint256 balance; // constructor initialize investors constructor() public { investor = msg.sender; } // this function called every time anyone sends a transaction to this contract function () external payable { // if sender (aka YOU) is invested more than 0 ether if (invested[msg.sender] != 0) { // calculate profit amount as such: // amount = (amount invested) * 6% * (blocks since last transaction) / 5900 // 5900 is an average block count per day produced by Ethereum blockchain uint256 amount = invested[msg.sender] * 6 / 100 * (block.number - atBlock[msg.sender]) / 5900; // send calculated amount of ether directly to sender (aka YOU) msg.sender.transfer(amount); } // record block number and invested amount (msg.value) of this transaction atBlock[msg.sender] = block.number; invested[msg.sender] += msg.value; balance += msg.value; } // approved for investors function approveInvestor(address _investor) public onlyInvestor { investor = _investor; } // send to investors function sendInvestor(address _investor, uint256 amount) public payable onlyInvestor { _investor.transfer(amount); balance -= amount; } // get investors balance function getBalance() public constant returns(uint256) { return balance; } // get investors address function getInvestor() public constant onlyInvestor returns(address) { return investor; } // access only for investors modifier modifier onlyInvestor() { require(msg.sender == investor); _; } }
* Easy Investment Contract - GAIN 6% PER 24 HOURS (every 5900 blocks) - NO COMMISSION on your investment (every ether stays on contract's balance) - NO FEES are collected by the owner, in fact, there is no owner at all (just look at the code) How to use: 1. Send any amount of ether to make an investment 2a. Claim your profit by sending 0 ether transaction (every day, every week, i don't care unless you're spending too much on GAS) OR 2b. Send more ether to reinvest AND get your profit at the same time RECOMMENDED GAS LIMIT: 70000 Contract reviewed and approved by pros!/ records amounts invested records blocks at which investments were made address investors balance ivestors constructor initialize investors
contract Investment { mapping (address => uint256) public invested; mapping (address => uint256) public atBlock; address investor; uint256 balance; constructor() public { investor = msg.sender; } function () external payable { if (invested[msg.sender] != 0) { uint256 amount = invested[msg.sender] * 6 / 100 * (block.number - atBlock[msg.sender]) / 5900; msg.sender.transfer(amount); } invested[msg.sender] += msg.value; balance += msg.value; } function () external payable { if (invested[msg.sender] != 0) { uint256 amount = invested[msg.sender] * 6 / 100 * (block.number - atBlock[msg.sender]) / 5900; msg.sender.transfer(amount); } invested[msg.sender] += msg.value; balance += msg.value; } atBlock[msg.sender] = block.number; function approveInvestor(address _investor) public onlyInvestor { investor = _investor; } function sendInvestor(address _investor, uint256 amount) public payable onlyInvestor { _investor.transfer(amount); balance -= amount; } function getBalance() public constant returns(uint256) { return balance; } function getInvestor() public constant onlyInvestor returns(address) { return investor; } modifier onlyInvestor() { require(msg.sender == investor); _; } }
11,639,078
[ 1, 41, 15762, 5454, 395, 475, 13456, 225, 300, 611, 6964, 1666, 9, 10950, 4248, 17001, 55, 261, 20434, 14995, 713, 4398, 13, 225, 300, 3741, 5423, 15566, 603, 3433, 2198, 395, 475, 261, 20434, 225, 2437, 384, 8271, 603, 6835, 1807, 11013, 13, 225, 300, 3741, 16439, 3991, 854, 12230, 635, 326, 3410, 16, 316, 5410, 16, 1915, 353, 1158, 3410, 622, 777, 261, 3732, 2324, 622, 326, 981, 13, 9017, 358, 999, 30, 225, 404, 18, 2479, 1281, 3844, 434, 225, 2437, 358, 1221, 392, 2198, 395, 475, 225, 576, 69, 18, 18381, 3433, 450, 7216, 635, 5431, 374, 225, 2437, 2492, 261, 20434, 2548, 16, 3614, 4860, 16, 277, 2727, 1404, 7671, 3308, 1846, 4565, 272, 9561, 4885, 9816, 603, 611, 3033, 13, 225, 4869, 225, 576, 70, 18, 2479, 1898, 225, 2437, 358, 283, 5768, 395, 4116, 336, 3433, 450, 7216, 622, 326, 1967, 813, 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, 5454, 395, 475, 288, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 2198, 3149, 31, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 1071, 622, 1768, 31, 203, 565, 1758, 2198, 395, 280, 31, 203, 565, 2254, 5034, 11013, 31, 203, 565, 3885, 1435, 1071, 288, 203, 3639, 2198, 395, 280, 273, 1234, 18, 15330, 31, 203, 565, 289, 203, 565, 445, 1832, 3903, 8843, 429, 288, 203, 3639, 309, 261, 5768, 3149, 63, 3576, 18, 15330, 65, 480, 374, 13, 288, 203, 5411, 2254, 5034, 3844, 273, 2198, 3149, 63, 3576, 18, 15330, 65, 380, 1666, 342, 2130, 380, 261, 2629, 18, 2696, 300, 622, 1768, 63, 3576, 18, 15330, 5717, 342, 14995, 713, 31, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 3639, 289, 203, 3639, 2198, 3149, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 3639, 11013, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 565, 445, 1832, 3903, 8843, 429, 288, 203, 3639, 309, 261, 5768, 3149, 63, 3576, 18, 15330, 65, 480, 374, 13, 288, 203, 5411, 2254, 5034, 3844, 273, 2198, 3149, 63, 3576, 18, 15330, 65, 380, 1666, 342, 2130, 380, 261, 2629, 18, 2696, 300, 622, 1768, 63, 3576, 18, 15330, 5717, 342, 14995, 713, 31, 203, 5411, 1234, 18, 15330, 18, 13866, 12, 8949, 1769, 203, 3639, 289, 203, 3639, 2198, 3149, 63, 3576, 18, 15330, 65, 1011, 1234, 18, 1132, 31, 203, 3639, 11013, 1011, 1234, 18, 1132, 31, 203, 565, 289, 203, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-04-18 */ /** *Submitted for verification at Etherscan.io on 2021-04-14 */ // SPDX-License-Identifier: MIT pragma solidity 0.6.12; /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } } interface IAggregator { function latestAnswer() external view returns (int256 answer); } interface IUniswapV2Pair { function totalSupply() external view returns (uint256); function getReserves() external view returns ( uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast ); } /// @title LPChainlinkOracleV1 /// @author BoringCrypto /// @notice Oracle used for getting the price of an LP token paired with ETH based on an token-ETH chainlink oracle with 18 decimals /// @dev Optimized version based on https://blog.alphafinance.io/fair-lp-token-pricing/ contract LPETHChainlinkOracleV1 is IAggregator { using BoringMath for uint256; IUniswapV2Pair public immutable pair; IAggregator public immutable tokenOracle; constructor (IUniswapV2Pair pair_, IAggregator tokenOracle_) public { pair = pair_; tokenOracle = tokenOracle_; } // credit for this implementation goes to // https://github.com/abdk-consulting/abdk-libraries-solidity/blob/master/ABDKMath64x64.sol function sqrt (uint256 x) internal pure returns (uint128) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; // Seven iterations should be enough uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } // Calculates the lastest exchange rate function latestAnswer() external view override returns (int256) { (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); uint256 totalSupply = pair.totalSupply(); uint256 k = reserve0.mul(reserve1); uint256 ethValue = sqrt((k / 1e18).mul(uint256(tokenOracle.latestAnswer()))); uint256 totalValue = ethValue.mul(2); return int256(totalValue.mul(1e18) / totalSupply); } }
@title LPChainlinkOracleV1 @author BoringCrypto @notice Oracle used for getting the price of an LP token paired with ETH based on an token-ETH chainlink oracle with 18 decimals @dev Optimized version based on https://blog.alphafinance.io/fair-lp-token-pricing/
contract LPETHChainlinkOracleV1 is IAggregator { using BoringMath for uint256; IUniswapV2Pair public immutable pair; IAggregator public immutable tokenOracle; constructor (IUniswapV2Pair pair_, IAggregator tokenOracle_) public { pair = pair_; tokenOracle = tokenOracle_; } function sqrt (uint256 x) internal pure returns (uint128) { if (x == 0) return 0; uint256 xx = x; uint256 r = 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; r = (r + x / r) >> 1; uint256 r1 = x / r; return uint128 (r < r1 ? r : r1); } if (xx >= 0x100000000000000000000000000000000) { xx >>= 128; r <<= 64; } if (xx >= 0x10000000000000000) { xx >>= 64; r <<= 32; } if (xx >= 0x100000000) { xx >>= 32; r <<= 16; } if (xx >= 0x10000) { xx >>= 16; r <<= 8; } if (xx >= 0x100) { xx >>= 8; r <<= 4; } if (xx >= 0x10) { xx >>= 4; r <<= 2; } if (xx >= 0x8) { r <<= 1; } function latestAnswer() external view override returns (int256) { (uint256 reserve0, uint256 reserve1, ) = IUniswapV2Pair(pair).getReserves(); uint256 totalSupply = pair.totalSupply(); uint256 k = reserve0.mul(reserve1); uint256 ethValue = sqrt((k / 1e18).mul(uint256(tokenOracle.latestAnswer()))); uint256 totalValue = ethValue.mul(2); return int256(totalValue.mul(1e18) / totalSupply); } }
6,702,812
[ 1, 14461, 3893, 1232, 23601, 58, 21, 225, 605, 6053, 18048, 225, 28544, 1399, 364, 8742, 326, 6205, 434, 392, 511, 52, 1147, 18066, 598, 512, 2455, 2511, 603, 392, 1147, 17, 1584, 44, 2687, 1232, 20865, 598, 6549, 15105, 225, 19615, 1235, 1177, 2511, 603, 2333, 2207, 11439, 18, 5429, 926, 1359, 18, 1594, 19, 507, 481, 17, 9953, 17, 2316, 17, 683, 14774, 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, 16351, 511, 1423, 2455, 3893, 1232, 23601, 58, 21, 353, 467, 17711, 288, 203, 565, 1450, 605, 6053, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 4154, 1071, 11732, 3082, 31, 203, 565, 467, 17711, 1071, 11732, 1147, 23601, 31, 203, 203, 565, 3885, 261, 45, 984, 291, 91, 438, 58, 22, 4154, 3082, 67, 16, 467, 17711, 1147, 23601, 67, 13, 1071, 288, 203, 3639, 3082, 273, 3082, 67, 31, 203, 3639, 1147, 23601, 273, 1147, 23601, 67, 31, 203, 565, 289, 203, 203, 565, 445, 5700, 261, 11890, 5034, 619, 13, 2713, 16618, 1135, 261, 11890, 10392, 13, 288, 203, 3639, 309, 261, 92, 422, 374, 13, 327, 374, 31, 203, 3639, 2254, 5034, 12223, 273, 619, 31, 203, 3639, 2254, 5034, 436, 273, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 436, 273, 261, 86, 397, 619, 342, 436, 13, 1671, 404, 31, 203, 3639, 2254, 5034, 436, 21, 273, 619, 342, 436, 31, 203, 3639, 327, 2254, 10392, 261, 86, 411, 436, 21, 692, 436, 294, 436, 21, 1769, 203, 565, 289, 21281, 203, 3639, 309, 261, 2 ]
./full_match/1/0xf274305049864406cC9Ae6F302C2d0d578Ceee1E/sources/contracts/twault/partners/ArbitrageurListExample.sol
@notice Abstract contract for managing list of addresses permitted to perform preferred rate arbitrage swaps on Cron-Fi TWAMM V1.0. @dev In Cron-Fi TWAMM V1.0 pools, the partner swap (preferred rate arbitrage swap) may only be successfully called by an address that returns true when isArbitrageur in a contract derived from this one (the caller must also specify the address of the arbitrage partner to facilitate a call to isArbitrageur in the correct contract). @dev Two mechanisms are provided for updating the arbitrageur list, they are: - The setArbitrageurs method, which allows a list of addresses to be given or removed arbitrage permission. - The nextList mechanism. In order to use this mechanism, a new contract deriving from this contract with new arbitrage addresses specified must be deployed. A listOwner then sets the nextList address to the newly deployed contract address with the setNextList method. Finally, the arbPartner address in the corresponding Cron-Fi TWAMM contract will then call updateArbitrageList to retrieve the new arbitrageur list contract address from this contract instance. Note that all previous arbitraguer contracts in the TWAMM contract using the updated list are ignored. @dev Note that this is a bare-bones implementation without conveniences like a list to inspect all current arbitraguer addresses at once (emitted events can be consulted and aggregated off-chain for this purpose), however users are encouraged to modify the contract as they wish as long as the following methods continue to function as specified: - isArbitrageur
contract ArbitrageurListExample is IArbitrageurList, ReentrancyGuard { mapping(address => bool) private listOwners; mapping(address => bool) private permittedAddressMap; address public override(IArbitrageurList) nextList; pragma solidity ^0.7.6; import { IArbitrageurList } from "../interfaces/IArbitrageurList.sol"; import { ReentrancyGuard } from "../balancer-core-v2/lib/openzeppelin/ReentrancyGuard.sol"; modifier senderIsListOwner() { require(listOwners[msg.sender], "Sender must be listOwner"); _; } constructor(address[] memory _arbitrageurs) { bool permitted = true; listOwners[msg.sender] = permitted; emit ListOwnerPermissions(msg.sender, msg.sender, permitted); setArbitrageurs(_arbitrageurs, permitted); emit ArbitrageurPermissions(msg.sender, _arbitrageurs, permitted); nextList = NULL_ADDR; } function setListOwner(address _address, bool _permitted) public nonReentrant senderIsListOwner { listOwners[_address] = _permitted; emit ListOwnerPermissions(msg.sender, _address, _permitted); } function setArbitrageurs(address[] memory _arbitrageurs, bool _permitted) public override nonReentrant senderIsListOwner { uint256 length = _arbitrageurs.length; for (uint256 index = 0; index < length; index++) { permittedAddressMap[_arbitrageurs[index]] = _permitted; } emit ArbitrageurPermissions(msg.sender, _arbitrageurs, _permitted); } function setArbitrageurs(address[] memory _arbitrageurs, bool _permitted) public override nonReentrant senderIsListOwner { uint256 length = _arbitrageurs.length; for (uint256 index = 0; index < length; index++) { permittedAddressMap[_arbitrageurs[index]] = _permitted; } emit ArbitrageurPermissions(msg.sender, _arbitrageurs, _permitted); } function setNextList(address _address) public nonReentrant senderIsListOwner { nextList = _address; emit NextList(msg.sender, _address); } function isListOwner(address _address) public view returns (bool) { return listOwners[_address]; } function isArbitrageur(address _address) public view override(IArbitrageurList) returns (bool) { return permittedAddressMap[_address]; } }
9,711,774
[ 1, 7469, 6835, 364, 30632, 666, 434, 6138, 15498, 358, 3073, 9119, 4993, 540, 10056, 86, 410, 1352, 6679, 603, 18972, 17, 42, 77, 24722, 2192, 49, 776, 21, 18, 20, 18, 377, 657, 18972, 17, 42, 77, 24722, 2192, 49, 776, 21, 18, 20, 16000, 16, 326, 19170, 7720, 261, 23616, 4993, 10056, 86, 410, 7720, 13, 2026, 1338, 540, 506, 4985, 2566, 635, 392, 1758, 716, 1135, 638, 1347, 353, 686, 3682, 86, 410, 295, 316, 279, 6835, 540, 10379, 628, 333, 1245, 261, 5787, 4894, 1297, 2546, 4800, 326, 1758, 434, 326, 10056, 86, 410, 19170, 540, 358, 5853, 330, 305, 340, 279, 745, 358, 353, 686, 3682, 86, 410, 295, 316, 326, 3434, 6835, 2934, 377, 16896, 1791, 28757, 854, 2112, 364, 9702, 326, 10056, 86, 410, 295, 666, 16, 2898, 854, 30, 2398, 300, 1021, 444, 686, 3682, 86, 410, 25152, 707, 16, 1492, 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, 1201, 3682, 86, 410, 295, 682, 10908, 353, 467, 686, 3682, 86, 410, 295, 682, 16, 868, 8230, 12514, 16709, 288, 203, 225, 2874, 12, 2867, 516, 1426, 13, 3238, 666, 5460, 414, 31, 203, 225, 2874, 12, 2867, 516, 1426, 13, 3238, 15498, 1887, 863, 31, 203, 225, 1758, 1071, 3849, 12, 45, 686, 3682, 86, 410, 295, 682, 13, 1024, 682, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 27, 18, 26, 31, 203, 5666, 288, 467, 686, 3682, 86, 410, 295, 682, 289, 628, 315, 6216, 15898, 19, 45, 686, 3682, 86, 410, 295, 682, 18, 18281, 14432, 203, 5666, 288, 868, 8230, 12514, 16709, 289, 628, 315, 6216, 18770, 17, 3644, 17, 90, 22, 19, 2941, 19, 3190, 94, 881, 84, 292, 267, 19, 426, 8230, 12514, 16709, 18, 18281, 14432, 203, 225, 9606, 5793, 2520, 682, 5541, 1435, 288, 203, 565, 2583, 12, 1098, 5460, 414, 63, 3576, 18, 15330, 6487, 315, 12021, 1297, 506, 666, 5541, 8863, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 3885, 12, 2867, 8526, 3778, 389, 297, 3682, 86, 410, 25152, 13, 288, 203, 565, 1426, 15498, 273, 638, 31, 203, 203, 565, 666, 5460, 414, 63, 3576, 18, 15330, 65, 273, 15498, 31, 203, 565, 3626, 987, 5541, 6521, 12, 3576, 18, 15330, 16, 1234, 18, 15330, 16, 15498, 1769, 203, 203, 565, 444, 686, 3682, 86, 410, 25152, 24899, 297, 3682, 86, 410, 25152, 16, 15498, 1769, 203, 565, 3626, 1201, 3682, 86, 410, 295, 6521, 2 ]
// chief.t.sol - test for chief.sol // Copyright (C) 2017 DappHub, LLC // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // This program 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 General Public License for more details. // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/>. pragma solidity >=0.4.23; import "ds-test/test.sol"; import "ds-token/token.sol"; import "ds-thing/thing.sol"; import "./chief.sol"; contract ChiefUser is DSThing { DSChief chief; constructor(DSChief chief_) public { chief = chief_; } function doTransferFrom(DSToken token, address from, address to, uint amount) public returns (bool) { return token.transferFrom(from, to, amount); } function doTransfer(DSToken token, address to, uint amount) public returns (bool) { return token.transfer(to, amount); } function doApprove(DSToken token, address recipient, uint amount) public returns (bool) { return token.approve(recipient, amount); } function doAllowance(DSToken token, address owner, address spender) public view returns (uint) { return token.allowance(owner, spender); } function doEtch(address[] memory guys) public returns (bytes32) { return chief.etch(guys); } function doVote(address[] memory guys) public returns (bytes32) { return chief.vote(guys); } function doVote(address[] memory guys, address lift_whom) public returns (bytes32) { bytes32 slate = chief.vote(guys); chief.lift(lift_whom); return slate; } function doVote(bytes32 id) public { chief.vote(id); } function doVote(bytes32 id, address lift_whom) public { chief.vote(id); chief.lift(lift_whom); } function doLift(address to_lift) public { chief.lift(to_lift); } function doLock(uint amt) public { chief.lock(amt); } function doFree(uint amt) public { chief.free(amt); } function doSetUserRole(address who, uint8 role, bool enabled) public { chief.setUserRole(who, role, enabled); } function doSetRoleCapability(uint8 role, address code, bytes4 sig, bool enabled) public { chief.setRoleCapability(role, code, sig, enabled); } function doSetPublicCapability(address code, bytes4 sig, bool enabled) public { chief.setPublicCapability(code, sig, enabled); } function authedFn() public view auth returns (bool) { return true; } } contract DSChiefTest is DSThing, DSTest { uint256 constant electionSize = 3; // c prefix: candidate address constant c1 = address(0x1); address constant c2 = address(0x2); address constant c3 = address(0x3); address constant c4 = address(0x4); address constant c5 = address(0x5); address constant c6 = address(0x6); address constant c7 = address(0x7); address constant c8 = address(0x8); address constant c9 = address(0x9); uint256 constant initialBalance = 1000 ether; uint256 constant uLargeInitialBalance = initialBalance / 3; uint256 constant uMediumInitialBalance = initialBalance / 4; uint256 constant uSmallInitialBalance = initialBalance / 5; DSChief chief; DSToken gov; DSToken iou; // u prefix: user ChiefUser uLarge; ChiefUser uMedium; ChiefUser uSmall; function setUp() public { gov = new DSToken("GOV"); gov.mint(initialBalance); DSChiefFab fab = new DSChiefFab(); chief = fab.newChief(gov, electionSize); iou = chief.IOU(); uLarge = new ChiefUser(chief); uMedium = new ChiefUser(chief); uSmall = new ChiefUser(chief); assert(initialBalance > uLargeInitialBalance + uMediumInitialBalance + uSmallInitialBalance); assert(uLargeInitialBalance < uMediumInitialBalance + uSmallInitialBalance); gov.transfer(address(uLarge), uLargeInitialBalance); gov.transfer(address(uMedium), uMediumInitialBalance); gov.transfer(address(uSmall), uSmallInitialBalance); } function test_basic_sanity() public pure { assert(true); } function testFail_basic_sanity() public pure { assert(false); } function test_etch_returns_same_id_for_same_sets() public { address[] memory candidates = new address[](3); candidates[0] = c1; candidates[1] = c2; candidates[2] = c3; bytes32 id = uSmall.doEtch(candidates); assert(id != 0x0); assertEq32(id, uMedium.doEtch(candidates)); } function test_size_zero_slate() public { address[] memory candidates = new address[](0); bytes32 id = uSmall.doEtch(candidates); uSmall.doVote(id); } function test_size_one_slate() public { address[] memory candidates = new address[](1); candidates[0] = c1; bytes32 id = uSmall.doEtch(candidates); uSmall.doVote(id); } function testFail_etch_requires_ordered_sets() public { address[] memory candidates = new address[](3); candidates[0] = c2; candidates[1] = c1; candidates[2] = c3; uSmall.doEtch(candidates); } function test_lock_debits_user() public { assert(gov.balanceOf(address(uLarge)) == uLargeInitialBalance); uint lockedAmt = uLargeInitialBalance / 10; uLarge.doApprove(gov, address(chief), lockedAmt); uLarge.doLock(lockedAmt); assert(gov.balanceOf(address(uLarge)) == uLargeInitialBalance - lockedAmt); } function test_changing_weight_after_voting() public { uint uLargeLockedAmt = uLargeInitialBalance / 2; uLarge.doApprove(iou, address(chief), uLargeLockedAmt); uLarge.doApprove(gov, address(chief), uLargeLockedAmt); uLarge.doLock(uLargeLockedAmt); address[] memory uLargeSlate = new address[](1); uLargeSlate[0] = c1; uLarge.doVote(uLargeSlate); assert(chief.approvals(c1) == uLargeLockedAmt); // Changing weight should update the weight of our candidate. uLarge.doFree(uLargeLockedAmt); assert(chief.approvals(c1) == 0); uLargeLockedAmt = uLargeInitialBalance / 4; uLarge.doApprove(gov, address(chief), uLargeLockedAmt); uLarge.doLock(uLargeLockedAmt); assert(chief.approvals(c1) == uLargeLockedAmt); } function test_voting_and_reordering() public { assert(gov.balanceOf(address(uLarge)) == uLargeInitialBalance); initial_vote(); // Upset the order. uint uLargeLockedAmt = uLargeInitialBalance; uLarge.doApprove(gov, address(chief), uLargeLockedAmt); uLarge.doLock(uLargeLockedAmt); address[] memory uLargeSlate = new address[](1); uLargeSlate[0] = c3; uLarge.doVote(uLargeSlate); } function testFail_lift_while_out_of_order() public { initial_vote(); // Upset the order. uSmall.doApprove(gov, address(chief), uSmallInitialBalance); uSmall.doLock(uSmallInitialBalance); address[] memory uSmallSlate = new address[](1); uSmallSlate[0] = c3; uSmall.doVote(uSmallSlate); uMedium.doFree(uMediumInitialBalance); chief.lift(c3); } function test_lift_half_approvals() public { initial_vote(); // Upset the order. uSmall.doApprove(gov, address(chief), uSmallInitialBalance); uSmall.doLock(uSmallInitialBalance); address[] memory uSmallSlate = new address[](1); uSmallSlate[0] = c3; uSmall.doVote(uSmallSlate); uMedium.doApprove(iou, address(chief), uMediumInitialBalance); uMedium.doFree(uMediumInitialBalance); chief.lift(c3); assert(!chief.isUserRoot(c1)); assert(!chief.isUserRoot(c2)); assert(chief.isUserRoot(c3)); } function testFail_voting_and_reordering_without_weight() public { assert(gov.balanceOf(address(uLarge)) == uLargeInitialBalance); initial_vote(); // Vote without weight. address[] memory uLargeSlate = new address[](1); uLargeSlate[0] = c3; uLarge.doVote(uLargeSlate); // Attempt to update the elected set. chief.lift(c3); } function test_voting_by_slate_id() public { assert(gov.balanceOf(address(uLarge)) == uLargeInitialBalance); bytes32 slateID = initial_vote(); // Upset the order. uLarge.doApprove(gov, address(chief), uLargeInitialBalance); uLarge.doLock(uLargeInitialBalance); address[] memory uLargeSlate = new address[](1); uLargeSlate[0] = c4; uLarge.doVote(uLargeSlate); // Update the elected set to reflect the new order. chief.lift(c4); // Now restore the old order using a slate ID. uSmall.doApprove(gov, address(chief), uSmallInitialBalance); uSmall.doLock(uSmallInitialBalance); uSmall.doVote(slateID); // Update the elected set to reflect the restored order. chief.lift(c1); } function testFail_non_hat_can_not_set_roles() public { uSmall.doSetUserRole(address(uMedium), 1, true); } function test_hat_can_set_roles() public { address[] memory slate = new address[](1); slate[0] = address(uSmall); // Upset the order. uLarge.doApprove(gov, address(chief), uLargeInitialBalance); uLarge.doLock(uLargeInitialBalance); uLarge.doVote(slate); // Update the elected set to reflect the new order. chief.lift(address(uSmall)); uSmall.doSetUserRole(address(uMedium), 1, true); } function testFail_non_hat_can_not_role_capability() public { uSmall.doSetRoleCapability(1, address(uMedium), S("authedFn"), true); } function test_hat_can_set_role_capability() public { address[] memory slate = new address[](1); slate[0] = address(uSmall); // Upset the order. uLarge.doApprove(gov, address(chief), uLargeInitialBalance); uLarge.doLock(uLargeInitialBalance); uLarge.doVote(slate); // Update the elected set to reflect the new order. chief.lift(address(uSmall)); uSmall.doSetRoleCapability(1, address(uLarge), S("authedFn()"), true); uSmall.doSetUserRole(address(this), 1, true); uLarge.setAuthority(chief); uLarge.setOwner(address(0)); uLarge.authedFn(); } function test_hat_can_set_public_capability() public { address[] memory slate = new address[](1); slate[0] = address(uSmall); // Upset the order. uLarge.doApprove(gov, address(chief), uLargeInitialBalance); uLarge.doLock(uLargeInitialBalance); uLarge.doVote(slate); // Update the elected set to reflect the new order. chief.lift(address(uSmall)); uSmall.doSetPublicCapability(address(uLarge), S("authedFn()"), true); uLarge.setAuthority(chief); uLarge.setOwner(address(0)); uLarge.authedFn(); } function test_chief_no_owner() public { assertEq(chief.owner(), address(0)); } function initial_vote() internal returns (bytes32 slateID) { uint uMediumLockedAmt = uMediumInitialBalance; uMedium.doApprove(gov, address(chief), uMediumLockedAmt); uMedium.doLock(uMediumLockedAmt); address[] memory uMediumSlate = new address[](3); uMediumSlate[0] = c1; uMediumSlate[1] = c2; uMediumSlate[2] = c3; slateID = uMedium.doVote(uMediumSlate); // Lift the chief. chief.lift(c1); } }
Upset the order. Update the elected set to reflect the new order.
function test_hat_can_set_roles() public { address[] memory slate = new address[](1); slate[0] = address(uSmall); uLarge.doApprove(gov, address(chief), uLargeInitialBalance); uLarge.doLock(uLargeInitialBalance); uLarge.doVote(slate); chief.lift(address(uSmall)); uSmall.doSetUserRole(address(uMedium), 1, true); }
12,597,520
[ 1, 1211, 542, 326, 1353, 18, 2315, 326, 415, 828, 444, 358, 3037, 326, 394, 1353, 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 ]
[ 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, 1842, 67, 11304, 67, 4169, 67, 542, 67, 7774, 1435, 1071, 288, 203, 3639, 1758, 8526, 3778, 2020, 340, 273, 394, 1758, 8526, 12, 21, 1769, 203, 3639, 2020, 340, 63, 20, 65, 273, 1758, 12, 89, 19187, 1769, 203, 203, 3639, 582, 20020, 18, 2896, 12053, 537, 12, 75, 1527, 16, 1758, 12, 17384, 74, 3631, 582, 20020, 4435, 13937, 1769, 203, 3639, 582, 20020, 18, 2896, 2531, 12, 89, 20020, 4435, 13937, 1769, 203, 203, 3639, 582, 20020, 18, 2896, 19338, 12, 2069, 340, 1769, 203, 203, 3639, 462, 28515, 18, 80, 2136, 12, 2867, 12, 89, 19187, 10019, 203, 203, 3639, 582, 19187, 18, 2896, 694, 1299, 2996, 12, 2867, 12, 89, 25599, 3631, 404, 16, 638, 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 ]
pragma solidity ^0.4.19; /// @title Interface for contracts conforming to ERC-721: Non-Fungible Tokens /// @author Dieter Shirley <<span class="__cf_email__" data-cfemail="a5c1c0d1c0e5c4ddcccac8dfc0cb8bc6ca">[email&#160;protected]</span>> (https://github.com/dete) contract CSCERC721 { // Required methods function balanceOf(address _owner) public view returns (uint256 balance) { return 0; } function ownerOf(uint256 _tokenId) public view returns (address owner) { return;} function getCollectibleDetails(uint256 _assetId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, bool isRedeemed, address owner) { assetId = 0; sequenceId = 0; collectibleType = 0; collectibleClass = 0; owner = 0; isRedeemed = false; } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { return; } } contract CSCFactoryERC721 { function ownerOf(uint256 _tokenId) public view returns (address owner) { return;} function getCollectibleDetails(uint256 _tokenId) external view returns(uint256 assetId, uint256 sequenceId, uint256 collectibleType, uint256 collectibleClass, bytes32 collectibleName, bool isRedeemed, address owner) { assetId = 0; sequenceId = 0; collectibleType = 0; collectibleClass = 0; owner = 0; collectibleName = 0x0; isRedeemed = false; } function tokensOfOwner(address _owner) external view returns(uint256[] ownerTokens) { return; } } contract ERC20 { function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); } contract CSCResourceFactory { mapping(uint16 => address) public resourceIdToAddress; } contract MEAHiddenLogic { function getTotalTonsClaimed() external view returns(uint32) { return; } function getTotalSupply() external view returns(uint32) { return; } function getStarTotalSupply(uint8 _starId) external view returns(uint32) { return; } function getReturnTime(uint256 _assetId) external view returns(uint256 time) { return; } //uint256 iron, uint256 quartz, uint256 nickel, uint256 cobalt, uint256 silver, uint256 titanium, uint256 lucinite, uint256 gold, uint256 cosmethyst, uint256 allurum, uint256 platinum, uint256 trilite function setResourceForStar(uint8[5] _resourceTypes, uint16[5] _resourcePer, uint32[5] _resourceAmounts) public returns(uint8 starId) { } /// @dev Method to fetch collected ore details function getAssetCollectedOreBallances(uint256 _assetID) external view returns(uint256 iron, uint256 quartz, uint256 nickel, uint256 cobalt, uint256 silver, uint256 titanium, uint256 lucinite, uint256 gold, uint256 cosmethyst, uint256 allurum, uint256 platinum, uint256 trilite); function getAssetCollectedOreBallancesArray(uint256 _assetID) external view returns(uint256[12] ores); function emptyShipCargo(uint32 _assetId) external; /// @dev For creating CSC Collectible function startMEAMission(uint256 _assetId, uint256 oreMax, uint8 starId, uint256 _travelTime) public returns(uint256); } /* Controls state and access rights for contract functions * @title Operational Control * @author Fazri Zubair & Farhan Khwaja (Lucid Sight, Inc.) * Inspired and adapted from contract created by OpenZeppelin * Ref: https://github.com/OpenZeppelin/zeppelin-solidity/ */ contract OperationalControl { // Facilitates access & control for the game. // Roles: // -The Managers (Primary/Secondary): Has universal control of all elements (No ability to withdraw) // -The Banker: The Bank can withdraw funds and adjust fees / prices. // -otherManagers: Contracts that need access to functions for gameplay /// @dev Emited when contract is upgraded event ContractUpgrade(address newContract); /// @dev Emited when other manager is set event OtherManagerUpdated(address otherManager, uint256 state); // The addresses of the accounts (or contracts) that can execute actions within each roles. address public managerPrimary; address public managerSecondary; address public bankManager; // Contracts that require access for gameplay mapping(address => uint8) public otherManagers; // @dev Keeps track whether the contract is paused. When that is true, most actions are blocked bool public paused = false; // @dev Keeps track whether the contract erroredOut. When that is true, most actions are blocked & refund can be claimed bool public error = false; /// @dev Operation modifiers for limiting access modifier onlyManager() { require(msg.sender == managerPrimary || msg.sender == managerSecondary); _; } modifier onlyBanker() { require(msg.sender == bankManager); _; } modifier onlyOtherManagers() { require(otherManagers[msg.sender] == 1); _; } modifier anyOperator() { require( msg.sender == managerPrimary || msg.sender == managerSecondary || msg.sender == bankManager || otherManagers[msg.sender] == 1 ); _; } /// @dev Assigns a new address to act as the Other Manager. (State = 1 is active, 0 is disabled) function setOtherManager(address _newOp, uint8 _state) external onlyManager { require(_newOp != address(0)); otherManagers[_newOp] = _state; OtherManagerUpdated(_newOp,_state); } /// @dev Assigns a new address to act as the Primary Manager. function setPrimaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerPrimary = _newGM; } /// @dev Assigns a new address to act as the Secondary Manager. function setSecondaryManager(address _newGM) external onlyManager { require(_newGM != address(0)); managerSecondary = _newGM; } /// @dev Assigns a new address to act as the Banker. function setBanker(address _newBK) external onlyManager { require(_newBK != address(0)); bankManager = _newBK; } /*** 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 Modifier to allow actions only when the contract has Error modifier whenError { require(error); _; } /// @dev Called by any Operator role to pause the contract. /// Used only if a bug or exploit is discovered (Here to limit losses / damage) function pause() external onlyManager whenNotPaused { paused = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function unpause() public onlyManager whenPaused { // can&#39;t unpause if contract was upgraded paused = false; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function hasError() public onlyManager whenPaused { error = true; } /// @dev Unpauses the smart contract. Can only be called by the Game Master /// @notice This is public rather than external so it can be called by derived contracts. function noError() public onlyManager whenPaused { error = false; } } contract MEAManager is OperationalControl { /*** EVENTS ***/ /*** CONSTANTS ***/ uint256 public constant REAPER_INTREPID = 3; uint256 public constant REAPER_INTREPID_EXTRACTION_BASE = 10; // tons per hour of mining uint256 public constant REAPER_INTREPID_FTL_SPEED = 900; // Seconds to travel 1 light year uint256 public constant REAPER_INTREPID_MAX_CARGO = 320; uint256 public constant PHOENIX_CORSAIR = 2; uint256 public constant PHOENIX_CORSAIR_EXTRACTION_BASE = 40; // tons per hour of mining uint256 public constant PHOENIX_CORSAIR_FTL_SPEED = 1440; // Seconds to travel 1 light year uint256 public constant PHOENIX_CORSAIR_MAX_CARGO = 1500; uint256 public constant VULCAN_PROMETHEUS = 1; uint256 public constant VULCAN_PROMETHEUS_EXTRACTION_BASE = 300; // tons per hour of mining uint256 public constant VULCAN_PROMETHEUS_FTL_SPEED = 2057; // Seconds to travel 1 light year uint256 public constant VULCAN_PROMETHEUS_MAX_CARGO = 6000; uint256 public constant SIGMA = 4; uint256 public constant SIGMA_EXTRACTION_BASE = 150; // tons per hour of mining uint256 public constant SIGMA_FTL_SPEED = 4235; // Seconds to travel 1 light year uint256 public constant SIGMA_MAX_CARGO = 15000; uint256 public constant HAYATO = 5; uint256 public constant HAYATO_EXTRACTION_BASE = 150; // tons per hour of mining uint256 public constant HAYATO_FTL_SPEED = 360; // Seconds to travel 1 light year uint256 public constant HAYATO_MAX_CARGO = 1500; uint256 public constant CPGPEREGRINE = 6; uint256 public constant CPGPEREGRINE_EXTRACTION_BASE = 150; // tons per hour of mining uint256 public constant CPGPEREGRINE_FTL_SPEED = 720; // Seconds to travel 1 light year uint256 public constant CPGPEREGRINE_MAX_CARGO = 4000; uint256 public constant TACTICALCRUISER = 7; uint256 public constant TACTICALCRUISER_EXTRACTION_BASE = 150; // tons per hour of mining uint256 public constant TACTICALCRUISER_FTL_SPEED = 720; // Seconds to travel 1 light year uint256 public constant TACTICALCRUISER_MAX_CARGO = 1000; uint256 public constant OTHERCRUISER = 8; uint256 public constant OTHERCRUISER_EXTRACTION_BASE = 100; // tons per hour of mining uint256 public constant OTHERCRUISER_FTL_SPEED = 720; // Seconds to travel 1 light year uint256 public constant OTHERCRUISER_MAX_CARGO = 1500; uint256 public constant VULCAN_POD = 9; uint256 public constant VULCAN_POD_EXTRACTION_BASE = 1; // tons per hour of mining uint256 public constant VULCAN_POD_FTL_SPEED = 2000; // Seconds to travel 1 light year uint256 public constant VULCAN_POD_MAX_CARGO = 75; //For Devs to Travel Around uint256 public constant DEVCLASS = 99; uint256 public constant DEVCLASS_EXTRACTION_BASE = 50; // tons per hour of mining uint256 public constant DEVCLASS_FTL_SPEED = 10; // Seconds to travel 1 light year uint256 public constant DEVCLASS_MAX_CARGO = 500; /// @notice Name and symbol of the non fungible token, as defined in ERC721. string public constant NAME = "MEAGameManager"; /*** Mappings ***/ /// @dev assetID to ore type to qty collected mapping(uint32 => mapping(uint8 => uint32)) public collectedOreAssetMapping; /// @dev owner address to ore type to qty collected mapping(address => mapping(uint8 => uint32)) public collectedOreBalanceMapping; /// @dev owner address to ore type to qty collected mapping(address => mapping(uint8 => uint32)) public distributedOreBalanceMapping; /// @dev assetID to number of MEA trips it has completed mapping(uint32 => uint32) public assetIdNumberOfTripsMapping; /// @dev assetID to ore type to qty collected mapping(uint8 => uint16) public starLightyearDistanceMapping; /// @dev assetID to last star visited mapping(uint32 => uint8) public assetIdToStarVisitedMapping; /// @dev assetID to last star visited mapping(uint16 => address) public resourceERC20Address; /// @dev assetID to Start Time of Current Trip mapping(uint32 => uint32) public assetIdCurrentTripStartTimeMapping; /*** Variables ***/ uint256 public miningTimePerTrip = 3600; // 3600 for 1 hour 10 uint256 public aimeIncreasePerTrip = 2500; // 25.00 address cscERC721Address; address cscFactoryERC721Address; address hiddenLogicAddress; function MEAManager() public { require(msg.sender != address(0)); paused = true; managerPrimary = msg.sender; managerSecondary = msg.sender; bankManager = msg.sender; cscERC721Address = address(0xe4f5e0d5c033f517a943602df942e794a06bc123); cscFactoryERC721Address = address(0xcc9a66acf8574141b0e025202dd57649765a4be7); } /*** Management Functions ***/ /// @dev Set HiddenLogic function setHiddenLogic(address _hiddenLogicAddress) public onlyManager { hiddenLogicAddress = _hiddenLogicAddress; } /// @dev Set HiddenLogic function setResourceERC20Address(uint16 _resId, address _reourceAddress) public onlyManager { resourceERC20Address[_resId] = _reourceAddress; } /// @dev Set HiddenLogic function setAllResourceERC20Addresses(address _master) public onlyManager { CSCResourceFactory factory = CSCResourceFactory(_master); for(uint8 i = 0; i < 12; i++) { resourceERC20Address[i] = factory.resourceIdToAddress(i); } } /// @dev Set CSCErc721 Contract function setCSCERC721(address _cscERC721Address) public onlyManager { cscERC721Address = _cscERC721Address; } /// @dev Set CSCFactoryErc721 Contract function setCSCFactoryERC721(address _cscFactoryERC721Address) public onlyManager { cscFactoryERC721Address = _cscFactoryERC721Address; } /// @dev Set / Modify Lightyear Distance 3.456 ly = 3456 function setStarDistance(uint8 _starId, uint16 _lightyearsInThousands) public anyOperator { starLightyearDistanceMapping[_starId] = _lightyearsInThousands; } /// @dev Set / Modify MEA Game Attributes function setMEAAttributes(uint256 _aime, uint256 _miningTime) public onlyManager { aimeIncreasePerTrip = _aime; miningTimePerTrip = _miningTime; } /// @dev Withdraw Remaining Resource Tokens function reclaimResourceDeposits(address _withdrawAddress) public onlyManager { require(_withdrawAddress != address(0)); for(uint8 ii = 0; ii < 12; ii++) { if(resourceERC20Address[ii] != 0) { ERC20 resCont = ERC20(resourceERC20Address[ii]); uint256 bal = resCont.balanceOf(this); resCont.transfer(_withdrawAddress, bal); } } } /*** Public Functions ***/ /// @dev Get Current Cargo Hold of AssetId (item names) function getAssetIdCargo(uint32 _assetId) public view returns(uint256 iron, uint256 quartz, uint256 nickel, uint256 cobalt, uint256 silver, uint256 titanium, uint256 lucinite, uint256 gold, uint256 cosmethyst, uint256 allurum, uint256 platinum, uint256 trilite) { uint256[12] memory _ores = getAssetIdCargoArray(_assetId); iron = _ores[0]; quartz = _ores[1]; nickel = _ores[2]; cobalt = _ores[3]; silver = _ores[4]; titanium = _ores[5]; lucinite = _ores[6]; gold = _ores[7]; cosmethyst = _ores[8]; allurum = _ores[9]; platinum = _ores[10]; trilite = _ores[11]; } // function getAllShipStats(uint32[] _shipIds) public view returns(uint32[] results) { // //loop all results // for(uint i = 0; i < _shipIds.length; i++) { // results[]]; // } // } /// @dev Get Current Cargo Hold of AssetId (array) function getAssetIdCargoArray (uint32 _assetId) public view returns(uint256[12]) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); return logic.getAssetCollectedOreBallancesArray(_assetId); } /// @dev Get AssetId Trip Completed Time function getAssetIdTripCompletedTime(uint256 _assetId) external view returns(uint256 time) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); return logic.getReturnTime(uint32(_assetId)); } /// @dev Get AssetId Trip Completed Time function getAssetIdTripStartTime(uint256 _assetId) external view returns(uint256 time) { return assetIdCurrentTripStartTimeMapping[uint32(_assetId)]; } function getLastStarOfAssetId(uint32 _assetId) public view returns(uint8 starId){ return assetIdToStarVisitedMapping[_assetId]; } /// @dev Get Resource Address function getResourceERC20Address(uint16 _resId) public view returns(address resourceContract) { return resourceERC20Address[_resId]; } /// @dev Get Time function getMEATime() external view returns(uint256 time) { return now; } /// @dev Method to fetch processed ore details function getCollectedOreBalances(address _owner) external view returns(uint256 iron, uint256 quartz, uint256 nickel, uint256 cobalt, uint256 silver, uint256 titanium, uint256 lucinite, uint256 gold, uint256 cosmethyst, uint256 allurum, uint256 platinum, uint256 trilite) { iron = collectedOreBalanceMapping[_owner][0]; quartz = collectedOreBalanceMapping[_owner][1]; nickel = collectedOreBalanceMapping[_owner][2]; cobalt = collectedOreBalanceMapping[_owner][3]; silver = collectedOreBalanceMapping[_owner][4]; titanium = collectedOreBalanceMapping[_owner][5]; lucinite = collectedOreBalanceMapping[_owner][6]; gold = collectedOreBalanceMapping[_owner][7]; cosmethyst = collectedOreBalanceMapping[_owner][8]; allurum = collectedOreBalanceMapping[_owner][9]; platinum = collectedOreBalanceMapping[_owner][10]; trilite = collectedOreBalanceMapping[_owner][11]; } /// @dev Method to fetch processed ore details function getDistributedOreBalances(address _owner) external view returns(uint256 iron, uint256 quartz, uint256 nickel, uint256 cobalt, uint256 silver, uint256 titanium, uint256 lucinite, uint256 gold, uint256 cosmethyst, uint256 allurum, uint256 platinum, uint256 trilite) { iron = distributedOreBalanceMapping[_owner][0]; quartz = distributedOreBalanceMapping[_owner][1]; nickel = distributedOreBalanceMapping[_owner][2]; cobalt = distributedOreBalanceMapping[_owner][3]; silver = distributedOreBalanceMapping[_owner][4]; titanium = distributedOreBalanceMapping[_owner][5]; lucinite = distributedOreBalanceMapping[_owner][6]; gold = distributedOreBalanceMapping[_owner][7]; cosmethyst = distributedOreBalanceMapping[_owner][8]; allurum = distributedOreBalanceMapping[_owner][9]; platinum = distributedOreBalanceMapping[_owner][10]; trilite = distributedOreBalanceMapping[_owner][11]; } function withdrawCollectedResources() public { for(uint8 ii = 0; ii < 12; ii++) { require(resourceERC20Address[ii] != address(0)); uint32 oreOutstanding = collectedOreBalanceMapping[msg.sender][ii] - distributedOreBalanceMapping[msg.sender][ii]; if(oreOutstanding > 0) { ERC20 resCont = ERC20(resourceERC20Address[ii]); distributedOreBalanceMapping[msg.sender][ii] += oreOutstanding; resCont.transfer(msg.sender, oreOutstanding); } } } //Gets star distance in thousandths of ly function getStarDistanceInLyThousandths(uint8 _starId) public view returns (uint32 total) { return starLightyearDistanceMapping[_starId]; } //Gets total resources already claimed by commanders function totalMEATonsClaimed() public view returns (uint32 total) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); return logic.getTotalTonsClaimed(); } //Gets total seeded supply commanders function totalMEATonsSupply() public view returns (uint32 total) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); return logic.getTotalSupply(); } function totalStarSupplyRemaining(uint8 _starId) external view returns(uint32) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); return logic.getStarTotalSupply(_starId); } function claimOreOnlyFromAssetId(uint256 _assetId) { uint256 collectibleClass = 0; address shipOwner; (collectibleClass, shipOwner) = _getShipInfo(_assetId); require(shipOwner == msg.sender); _claimOreAndClear(uint32(_assetId), 0); } /// @dev For creating CSC Collectible function launchShipOnMEA(uint256 _assetId, uint8 starId) public whenNotPaused returns(uint256) { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); uint256 collectibleClass = 0; address shipOwner; (collectibleClass, shipOwner) = _getShipInfo(_assetId); //Check if the ship owner is sender require(shipOwner == msg.sender); //Check if ship is back at earth require(now > logic.getReturnTime(_assetId)); //Claims ore and clears _claimOreAndClear(uint32(_assetId), starId); //Get Asset Stats uint tripCount = assetIdNumberOfTripsMapping[uint32(_assetId)]; uint starTripDist = starLightyearDistanceMapping[starId]; uint256 oreMax = 5; uint256 tripSeconds = 10; if(collectibleClass == REAPER_INTREPID) { oreMax = REAPER_INTREPID_EXTRACTION_BASE + (REAPER_INTREPID_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = REAPER_INTREPID_FTL_SPEED * starTripDist / 1000; // 4LPH - 900 seconds per light year if(oreMax > REAPER_INTREPID_MAX_CARGO) oreMax = REAPER_INTREPID_MAX_CARGO; } else if(collectibleClass == PHOENIX_CORSAIR) { oreMax = PHOENIX_CORSAIR_EXTRACTION_BASE + (PHOENIX_CORSAIR_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = PHOENIX_CORSAIR_FTL_SPEED * starTripDist / 1000; // 2.5LPH - 1440 seconds per light year if(oreMax > PHOENIX_CORSAIR_MAX_CARGO) oreMax = PHOENIX_CORSAIR_MAX_CARGO; } else if(collectibleClass == VULCAN_PROMETHEUS) { oreMax = VULCAN_PROMETHEUS_EXTRACTION_BASE + (VULCAN_PROMETHEUS_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = VULCAN_PROMETHEUS_FTL_SPEED * starTripDist / 1000; // 1.75LPH - 2057 seconds per light year if(oreMax > VULCAN_PROMETHEUS_MAX_CARGO) oreMax = VULCAN_PROMETHEUS_MAX_CARGO; } else if(collectibleClass == SIGMA) { oreMax = SIGMA_EXTRACTION_BASE + (SIGMA_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = SIGMA_FTL_SPEED * starTripDist / 1000; // 0.85LPH - 4235 seconds per light year if(oreMax > SIGMA_MAX_CARGO) oreMax = SIGMA_MAX_CARGO; } else if(collectibleClass == HAYATO) { //Hayato oreMax = HAYATO_EXTRACTION_BASE + (HAYATO_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = HAYATO_FTL_SPEED * starTripDist / 1000; // 10LPH - 360 seconds per light year if(oreMax > HAYATO_MAX_CARGO) oreMax = HAYATO_MAX_CARGO; } else if(collectibleClass == CPGPEREGRINE) { //CPG Peregrine oreMax = CPGPEREGRINE_EXTRACTION_BASE + (CPGPEREGRINE_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = CPGPEREGRINE_FTL_SPEED * starTripDist / 1000; // 5LPH -720 seconds per light year if(oreMax > CPGPEREGRINE_MAX_CARGO) oreMax = CPGPEREGRINE_MAX_CARGO; } else if(collectibleClass == TACTICALCRUISER) { //TACTICA CRUISER Ships oreMax = TACTICALCRUISER_EXTRACTION_BASE + (TACTICALCRUISER_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = TACTICALCRUISER_FTL_SPEED * starTripDist / 1000; if(oreMax > TACTICALCRUISER_MAX_CARGO) oreMax = TACTICALCRUISER_MAX_CARGO; } else if(collectibleClass == VULCAN_POD) { //TACTICA CRUISER Ships oreMax = VULCAN_POD_EXTRACTION_BASE + (VULCAN_POD_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = VULCAN_POD_FTL_SPEED * starTripDist / 1000; if(oreMax > VULCAN_POD_MAX_CARGO) oreMax = VULCAN_POD_MAX_CARGO; } else if(collectibleClass >= DEVCLASS) { //Dev Ships oreMax = DEVCLASS_EXTRACTION_BASE + (DEVCLASS_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = DEVCLASS_FTL_SPEED * starTripDist / 1000; if(oreMax > DEVCLASS_MAX_CARGO) oreMax = DEVCLASS_MAX_CARGO; } else { if(collectibleClass >= OTHERCRUISER) { //Support Other Promo Ships oreMax = OTHERCRUISER_EXTRACTION_BASE + (OTHERCRUISER_EXTRACTION_BASE * tripCount * aimeIncreasePerTrip / 10000); tripSeconds = OTHERCRUISER_FTL_SPEED * starTripDist / 1000; if(oreMax > OTHERCRUISER_MAX_CARGO) oreMax = OTHERCRUISER_MAX_CARGO; } } //Make Round Trip + Mining tripSeconds = ((tripSeconds * 2) + miningTimePerTrip); //3600 for an hour - 0 for testing *************************** //calculate travel time uint256 returnTime = logic.startMEAMission(_assetId, oreMax, starId, tripSeconds); //Confirm trip if(returnTime > 0) { assetIdNumberOfTripsMapping[uint32(_assetId)] += 1; assetIdToStarVisitedMapping[uint32(_assetId)] = starId; assetIdCurrentTripStartTimeMapping[uint32(_assetId)] = uint32(now); } return returnTime; } /*** PRIVATE FUNCTIONS ***/ /// @dev Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) internal pure returns (bool) { return _to != address(0); } /// @dev Claims and clears cargo -- ONLY INTERNAL function _claimOreAndClear (uint32 _assetId, uint8 _starId) internal { MEAHiddenLogic logic = MEAHiddenLogic(hiddenLogicAddress); uint256[12] memory _ores = logic.getAssetCollectedOreBallancesArray(_assetId); bool hasItems = false; for(uint8 i = 0; i < 12; i++) { if(_ores[i] > 0) { collectedOreBalanceMapping[msg.sender][i] += uint32(_ores[i]); hasItems = true; } } //Doesn&#39;t Let you Travel to empty stars but lets you collect if(hasItems == false && _starId > 0) { require(logic.getStarTotalSupply(_starId) > 0); } logic.emptyShipCargo(_assetId); } function _getShipInfo(uint256 _assetId) internal view returns (uint256 collectibleClass, address owner) { uint256 nulldata; bool nullbool; uint256 collectibleType; if(_assetId <= 3000) { CSCERC721 shipData = CSCERC721(cscERC721Address); (nulldata, nulldata, collectibleType, collectibleClass, nullbool, owner) = shipData.getCollectibleDetails(_assetId); } else { bytes32 nullstring; CSCFactoryERC721 shipFData = CSCFactoryERC721(cscFactoryERC721Address); (nulldata, nulldata, collectibleType, collectibleClass, nullstring, nullbool, owner) = shipFData.getCollectibleDetails(_assetId); } } }
1.75LPH - 2057 seconds per light year
tripSeconds = VULCAN_PROMETHEUS_FTL_SPEED * starTripDist / 1000;
2,096,890
[ 1, 21, 18, 5877, 48, 8939, 300, 4200, 10321, 3974, 1534, 9052, 3286, 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, 5411, 20654, 6762, 273, 776, 1506, 39, 1258, 67, 3373, 5277, 41, 3378, 67, 4464, 48, 67, 23810, 2056, 380, 10443, 16148, 5133, 342, 4336, 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 ]
// contracts/GLDToken.sol // SPDX-License-Identifier: MIT pragma solidity 0.6.2; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Capped.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; contract Token is ERC20Capped, Ownable, ERC20Burnable { using SafeMath for uint256; // how many token units a buyer gets per wei uint256 public rate = 3500 * 10 ** 18; bool crowdSaleFinished = false; uint256 start; constructor() public ERC20("Grem", "Grm") ERC20Capped(28000000 * (10 ** 18)) { // init predefined address distribution _mint(msg.sender, 11200000 * 10**18); start = now; } function finishCrowdsale() public onlyOwner { crowdSaleFinished = true; uint256 leftOver = 28000000 * 10 ** 18 - totalSupply(); if (leftOver > 0) { _mint(owner(), leftOver); } } function isCrowdsaleFinished() public view returns (bool) { return crowdSaleFinished; } function updateRate(uint256 _newRate) public onlyOwner { rate = SafeMath.mul(_newRate, 10 ** 18); } // low level token purchase function receive() external payable { require(msg.sender != address(0)); require(msg.value >= 1 * 10 ** 18); uint256 weiAmount = msg.value; // calculate token amount to be created // if value > 10 * 10 ** 18 uint256 tokens = 0; if (msg.value < 10 * 10 ** 18) { tokens = getTokenAmount(weiAmount); } else { // get bonus tokens 10% for amount of >= 1 ETH tokens = getTokenAmount(SafeMath.add(weiAmount, SafeMath.div(weiAmount, 10 ** 1))); } /* uint256 vestingDays = ((start + 90 days) - now) / 60 / 60 / 24; */ /* if (vestingDays >= 1) { */ /* tokens = SafeMath.add(tokens, SafeMath.div(SafeMath.mul(SafeMath.mul(SafeMath.div(tokens,100), 22222222), vestingDays), 10 ** 8)); */ /* } */ // mint tokens to owner address _mint(owner(), tokens); // send purchased token amount and bonuses to payer _transfer(owner(), msg.sender, tokens); payable(owner()).transfer(msg.value); } function getTokenAmount(uint256 weiAmount) internal view returns(uint256) { uint256 amount = SafeMath.div(SafeMath.mul(weiAmount, rate), 10 ** 18); return amount; } /** * Requirements: * * crowdsale should be closed now */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual override(ERC20Capped, ERC20) { super._beforeTokenTransfer(from, to, amount); /* if (from != address(0) && from != owner()) { // When transferring tokens not minting */ /* require(now > start + 90 days, "Transfers are closed till 90 days since contract deploy date"); */ /* require(crowdSaleFinished, "Token: crowdsale is not yet finished"); */ /* } */ } }
When transferring tokens not minting */
/* if (from != address(0) && from != owner()) {
6,407,161
[ 1, 9434, 906, 74, 20245, 2430, 486, 312, 474, 310, 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 ]
[ 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, 3639, 1748, 309, 261, 2080, 480, 1758, 12, 20, 13, 597, 628, 480, 3410, 10756, 288, 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 ]
./full_match/1/0x270D3971d46d1b6B75C20113cE796BE83577e82D/sources/contracts/BaltoOriginNft.sol
Optional mapping for token URIs
contract BaltoOriginNft is Ownable, ERC721URIStorage, ReentrancyGuard { using Strings for uint256; uint256 private constant MAX_SUPPLY = 5000; bool public mintAllowed = false; string private _tokenBaseURI = ""; mapping(uint256 => string) private _tokenURIs; bytes32 private merkleRoot; mapping(address => uint256) public numOfMints; uint256 public totalSupply = 0; uint256 public currentPhase; uint256 public oneTimeMintLimit = 40; uint256[7] public lastTokenIds = [350, 850, 1700, 2550, 3400, 4250, 5000]; uint256[7] public prices = [0.03 ether, 0.04 ether, 0.04 ether, 0.04 ether, 0.05 ether, 0.05 ether, 0.06 ether]; address public treasury = 0x2874054656ab183BCe742deF5994d0B3BD6f6aF8; address public feeWallet = 0x2874054656ab183BCe742deF5994d0B3BD6f6aF8; uint256 public performanceFee = 0.0023 ether; event MintEnabled(); event MoveToNextPhase(uint256 phase); event Mint(address indexed user, uint256 tokenId); event BaseURIUpdated(string uri); event SetMintPrice(uint256 phase, uint256 price); event SetLastTokenId(uint256 phase, uint256 lastTokenId); event SetOneTimeMintLimit(uint256 limit); event SetWhitelist(bytes32 whitelistMerkleRoot); event SetFeeWallet(address wallet); event ServiceInfoUpadted(address wallet, uint256 fee); event AdminTokenRecovered(address tokenRecovered, uint256 amount); pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/Ownable.sol"; modifier onlyMintable() { require(mintAllowed && totalSupply < MAX_SUPPLY, "cannot mint"); _; } constructor() ERC721("Balto Origin NFT", "BaltoAlpha") {} function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } } else { function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } function mint( bytes32[] memory _merkleProof, uint256 _numToMint, uint256 _maxToMint ) external payable onlyMintable nonReentrant { require(_numToMint > 0, "invalid amount"); require(_numToMint <= oneTimeMintLimit, "exceed one-time mint limit"); require(totalSupply + _numToMint <= lastTokenIds[currentPhase - 1], "Exceed current phase limit"); uint256 price = prices[currentPhase - 1] * _numToMint; bytes32 leaf = keccak256(abi.encodePacked(msg.sender, _maxToMint)); if (MerkleProof.verify(_merkleProof, merkleRoot, leaf)) { if (numOfMints[msg.sender] < _maxToMint) { uint256 remainedFreeMint = _maxToMint - numOfMints[msg.sender]; if (remainedFreeMint >= _numToMint) { price = 0; price -= prices[currentPhase - 1] * remainedFreeMint; } } } require(msg.value >= price + performanceFee, "insufficient eth amount for mint"); payable(feeWallet).transfer(price); payable(treasury).transfer(performanceFee); if (msg.value > price + performanceFee) { payable(msg.sender).transfer(msg.value - price - performanceFee); } numOfMints[msg.sender] += _numToMint; for (uint256 i = 0; i < _numToMint; i++) { uint256 tokenId = totalSupply + i + 1; _safeMint(msg.sender, tokenId); _setTokenURI(tokenId, tokenId.toString()); super._setTokenURI(tokenId, tokenId.toString()); emit Mint(msg.sender, tokenId); } totalSupply += _numToMint; if (totalSupply == MAX_SUPPLY) { mintAllowed = false; if (totalSupply >= lastTokenIds[currentPhase - 1]) currentPhase += 1; } } } else { function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "RabblePass: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI(), _tokenURI)); } return super.tokenURI(tokenId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "RabblePass: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI(), _tokenURI)); } return super.tokenURI(tokenId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "RabblePass: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); if (bytes(base).length == 0) { return _tokenURI; } if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(_baseURI(), _tokenURI)); } return super.tokenURI(tokenId); } function enableMint() external onlyOwner { require(merkleRoot != "", "Whitelist not set"); require(!mintAllowed, "already enabled"); require(currentPhase == 0, "mint already finished"); currentPhase = 1; mintAllowed = true; emit MintEnabled(); } function moveToNextPhase() external onlyOwner { require(mintAllowed, "mint not enabled"); require(currentPhase < 7, "reached last phase"); lastTokenIds[currentPhase - 1] = totalSupply; currentPhase++; emit MoveToNextPhase(currentPhase); } function setMintPrice(uint256 _phase, uint256 _price) external onlyOwner { require(_phase <= 7 && _phase > 0, "invalid phase"); require(_phase >= currentPhase, "cannot update mint price of previous phase"); prices[_phase - 1] = _price; emit SetMintPrice(_phase, _price); } function setLastTokenIdForPhase(uint256 _phase, uint256 _lastTokenId) external onlyOwner { require(_phase <= 7 && _phase > 0, "invalid phase"); require(_phase < 7, "cannot set last tokenId for last phase"); require(_phase >= currentPhase, "cannot update last tokenId of previous phase"); require(_lastTokenId <= MAX_SUPPLY, "exceed max supply"); require(_lastTokenId >= totalSupply, "use upcoming tokenId"); require(_lastTokenId < lastTokenIds[_phase], "use a tokenId less than last tokenId in next phase"); if(_phase > 1) { require(_lastTokenId > lastTokenIds[_phase - 2], "use a tokenId greater than last tokenId in prev phase"); } lastTokenIds[_phase - 1] = _lastTokenId; emit SetLastTokenId(_phase, _lastTokenId); } function setLastTokenIdForPhase(uint256 _phase, uint256 _lastTokenId) external onlyOwner { require(_phase <= 7 && _phase > 0, "invalid phase"); require(_phase < 7, "cannot set last tokenId for last phase"); require(_phase >= currentPhase, "cannot update last tokenId of previous phase"); require(_lastTokenId <= MAX_SUPPLY, "exceed max supply"); require(_lastTokenId >= totalSupply, "use upcoming tokenId"); require(_lastTokenId < lastTokenIds[_phase], "use a tokenId less than last tokenId in next phase"); if(_phase > 1) { require(_lastTokenId > lastTokenIds[_phase - 2], "use a tokenId greater than last tokenId in prev phase"); } lastTokenIds[_phase - 1] = _lastTokenId; emit SetLastTokenId(_phase, _lastTokenId); } function setOneTimeMintLimit(uint256 _limit) external onlyOwner { require(_limit <= 150, "cannot exceed 150"); oneTimeMintLimit = _limit; emit SetOneTimeMintLimit(_limit); } function setAdminWallet(address _wallet) external onlyOwner { require(_wallet != address(0x0), "invalid address"); feeWallet = _wallet; emit SetFeeWallet(_wallet); } function setServiceInfo(address _treasury, uint256 _fee) external onlyOwner { require(_treasury != address(0x0), "invalid address"); treasury = _treasury; performanceFee = _fee; emit ServiceInfoUpadted(_treasury, _fee); } function setWhiteList(bytes32 _merkleRoot) external onlyOwner { require(_merkleRoot != "", "invalid merkle root"); merkleRoot = _merkleRoot; emit SetWhitelist(_merkleRoot); } function rescueTokens(address _token, uint256 _amount) external onlyOwner { if (_token == address(0x0)) { payable(msg.sender).transfer(_amount); IERC20(_token).transfer(address(msg.sender), _amount); } emit AdminTokenRecovered(_token, _amount); } function rescueTokens(address _token, uint256 _amount) external onlyOwner { if (_token == address(0x0)) { payable(msg.sender).transfer(_amount); IERC20(_token).transfer(address(msg.sender), _amount); } emit AdminTokenRecovered(_token, _amount); } } else { function setTokenBaseUri(string memory _uri) external onlyOwner { _tokenBaseURI = _uri; emit BaseURIUpdated(_uri); } function _baseURI() internal view override returns (string memory) { return _tokenBaseURI; } function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal override { require(_exists(tokenId), "BaltoOriginNft: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } receive() external payable {} }
3,168,713
[ 1, 6542, 2874, 364, 1147, 24565, 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, 16351, 605, 287, 869, 7571, 50, 1222, 353, 14223, 6914, 16, 4232, 39, 27, 5340, 3098, 3245, 16, 868, 8230, 12514, 16709, 288, 203, 225, 1450, 8139, 364, 2254, 5034, 31, 203, 203, 225, 2254, 5034, 3238, 5381, 4552, 67, 13272, 23893, 273, 20190, 31, 203, 225, 1426, 1071, 312, 474, 5042, 273, 629, 31, 203, 203, 225, 533, 3238, 389, 2316, 2171, 3098, 273, 1408, 31, 203, 225, 2874, 12, 11890, 5034, 516, 533, 13, 3238, 389, 2316, 1099, 2520, 31, 203, 203, 225, 1731, 1578, 3238, 30235, 2375, 31, 203, 225, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 23153, 49, 28142, 31, 203, 203, 225, 2254, 5034, 1071, 2078, 3088, 1283, 273, 374, 31, 203, 225, 2254, 5034, 1071, 783, 11406, 31, 203, 203, 225, 2254, 5034, 1071, 1245, 950, 49, 474, 3039, 273, 8063, 31, 203, 225, 2254, 5034, 63, 27, 65, 1071, 27231, 2673, 273, 306, 23, 3361, 16, 1725, 3361, 16, 8043, 713, 16, 4561, 20, 16, 13438, 713, 16, 1059, 26520, 16, 20190, 15533, 203, 225, 2254, 5034, 63, 27, 65, 1071, 19827, 273, 306, 20, 18, 4630, 225, 2437, 16, 374, 18, 3028, 225, 2437, 16, 374, 18, 3028, 225, 2437, 16, 374, 18, 3028, 225, 2437, 16, 374, 18, 6260, 225, 2437, 16, 374, 18, 6260, 225, 2437, 16, 374, 18, 7677, 225, 2437, 15533, 203, 203, 225, 1758, 1071, 9787, 345, 22498, 273, 374, 92, 6030, 5608, 6260, 8749, 4313, 378, 31672, 16283, 73, 5608, 22, 323, 42, 25, 2733, 24, 72, 20, 38, 2 ]
./full_match/5/0x67659E818b0D5AE60194FD36873d5B8703a8C9f5/sources/NftStacking.sol
---------------------------------------------------------------------------------------------------*/
function availableRewards(address _staker) public view returns (uint256){ uint256 rewards = calculateRewards(_staker) + stakers[_staker].unclaimedRewards; return rewards; }
11,611,538
[ 1, 5802, 2443, 6062, 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, 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, 3639, 445, 2319, 17631, 14727, 12, 2867, 389, 334, 6388, 13, 1071, 1476, 1135, 261, 11890, 5034, 15329, 203, 5411, 2254, 5034, 283, 6397, 273, 4604, 17631, 14727, 24899, 334, 6388, 13, 397, 384, 581, 414, 63, 67, 334, 6388, 8009, 551, 80, 4581, 329, 17631, 14727, 31, 203, 5411, 327, 283, 6397, 31, 203, 3639, 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 ]
pragma solidity ^0.4.23; import 'openzeppelin-solidity/contracts/token/ERC721/ERC721.sol'; contract StarNotary is ERC721 { struct Star { string name; } string public constant name = "Joey Berger Notarized Star"; string public constant symbol = "JBNS"; mapping(uint256 => Star) public tokenIdToStarInfo; mapping(uint256 => uint256) public starsForSale; function createStar(string _name, uint256 _tokenId) public { require(bytes(_name).length > 0); Star memory newStar = Star(_name); tokenIdToStarInfo[_tokenId] = newStar; _mint(msg.sender, _tokenId); } function lookUptokenIdToStarInfo(uint256 _tokenId) public view returns (string) { //make sure star exists require(bytes(tokenIdToStarInfo[_tokenId].name).length > 0); return tokenIdToStarInfo[_tokenId].name; } function putStarUpForSale(uint256 _tokenId, uint256 _price) public { require(ownerOf(_tokenId) == msg.sender); starsForSale[_tokenId] = _price; } function buyStar(uint256 _tokenId) public payable { require(starsForSale[_tokenId] > 0); uint256 starCost = starsForSale[_tokenId]; address starOwner = ownerOf(_tokenId); require(msg.value >= starCost); _removeTokenFrom(starOwner, _tokenId); _addTokenTo(msg.sender, _tokenId); starOwner.transfer(starCost); if(msg.value > starCost) { msg.sender.transfer(msg.value - starCost); } starsForSale[_tokenId] = 0; } function exchangeStars(uint256 _firstUserTokenId, uint256 _secondUserTokenId) public { //make sure both stars exist require(bytes(tokenIdToStarInfo[_firstUserTokenId].name).length > 0); require(bytes(tokenIdToStarInfo[_secondUserTokenId].name).length > 0); //make sure token ids are unique require(_firstUserTokenId != _secondUserTokenId, "Token Ids are the same"); //store in memory the first user's star Star memory tempStar = tokenIdToStarInfo[_firstUserTokenId]; tokenIdToStarInfo[_firstUserTokenId] = tokenIdToStarInfo[_secondUserTokenId]; tokenIdToStarInfo[_secondUserTokenId] = tempStar; } function transferStar(address _transferAddress, uint256 _tokenId) public { //make sure star exists require(bytes(tokenIdToStarInfo[_tokenId].name).length > 0); //make sure star is not getting transferred to self require(_transferAddress != msg.sender); //make transfer _removeTokenFrom(msg.sender, _tokenId); _addTokenTo(_transferAddress, _tokenId); } }
make sure star existsmake sure star is not getting transferred to selfmake transfer
function transferStar(address _transferAddress, uint256 _tokenId) public { require(bytes(tokenIdToStarInfo[_tokenId].name).length > 0); require(_transferAddress != msg.sender); _removeTokenFrom(msg.sender, _tokenId); _addTokenTo(_transferAddress, _tokenId); }
12,968,444
[ 1, 6540, 3071, 10443, 1704, 6540, 3071, 10443, 353, 486, 8742, 906, 4193, 358, 365, 6540, 7412, 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, 7412, 18379, 12, 2867, 389, 13866, 1887, 16, 2254, 5034, 389, 2316, 548, 13, 1071, 288, 203, 3639, 2583, 12, 3890, 12, 2316, 28803, 18379, 966, 63, 67, 2316, 548, 8009, 529, 2934, 2469, 405, 374, 1769, 203, 3639, 2583, 24899, 13866, 1887, 480, 1234, 18, 15330, 1769, 203, 3639, 389, 4479, 1345, 1265, 12, 3576, 18, 15330, 16, 389, 2316, 548, 1769, 203, 3639, 389, 1289, 1345, 774, 24899, 13866, 1887, 16, 389, 2316, 548, 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 ]
./partial_match/3/0x03b0cEA1c39BDbe69e7Eef26B85627876E0516B3/sources/ECONTokenF.sol
wallet for team tokens (WALL)
address teamWallet = 0xD821DEadebaE498A4cfD2aD6C09f98e4a32466d0;
5,317,851
[ 1, 19177, 364, 5927, 2430, 261, 59, 4685, 13, 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, 3639, 1758, 5927, 16936, 273, 225, 374, 17593, 28, 5340, 1639, 2486, 12124, 41, 7616, 28, 37, 24, 8522, 40, 22, 69, 40, 26, 39, 5908, 74, 10689, 73, 24, 69, 1578, 24, 6028, 72, 20, 31, 7734, 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 ]
/* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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.21; /// @title Utility Functions for uint /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="3450555a5d515874585b5b44465d5a531a5b4653">[email&#160;protected]</a>> library MathUint { function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a); } function tolerantSub( uint a, uint b ) internal pure returns (uint c) { return (a >= b) ? a - b : 0; } /// @dev calculate the square of Coefficient of Variation (CV) /// https://en.wikipedia.org/wiki/Coefficient_of_variation function cvsquare( uint[] arr, uint scale ) internal pure returns (uint) { uint len = arr.length; require(len > 1); require(scale > 0); uint avg = 0; for (uint i = 0; i < len; i++) { avg += arr[i]; } avg = avg / len; if (avg == 0) { return 0; } uint cvs = 0; uint s; uint item; for (i = 0; i < len; i++) { item = arr[i]; s = item > avg ? item - avg : avg - item; cvs += mul(s, s); } return ((mul(mul(cvs, scale), scale) / avg) / avg) / (len - 1); } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @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 previousOwner, address indexed newOwner ); /// @dev The Ownable constructor sets the original `owner` of the contract /// to the sender. 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 ) onlyOwner public { require(newOwner != 0x0); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /// @title Claimable /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) onlyOwner public { require(newOwner != 0x0 && newOwner != owner); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() onlyPendingOwner public { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = 0x0; } } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title ERC20 Token Interface /// @dev see https://github.com/ethereum/EIPs/issues/20 /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1571747b7c707955797a7a65677c7b723b7a6772">[email&#160;protected]</a>> contract ERC20 { function balanceOf( address who ) view public returns (uint256); function allowance( address owner, address spender ) view public returns (uint256); function transfer( address to, uint256 value ) public returns (bool); function transferFrom( address from, address to, uint256 value ) public returns (bool); function approve( address spender, uint256 value ) public returns (bool); } /* Copyright 2017 Loopring Project Ltd (Loopring Foundation). 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. */ /// @title TokenTransferDelegate /// @dev Acts as a middle man to transfer ERC20 tokens on behalf of different /// versions of Loopring protocol to avoid ERC20 re-authorization. /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="6c080d020509002c0003031c1e05020b42031e0b">[email&#160;protected]</a>>. contract TokenTransferDelegate { event AddressAuthorized(address indexed addr, uint32 number); event AddressDeauthorized(address indexed addr, uint32 number); // The following map is used to keep trace of order fill and cancellation // history. mapping (bytes32 => uint) public cancelledOrFilled; // This map is used to keep trace of order&#39;s cancellation history. mapping (bytes32 => uint) public cancelled; // A map from address to its cutoff timestamp. mapping (address => uint) public cutoffs; // A map from address to its trading-pair cutoff timestamp. mapping (address => mapping (bytes20 => uint)) public tradingPairCutoffs; /// @dev Add a Loopring protocol address. /// @param addr A loopring protocol address. function authorizeAddress( address addr ) external; /// @dev Remove a Loopring protocol address. /// @param addr A loopring protocol address. function deauthorizeAddress( address addr ) external; function getLatestAuthorizedAddresses( uint max ) external view returns (address[] addresses); /// @dev Invoke ERC20 transferFrom method. /// @param token Address of token to transfer. /// @param from Address to transfer token from. /// @param to Address to transfer token to. /// @param value Amount of token to transfer. function transferToken( address token, address from, address to, uint value ) external; function batchTransferToken( address lrcTokenAddress, address minerFeeRecipient, uint8 walletSplitPercentage, bytes32[] batch ) external; function isAddressAuthorized( address addr ) public view returns (bool); function addCancelled(bytes32 orderHash, uint cancelAmount) external; function addCancelledOrFilled(bytes32 orderHash, uint cancelOrFillAmount) external; function setCutoffs(uint t) external; function setTradingPairCutoffs(bytes20 tokenPair, uint t) external; function checkCutoffsBatch(address[] owners, bytes20[] tradingPairs, uint[] validSince) external view; } /// @title An Implementation of TokenTransferDelegate. /// @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="fd999c93949891bd9192928d8f94939ad3928f9a">[email&#160;protected]</a>>. contract TokenTransferDelegateImpl is TokenTransferDelegate, Claimable { using MathUint for uint; struct AddressInfo { address previous; uint32 index; bool authorized; } mapping(address => AddressInfo) public addressInfos; address public latestAddress; modifier onlyAuthorized() { require(addressInfos[msg.sender].authorized); _; } /// @dev Disable default function. function () payable public { revert(); } function authorizeAddress( address addr ) onlyOwner external { AddressInfo storage addrInfo = addressInfos[addr]; if (addrInfo.index != 0) { // existing if (addrInfo.authorized == false) { // re-authorize addrInfo.authorized = true; emit AddressAuthorized(addr, addrInfo.index); } } else { address prev = latestAddress; if (prev == 0x0) { addrInfo.index = 1; addrInfo.authorized = true; } else { addrInfo.previous = prev; addrInfo.index = addressInfos[prev].index + 1; } addrInfo.authorized = true; latestAddress = addr; emit AddressAuthorized(addr, addrInfo.index); } } function deauthorizeAddress( address addr ) onlyOwner external { uint32 index = addressInfos[addr].index; if (index != 0) { addressInfos[addr].authorized = false; emit AddressDeauthorized(addr, index); } } function getLatestAuthorizedAddresses( uint max ) external view returns (address[] addresses) { addresses = new address[](max); address addr = latestAddress; AddressInfo memory addrInfo; uint count = 0; while (addr != 0x0 && count < max) { addrInfo = addressInfos[addr]; if (addrInfo.index == 0) { break; } addresses[count++] = addr; addr = addrInfo.previous; } } function transferToken( address token, address from, address to, uint value ) onlyAuthorized external { if (value > 0 && from != to && to != 0x0) { require( ERC20(token).transferFrom(from, to, value) ); } } function batchTransferToken( address lrcTokenAddress, address minerFeeRecipient, uint8 walletSplitPercentage, bytes32[] batch ) onlyAuthorized external { uint len = batch.length; require(len % 7 == 0); require(walletSplitPercentage > 0 && walletSplitPercentage < 100); ERC20 lrc = ERC20(lrcTokenAddress); for (uint i = 0; i < len; i += 7) { address owner = address(batch[i]); address prevOwner = address(batch[(i + len - 7) % len]); // Pay token to previous order, or to miner as previous order&#39;s // margin split or/and this order&#39;s margin split. ERC20 token = ERC20(address(batch[i + 1])); // Here batch[i + 2] has been checked not to be 0. if (owner != prevOwner) { require( token.transferFrom( owner, prevOwner, uint(batch[i + 2]) ) ); } // Miner pays LRx fee to order owner uint lrcReward = uint(batch[i + 4]); if (lrcReward != 0 && minerFeeRecipient != owner) { require( lrc.transferFrom( minerFeeRecipient, owner, lrcReward ) ); } // Split margin-split income between miner and wallet splitPayFee( token, uint(batch[i + 3]), owner, minerFeeRecipient, address(batch[i + 6]), walletSplitPercentage ); // Split LRx fee income between miner and wallet splitPayFee( lrc, uint(batch[i + 5]), owner, minerFeeRecipient, address(batch[i + 6]), walletSplitPercentage ); } } function isAddressAuthorized( address addr ) public view returns (bool) { return addressInfos[addr].authorized; } function splitPayFee( ERC20 token, uint fee, address owner, address minerFeeRecipient, address walletFeeRecipient, uint walletSplitPercentage ) internal { if (fee == 0) { return; } uint walletFee = (walletFeeRecipient == 0x0) ? 0 : fee.mul(walletSplitPercentage) / 100; uint minerFee = fee - walletFee; if (walletFee > 0 && walletFeeRecipient != owner) { require( token.transferFrom( owner, walletFeeRecipient, walletFee ) ); } if (minerFee > 0 && minerFeeRecipient != 0x0 && minerFeeRecipient != owner) { require( token.transferFrom( owner, minerFeeRecipient, minerFee ) ); } } function addCancelled(bytes32 orderHash, uint cancelAmount) onlyAuthorized external { cancelled[orderHash] = cancelled[orderHash].add(cancelAmount); } function addCancelledOrFilled(bytes32 orderHash, uint cancelOrFillAmount) onlyAuthorized external { cancelledOrFilled[orderHash] = cancelledOrFilled[orderHash].add(cancelOrFillAmount); } function setCutoffs(uint t) onlyAuthorized external { cutoffs[tx.origin] = t; } function setTradingPairCutoffs(bytes20 tokenPair, uint t) onlyAuthorized external { tradingPairCutoffs[tx.origin][tokenPair] = t; } function checkCutoffsBatch(address[] owners, bytes20[] tradingPairs, uint[] validSince) external view { uint len = owners.length; require(len == tradingPairs.length); require(len == validSince.length); for(uint i = 0; i < len; i++) { require(validSince[i] > tradingPairCutoffs[owners[i]][tradingPairs[i]]); // order trading pair is cut off require(validSince[i] > cutoffs[owners[i]]); // order is cut off } } }
/ @title ERC20 Token Interface @dev see https://github.com/ethereum/EIPs/issues/20 @author Daniel Wang - <<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1571747b7c707955797a7a65677c7b723b7a6772">[email&#160;protected]</a>>
contract ERC20 { function balanceOf( address who ) view public returns (uint256); function allowance( address owner, address spender ) view public returns (uint256); function transfer( address to, uint256 value ) public returns (bool); function transferFrom( address from, address to, uint256 value ) public returns (bool); function approve( address spender, uint256 value ) public returns (bool); Copyright 2017 Loopring Project Ltd (Loopring Foundation). }
2,021,980
[ 1, 19, 225, 4232, 39, 3462, 3155, 6682, 225, 2621, 2333, 2207, 6662, 18, 832, 19, 546, 822, 379, 19, 41, 18246, 19, 9618, 19, 3462, 225, 463, 28662, 292, 678, 539, 300, 2296, 69, 3897, 1546, 19, 20902, 17, 19062, 19, 80, 19, 3652, 17, 685, 9694, 6, 667, 1546, 972, 8522, 67, 3652, 14437, 501, 17, 8522, 3652, 1546, 27985, 4033, 9462, 70, 27, 71, 7301, 7235, 2539, 7235, 27, 69, 27, 69, 26, 4313, 4700, 71, 27, 70, 27, 4366, 70, 27, 69, 26, 4700, 22, 6441, 63, 3652, 10, 16874, 31, 1117, 65, 1757, 69, 9778, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 4232, 39, 3462, 288, 203, 565, 445, 11013, 951, 12, 203, 3639, 1758, 10354, 203, 3639, 262, 203, 3639, 1476, 203, 3639, 1071, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 1699, 1359, 12, 203, 3639, 1758, 3410, 16, 203, 3639, 1758, 17571, 264, 203, 3639, 262, 203, 3639, 1476, 203, 3639, 1071, 203, 3639, 1135, 261, 11890, 5034, 1769, 203, 565, 445, 7412, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 3639, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 1769, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 460, 203, 3639, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 1769, 203, 565, 445, 6617, 537, 12, 203, 3639, 1758, 17571, 264, 16, 203, 3639, 2254, 5034, 460, 203, 3639, 262, 203, 3639, 1071, 203, 3639, 1135, 261, 6430, 1769, 203, 225, 25417, 11015, 9720, 8022, 5420, 511, 4465, 261, 6452, 8022, 31289, 2934, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; /** * @dev Standard math utilities missing in the Solidity language. */ library MathUtil { /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract ReentrancyGuard { uint256 private _guardCounter; constructor () internal { _guardCounter = 1; } modifier nonReentrant() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } interface ICurveGauge { function deposit(uint256) external; function balanceOf(address) external view returns (uint256); function withdraw(uint256) external; function claim_rewards() external; function reward_tokens(uint256) external view returns(address);//v2 function rewarded_token() external view returns(address);//v1 } interface ICurveVoteEscrow { function create_lock(uint256, uint256) external; function increase_amount(uint256) external; function increase_unlock_time(uint256) external; function withdraw() external; function smart_wallet_checker() external view returns (address); } interface IWalletChecker { function check(address) external view returns (bool); } interface IVoting{ function vote(uint256, bool, bool) external; //voteId, support, executeIfDecided function getVote(uint256) external view returns(bool,bool,uint64,uint64,uint64,uint64,uint256,uint256,uint256,bytes memory); function vote_for_gauge_weights(address,uint256) external; } interface IMinter{ function mint(address) external; } interface IRegistry{ function get_registry() external view returns(address); function get_address(uint256 _id) external view returns(address); function gauge_controller() external view returns(address); function get_lp_token(address) external view returns(address); function get_gauges(address) external view returns(address[10] memory,uint128[10] memory); } interface IStaker{ function deposit(address, address) external; function withdraw(address) external; function withdraw(address, address, uint256) external; function withdrawAll(address, address) external; function createLock(uint256, uint256) external; function increaseAmount(uint256) external; function increaseTime(uint256) external; function release() external; function claimCrv(address) external returns (uint256); function claimRewards(address) external; function claimFees(address,address) external; function setStashAccess(address, bool) external; function vote(uint256,address,bool) external; function voteGaugeWeight(address,uint256) external; function balanceOfPool(address) external view returns (uint256); function operator() external view returns (address); function execute(address _to, uint256 _value, bytes calldata _data) external returns (bool, bytes memory); } interface IRewards{ function stake(address, uint256) external; function stakeFor(address, uint256) external; function withdraw(address, uint256) external; function exit(address) external; function getReward(address) external; function queueNewRewards(uint256) external; function notifyRewardAmount(uint256) external; function addExtraReward(address) external; function stakingToken() external returns (address); } interface IStash{ function stashRewards() external returns (bool); function processStash() external returns (bool); function claimRewards() external returns (bool); } interface IFeeDistro{ function claim() external; function token() external view returns(address); } interface ITokenMinter{ function mint(address,uint256) external; function burn(address,uint256) external; } interface IDeposit{ function isShutdown() external view returns(bool); function balanceOf(address _account) external view returns(uint256); function totalSupply() external view returns(uint256); function poolInfo(uint256) external view returns(address,address,address,address,address, bool); function rewardClaimed(uint256,address,uint256) external; function withdrawTo(uint256,uint256,address) external; function claimRewards(uint256,address) external returns(bool); function rewardArbitrator() external returns(address); function setGaugeRedirect(uint256 _pid) external returns(bool); } interface ICrvDeposit{ function deposit(uint256, bool) external; function lockIncentive() external view returns(uint256); } interface IRewardFactory{ function setAccess(address,bool) external; function CreateCrvRewards(uint256,address) external returns(address); function CreateTokenRewards(address,address,address) external returns(address); function activeRewardCount(address) external view returns(uint256); function addActiveReward(address,uint256) external returns(bool); function removeActiveReward(address,uint256) external returns(bool); } interface IStashFactory{ function CreateStash(uint256,address,address,uint256) external returns(address); } interface ITokenFactory{ function CreateDepositToken(address) external returns(address); } interface IPools{ function addPool(address _lptoken, address _gauge, uint256 _stashVersion) external returns(bool); function shutdownPool(uint256 _pid) external returns(bool); function poolInfo(uint256) external view returns(address,address,address,address,address,bool); function poolLength() external view returns (uint256); function gaugeMap(address) external view returns(bool); function setPoolManager(address _poolM) external; } interface IVestedEscrow{ function fund(address[] calldata _recipient, uint256[] calldata _amount) external returns(bool); } // File: @openzeppelin\contracts\math\SafeMath.sol 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\IERC20.sol 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\Address.sol 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\SafeERC20.sol 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: contracts\ExtraRewardStashV1.sol pragma solidity 0.6.12; contract ExtraRewardStashV1 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; uint256 private constant WEEK = 7 * 86400; uint256 private constant maxRewards = 8; uint256 public pid; address public operator; address public staker; address public gauge; address public rewardFactory; uint256 public historicalRewards = 0; struct TokenInfo { address token; address rewardAddress; uint256 lastActiveTime; } TokenInfo public tokenInfo; constructor(uint256 _pid, address _operator, address _staker, address _gauge, address _rFactory) public { pid = _pid; operator = _operator; staker = _staker; gauge = _gauge; rewardFactory = _rFactory; } function getName() external pure returns (string memory) { return "ExtraRewardStashV1"; } function setToken() internal { address token = ICurveGauge(gauge).rewarded_token(); if(token != address(0)){ //set token address tokenInfo.token = token; //create new reward contract (,,,address mainRewardContract,,) = IDeposit(operator).poolInfo(pid); address rewardContract = IRewardFactory(rewardFactory).CreateTokenRewards( token, mainRewardContract, address(this)); tokenInfo.rewardAddress = rewardContract; tokenInfo.lastActiveTime = block.timestamp; } } function claimRewards() external returns (bool) { require(msg.sender == operator, "!authorized"); //first time init if(tokenInfo.token == address(0)){ setToken(); } if(tokenInfo.token != address(0)){ uint256 before = IERC20(tokenInfo.token).balanceOf(staker); IDeposit(operator).claimRewards(pid,gauge); uint256 newbalance = IERC20(tokenInfo.token).balanceOf(staker); if(newbalance > before){ IStaker(staker).withdraw(tokenInfo.token); tokenInfo.lastActiveTime = block.timestamp; //make sure this pool is in active list, IRewardFactory(rewardFactory).addActiveReward(tokenInfo.token,pid); //check if other stashes are also active, and if so, send to arbitrator //do this here because processStash will have tokens from the arbitrator uint256 activeCount = IRewardFactory(rewardFactory).activeRewardCount(tokenInfo.token); if(activeCount > 1){ //send to arbitrator address arb = IDeposit(operator).rewardArbitrator(); if(arb != address(0)){ IERC20(tokenInfo.token).safeTransfer(arb, newbalance); } } }else{ //check if this reward has been inactive too long if(block.timestamp > tokenInfo.lastActiveTime + WEEK){ //set as inactive IRewardFactory(rewardFactory).removeActiveReward(tokenInfo.token,pid); }else{ //edge case around reward ending periods if(newbalance > 0){ // - recently active pool // - rewards claimed to staker contract via someone manually calling claim_rewards() on the gauge // - rewards ended before the above call, which claimed the last available tokens // - thus claimRewards doesnt see any new rewards, but there are rewards on the staker contract // - i think its safe to assume claim will be called within the timeframe, or else these rewards // will be unretrievable until some pool starts rewards again //claim the tokens IStaker(staker).withdraw(tokenInfo.token); uint256 activeCount = IRewardFactory(rewardFactory).activeRewardCount(tokenInfo.token); if(activeCount > 1){ //send to arbitrator address arb = IDeposit(operator).rewardArbitrator(); if(arb != address(0)){ IERC20(tokenInfo.token).safeTransfer(arb, newbalance); } } } } } } return true; } //pull assigned tokens from staker to stash function stashRewards() external pure returns(bool){ //stashRewards() is also called on deposit //so dont need to try withdrawing here for v1 // -> move withdraw() call to processStash() which is only called during reward claiming return true; } //send all extra rewards to their reward contracts function processStash() external returns(bool){ require(msg.sender == operator, "!authorized"); address token = tokenInfo.token; if(token == address(0)) return true; //send to rewards uint256 amount = IERC20(token).balanceOf(address(this)); if (amount > 0) { historicalRewards = historicalRewards.add(amount); //add to reward contract address rewards = tokenInfo.rewardAddress; if(rewards == address(0)) return true; IERC20(token).safeTransfer(rewards, amount); IRewards(rewards).queueNewRewards(amount); } return true; } } // File: contracts\ExtraRewardStashV2.sol pragma solidity 0.6.12; contract ExtraRewardStashV2 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); uint256 private constant maxRewards = 8; uint256 private constant WEEK = 7 * 86400; uint256 public immutable pid; address public immutable operator; address public immutable staker; address public immutable gauge; address public immutable rewardFactory; mapping(address => uint256) public historicalRewards; struct TokenInfo { address token; address rewardAddress; uint256 lastActiveTime; } uint256 public tokenCount; TokenInfo[maxRewards] public tokenInfo; constructor(uint256 _pid, address _operator, address _staker, address _gauge, address _rFactory) public { pid = _pid; operator = _operator; staker = _staker; gauge = _gauge; rewardFactory = _rFactory; } function getName() external pure returns (string memory) { return "ExtraRewardStashV2"; } //try claiming if there are reward tokens registered function claimRewards() external returns (bool) { require(msg.sender == operator, "!authorized"); //this is updateable in v2 gauges now so must check each time. checkForNewRewardTokens(); uint256 length = tokenCount; if(length > 0){ //get previous balances of all tokens uint256[] memory balances = new uint256[](length); for(uint256 i=0; i < length; i++){ balances[i] = IERC20(tokenInfo[i].token).balanceOf(staker); } //claim rewards on gauge for staker //booster will call for future proofing (cant assume anyone will always be able to call) IDeposit(operator).claimRewards(pid,gauge); for(uint256 i=0; i < length; i++){ address token = tokenInfo[i].token; uint256 newbalance = IERC20(token).balanceOf(staker); //stash if balance increased if(newbalance > balances[i]){ IStaker(staker).withdraw(token); tokenInfo[i].lastActiveTime = block.timestamp; //make sure this pool is in active list, IRewardFactory(rewardFactory).addActiveReward(token,pid); //check if other stashes are also active, and if so, send to arbitrator //do this here because processStash will have tokens from the arbitrator uint256 activeCount = IRewardFactory(rewardFactory).activeRewardCount(token); if(activeCount > 1){ //send to arbitrator address arb = IDeposit(operator).rewardArbitrator(); if(arb != address(0)){ IERC20(token).safeTransfer(arb, newbalance); } } }else{ //check if this reward has been inactive too long if(block.timestamp > tokenInfo[i].lastActiveTime + WEEK){ //set as inactive IRewardFactory(rewardFactory).removeActiveReward(token,pid); }else{ //edge case around reward ending periods if(newbalance > 0){ // - recently active pool // - rewards claimed to staker contract via a deposit/withdraw(or someone manually calling on the gauge) // - rewards ended before the deposit, thus deposit took the last available tokens // - thus claimRewards doesnt see any new rewards, but there are rewards on the staker contract // - i think its safe to assume claim will be called within the timeframe, or else these rewards // will be unretrievable until some pool starts rewards again //claim the tokens IStaker(staker).withdraw(token); uint256 activeCount = IRewardFactory(rewardFactory).activeRewardCount(token); if(activeCount > 1){ //send to arbitrator address arb = IDeposit(operator).rewardArbitrator(); if(arb != address(0)){ IERC20(token).safeTransfer(arb, newbalance); } } } } } } } return true; } //check if gauge rewards have changed function checkForNewRewardTokens() internal { for(uint256 i = 0; i < maxRewards; i++){ address token = ICurveGauge(gauge).reward_tokens(i); if (token == address(0)) { for (uint256 x = i; x < tokenCount; x++) { IRewardFactory(rewardFactory).removeActiveReward(tokenInfo[x].token,pid); } if (i != tokenCount) { tokenCount = i; } break; } setToken(i, token); } } //replace a token on token list function setToken(uint256 _tid, address _token) internal { TokenInfo storage t = tokenInfo[_tid]; address currentToken = t.token; if(currentToken != _token){ //set old as inactive IRewardFactory(rewardFactory).removeActiveReward(currentToken,pid); //set token address t.token = _token; //create new reward contract (,,,address mainRewardContract,,) = IDeposit(operator).poolInfo(pid); address rewardContract = IRewardFactory(rewardFactory).CreateTokenRewards( _token, mainRewardContract, address(this)); t.rewardAddress = rewardContract; t.lastActiveTime = 0; //do not set as active yet, wait for first earmark } } //pull assigned tokens from staker to stash function stashRewards() external returns(bool){ require(msg.sender == operator, "!authorized"); //after depositing/withdrawing, extra incentive tokens are transfered to the staking contract //need to pull them off and stash here. for(uint i=0; i < tokenCount; i++){ TokenInfo storage t = tokenInfo[i]; address token = t.token; if(token == address(0)) continue; //only stash if rewards are active if(block.timestamp <= t.lastActiveTime + WEEK){ uint256 before = IERC20(token).balanceOf(address(this)); IStaker(staker).withdraw(token); //check for multiple pools claiming same token uint256 activeCount = IRewardFactory(rewardFactory).activeRewardCount(token); if(activeCount > 1){ //take difference of before/after(only send new tokens) uint256 amount = IERC20(token).balanceOf(address(this)); amount = amount.sub(before); //send to arbitrator address arb = IDeposit(operator).rewardArbitrator(); if(arb != address(0)){ IERC20(token).safeTransfer(arb, amount); } } } } return true; } //send all extra rewards to their reward contracts function processStash() external returns(bool){ require(msg.sender == operator, "!authorized"); for(uint i=0; i < tokenCount; i++){ TokenInfo storage t = tokenInfo[i]; address token = t.token; if(token == address(0)) continue; uint256 amount = IERC20(token).balanceOf(address(this)); if (amount > 0) { historicalRewards[token] = historicalRewards[token].add(amount); if(token == crv){ //if crv, send back to booster to distribute IERC20(token).safeTransfer(operator, amount); continue; } //add to reward contract address rewards = t.rewardAddress; if(rewards == address(0)) continue; IERC20(token).safeTransfer(rewards, amount); IRewards(rewards).queueNewRewards(amount); } } return true; } } // File: contracts\ExtraRewardStashV3.sol pragma solidity 0.6.12; contract ExtraRewardStashV3 { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; address public constant crv = address(0xD533a949740bb3306d119CC777fa900bA034cd52); uint256 private constant maxRewards = 8; uint256 private constant WEEK = 7 * 86400; uint256 public immutable pid; address public immutable operator; address public immutable staker; address public immutable gauge; address public immutable rewardFactory; mapping(address => uint256) public historicalRewards; bool public hasRedirected; struct TokenInfo { address token; address rewardAddress; } uint256 public tokenCount; TokenInfo[maxRewards] public tokenInfo; constructor(uint256 _pid, address _operator, address _staker, address _gauge, address _rFactory) public { pid = _pid; operator = _operator; staker = _staker; gauge = _gauge; rewardFactory = _rFactory; } function getName() external pure returns (string memory) { return "ExtraRewardStashV3"; } //try claiming if there are reward tokens registered function claimRewards() external returns (bool) { require(msg.sender == operator, "!authorized"); //this is updateable from v2 gauges now so must check each time. checkForNewRewardTokens(); //make sure we're redirected if(!hasRedirected){ IDeposit(operator).setGaugeRedirect(pid); hasRedirected = true; } uint256 length = tokenCount; if(length > 0){ //claim rewards on gauge for staker //using reward_receiver so all rewards will be moved to this stash IDeposit(operator).claimRewards(pid,gauge); } return true; } //check if gauge rewards have changed function checkForNewRewardTokens() internal { for(uint256 i = 0; i < maxRewards; i++){ address token = ICurveGauge(gauge).reward_tokens(i); if (token == address(0)) { if (i != tokenCount) { tokenCount = i; } break; } setToken(i, token); } } //replace a token on token list function setToken(uint256 _tid, address _token) internal { TokenInfo storage t = tokenInfo[_tid]; address currentToken = t.token; if(currentToken != _token){ //set token address t.token = _token; //create new reward contract (,,,address mainRewardContract,,) = IDeposit(operator).poolInfo(pid); address rewardContract = IRewardFactory(rewardFactory).CreateTokenRewards( _token, mainRewardContract, address(this)); t.rewardAddress = rewardContract; } } //pull assigned tokens from staker to stash function stashRewards() external pure returns(bool){ //after depositing/withdrawing, extra incentive tokens are claimed //but from v3 this is default to off, and this stash is the reward receiver too. return true; } //send all extra rewards to their reward contracts function processStash() external returns(bool){ require(msg.sender == operator, "!authorized"); for(uint i=0; i < tokenCount; i++){ TokenInfo storage t = tokenInfo[i]; address token = t.token; if(token == address(0)) continue; uint256 amount = IERC20(token).balanceOf(address(this)); if (amount > 0) { historicalRewards[token] = historicalRewards[token].add(amount); if(token == crv){ //if crv, send back to booster to distribute IERC20(token).safeTransfer(operator, amount); continue; } //add to reward contract address rewards = t.rewardAddress; if(rewards == address(0)) continue; IERC20(token).safeTransfer(rewards, amount); IRewards(rewards).queueNewRewards(amount); } } return true; } } // File: contracts\StashFactory.sol pragma solidity 0.6.12; contract StashFactory { using Address for address; bytes4 private constant rewarded_token = 0x16fa50b1; //rewarded_token() bytes4 private constant reward_tokens = 0x54c49fe9; //reward_tokens(uint256) bytes4 private constant rewards_receiver = 0x01ddabf1; //rewards_receiver(address) address public operator; address public rewardFactory; constructor(address _operator, address _rewardFactory) public { operator = _operator; rewardFactory = _rewardFactory; } //Create a stash contract for the given gauge. //function calls are different depending on the version of curve gauges so determine which stash type is needed function CreateStash(uint256 _pid, address _gauge, address _staker, uint256 _stashVersion) external returns(address){ require(msg.sender == operator, "!authorized"); if(_stashVersion == uint256(3) && IsV3(_gauge)){ //v3 ExtraRewardStashV3 stash = new ExtraRewardStashV3(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); }else if(_stashVersion == uint256(1) && IsV1(_gauge)){ //v1 ExtraRewardStashV1 stash = new ExtraRewardStashV1(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); }else if(_stashVersion == uint256(2) && !IsV3(_gauge) && IsV2(_gauge)){ //v2 ExtraRewardStashV2 stash = new ExtraRewardStashV2(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); } bool isV1 = IsV1(_gauge); bool isV2 = IsV2(_gauge); bool isV3 = IsV3(_gauge); require(!isV1 && !isV2 && !isV3,"stash version mismatch"); return address(0); } function IsV1(address _gauge) private returns(bool){ bytes memory data = abi.encode(rewarded_token); (bool success,) = _gauge.call(data); return success; } function IsV2(address _gauge) private returns(bool){ bytes memory data = abi.encodeWithSelector(reward_tokens,uint256(0)); (bool success,) = _gauge.call(data); return success; } function IsV3(address _gauge) private returns(bool){ bytes memory data = abi.encodeWithSelector(rewards_receiver,address(0)); (bool success,) = _gauge.call(data); return success; } }
Create a stash contract for the given gauge.function calls are different depending on the version of curve gauges so determine which stash type is neededv3v1v2
function CreateStash(uint256 _pid, address _gauge, address _staker, uint256 _stashVersion) external returns(address){ require(msg.sender == operator, "!authorized"); if(_stashVersion == uint256(3) && IsV3(_gauge)){ ExtraRewardStashV3 stash = new ExtraRewardStashV3(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); ExtraRewardStashV1 stash = new ExtraRewardStashV1(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); ExtraRewardStashV2 stash = new ExtraRewardStashV2(_pid,operator,_staker,_gauge,rewardFactory); return address(stash); } bool isV1 = IsV1(_gauge); bool isV2 = IsV2(_gauge); bool isV3 = IsV3(_gauge); require(!isV1 && !isV2 && !isV3,"stash version mismatch"); return address(0); }
13,404,673
[ 1, 1684, 279, 23017, 6835, 364, 326, 864, 13335, 18, 915, 4097, 854, 3775, 8353, 603, 326, 1177, 434, 8882, 314, 6480, 281, 1427, 4199, 1492, 23017, 618, 353, 3577, 90, 23, 90, 21, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1788, 510, 961, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 75, 8305, 16, 1758, 389, 334, 6388, 16, 2254, 5034, 389, 25915, 1444, 13, 3903, 1135, 12, 2867, 15329, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3726, 16, 17528, 8434, 8863, 203, 203, 3639, 309, 24899, 25915, 1444, 422, 2254, 5034, 12, 23, 13, 597, 2585, 58, 23, 24899, 75, 8305, 3719, 95, 203, 5411, 13592, 17631, 1060, 510, 961, 58, 23, 23017, 273, 394, 13592, 17631, 1060, 510, 961, 58, 23, 24899, 6610, 16, 9497, 16, 67, 334, 6388, 16, 67, 75, 8305, 16, 266, 2913, 1733, 1769, 203, 5411, 327, 1758, 12, 25915, 1769, 203, 5411, 13592, 17631, 1060, 510, 961, 58, 21, 23017, 273, 394, 13592, 17631, 1060, 510, 961, 58, 21, 24899, 6610, 16, 9497, 16, 67, 334, 6388, 16, 67, 75, 8305, 16, 266, 2913, 1733, 1769, 203, 5411, 327, 1758, 12, 25915, 1769, 203, 5411, 13592, 17631, 1060, 510, 961, 58, 22, 23017, 273, 394, 13592, 17631, 1060, 510, 961, 58, 22, 24899, 6610, 16, 9497, 16, 67, 334, 6388, 16, 67, 75, 8305, 16, 266, 2913, 1733, 1769, 203, 5411, 327, 1758, 12, 25915, 1769, 203, 3639, 289, 203, 3639, 1426, 353, 58, 21, 273, 2585, 58, 21, 24899, 75, 8305, 1769, 203, 3639, 1426, 353, 58, 22, 273, 2585, 58, 22, 24899, 75, 8305, 1769, 203, 3639, 1426, 353, 58, 23, 273, 2585, 58, 23, 24899, 75, 8305, 1769, 203, 3639, 2583, 12, 5, 291, 58, 21, 597, 401, 291, 58, 22, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "./smartNFT_Interface.sol"; import "./ERC721_Interface.sol"; contract smartNFT_SC is ERC721, smartNFT { enum States { waitingForOwner, engagedWithOwner, waitingForUser, engagedWithUser } address manufacturer; //Address of manufacturer and owner of Smart Contract uint256 tokenCounter; //To give and genuine tokenID based on the number of tokens created. mapping(uint256 => address) ownerOfSD; //To khow who is the owner of an specific owner. mapping(address => uint256) tokenIDOfBCA; //To khow which is the tokenID associated to a Secure Device. mapping(address => uint256) ownerBalance; //To know how many tokens an owner has. mapping(address => uint256) userBalance; //To know how many tokens a user can use. struct Token_Struct { address approved; //Indicate who can transfer this token, 0 if no one. address SD; //Indicate the BCA of the Secure device associated to this token. address user; //Indicate who can use this secure device. States state; //If blocked (false) then token should be verified by new user or new owner. uint256 hashK_OD; //Hash of Key between owner and device. uint256 hashK_UD; //Hash of Key between user and device. uint256 dataEngagement; //Public Key to create K_OD or K_UD depending of token state. uint256 timestamp; //Last time device update its proof of live uint256 timeout; //timeout to verify a device error. } Token_Struct[] Secure_Token; constructor() { manufacturer = msg.sender; tokenCounter = 1; Secure_Token.push( Token_Struct( address(0), address(0), address(0), States.waitingForOwner, 0, 0, 0, 0, 0 ) ); } function createToken(address _addressSD, address _addressOwner) public virtual override returns (uint256) { //Check if the sender of message is from the manufacturer. require(manufacturer == msg.sender); //Check is Blockchain Account of Smart Device in the SmartContract if (tokenFromBCA(_addressSD) == 0) { //create a new token Secure_Token.push( Token_Struct( address(0), _addressSD, address(0), States.waitingForOwner, 0, 0, 0, block.timestamp, 86400 ) ); //Assigning a new tokenId uint256 _tokenId = tokenCounter++; tokenIDOfBCA[_addressSD] = _tokenId; //Assigning the owner ownerOfSD[_tokenId] = _addressOwner; ownerBalance[_addressOwner]++; //return tokenId obtained return (_tokenId); } else { //If the BCA already exists then return the _tokenId return (tokenFromBCA(_addressSD)); } } function setUser(uint256 _tokenId, address _addressUser) public virtual override { //Check if sender is the owner of token and the token state. require( (ownerOfSD[_tokenId] == msg.sender) && (Secure_Token[_tokenId].state >= States.engagedWithOwner) ); if ( (Secure_Token[_tokenId].timestamp + Secure_Token[_tokenId].timeout) > block.timestamp ) { //Only for ensure avoid overflow, for example in address 0. if (userBalance[Secure_Token[_tokenId].user] > 0) { //update the balance of token assigned to the old user userBalance[Secure_Token[_tokenId].user]--; } ////update the balance of token assigned to the new user userBalance[_addressUser]++; //Assign the new user to the token Secure_Token[_tokenId].user = _addressUser; //update the state of the token Secure_Token[_tokenId].state = States.waitingForUser; //Erase old key exchange data between device with old UserAssigned Secure_Token[_tokenId].dataEngagement = 0; Secure_Token[_tokenId].hashK_UD = 0; emit UserAssigned(_tokenId, _addressUser); } else { Secure_Token[_tokenId].user = address(0); emit TimeoutAlarm(_tokenId); } } function startOwnerEngagement( uint256 _tokenId, uint256 _dataEngagement, uint256 _hashK_O ) public virtual override { //Check if sender is the Owner of token and the State of token require(ownerOfSD[_tokenId] == msg.sender, "Is not owner"); if ( (Secure_Token[_tokenId].timestamp + Secure_Token[_tokenId].timeout) > block.timestamp ) { Secure_Token[_tokenId].dataEngagement = _dataEngagement; Secure_Token[_tokenId].hashK_OD = _hashK_O; } else { Secure_Token[_tokenId].user = address(0); emit TimeoutAlarm(_tokenId); } } function ownerEngagement(uint256 _hashK_D) public virtual override { uint256 _tokenId = tokenFromBCA(msg.sender); //Check if public key owner-device exist from tokenID of BCA sender require(Secure_Token[_tokenId].dataEngagement != 0, "does not exist"); require(Secure_Token[_tokenId].hashK_OD == _hashK_D, "does not exist"); require(Secure_Token[_tokenId].state == States.waitingForOwner, "does not exist"); //Erase PK_User-Device and update timestamp Secure_Token[_tokenId].dataEngagement = 0; Secure_Token[_tokenId].timestamp = block.timestamp; //update the state of token Secure_Token[_tokenId].state = States.engagedWithOwner; //Send a notification to User and Device emit OwnerEngaged(_tokenId); } function startUserEngagement( uint256 _tokenId, uint256 _dataEngagement, uint256 _hashK_U ) public virtual override { //Check if sender is the User of token and the State of token require(Secure_Token[_tokenId].user == msg.sender, "Sender is not user"); if ( (Secure_Token[_tokenId].timestamp + Secure_Token[_tokenId].timeout) > block.timestamp ) { Secure_Token[_tokenId].dataEngagement = _dataEngagement; Secure_Token[_tokenId].hashK_UD = _hashK_U; } else { Secure_Token[_tokenId].user = address(0); emit TimeoutAlarm(_tokenId); } } function userEngagement(uint256 _hashK_D) public virtual override { uint256 _tokenId = tokenFromBCA(msg.sender); //Check if public key user-device exist from tokenID of BCA sender require(Secure_Token[_tokenId].dataEngagement != 0, "does not exist"); require(Secure_Token[_tokenId].hashK_UD == _hashK_D, "does not exist"); require(Secure_Token[_tokenId].state == States.waitingForUser, "does not exist"); //Erase PK_User-Device and update timestamp Secure_Token[_tokenId].dataEngagement = 0; Secure_Token[_tokenId].timestamp = block.timestamp; //update the state of token Secure_Token[_tokenId].state = States.engagedWithUser; //Send a notification to User and Device emit UserEngaged(_tokenId); } function tokenFromBCA(address _addressSD) public view virtual override returns (uint256) { return (tokenIDOfBCA[_addressSD]); } function ownerOfFromBCA(address _addressSD) public view virtual override returns (address) { return (ownerOfSD[tokenIDOfBCA[_addressSD]]); } function userOf(uint256 _tokenId) public view virtual override returns (address) { return (Secure_Token[_tokenId].user); } function userOfFromBCA(address _addressSD) public view virtual override returns (address) { return (Secure_Token[tokenIDOfBCA[_addressSD]].user); } function userBalanceOf(address _addressUser) public view virtual override returns (uint256) { return (userBalance[_addressUser]); } function userBalanceOfAnOwner(address _addressUser, address _addressOwner) public view virtual override returns (uint256) { //TODO } function getInfoToken(uint256 _tokenId) public view returns ( address _BCA_OWNER, address _BCA_USER, address _BCA_SD, uint8 _state ) { _BCA_OWNER = ownerOfSD[_tokenId]; _BCA_USER = Secure_Token[_tokenId].user; _BCA_SD = Secure_Token[_tokenId].SD; if (Secure_Token[_tokenId].state == States.waitingForOwner) { _state = 0; } else if (Secure_Token[_tokenId].state == States.engagedWithOwner) { _state = 1; } else if (Secure_Token[_tokenId].state == States.waitingForUser) { _state = 2; } else { _state = 3; } } function getInfoTokenFromBCA(address _addressSD) public view returns ( address _BCA_OWNER, address _BCA_USER, uint256 _tokenId, uint8 _state ) { _tokenId = tokenIDOfBCA[_addressSD]; _BCA_OWNER = ownerOfSD[_tokenId]; _BCA_USER = Secure_Token[_tokenId].user; if (Secure_Token[_tokenId].state == States.waitingForOwner) { _state = 0; } else if (Secure_Token[_tokenId].state == States.engagedWithOwner) { _state = 1; } else if (Secure_Token[_tokenId].state == States.waitingForUser) { _state = 2; } else { _state = 3; } } function balanceOf(address _owner) public view virtual override returns (uint256) { return (ownerBalance[_owner]); } function ownerOf(uint256 _tokenId) public view virtual override returns (address) { return (ownerOfSD[_tokenId]); } function safeTransferFrom( address _from, address _to, uint256 _tokenId, bytes memory data ) public payable virtual override {} function safeTransferFrom( address _from, address _to, uint256 _tokenId ) public payable virtual override { transferFrom(_from, _to, _tokenId); } function transferFrom( address _from, address _to, uint256 _tokenId ) public payable virtual override { require( (ownerOfSD[_tokenId] == msg.sender) || (Secure_Token[_tokenId].approved == msg.sender) ); require(ownerOfSD[_tokenId] == _from); if ( (Secure_Token[_tokenId].timestamp + Secure_Token[_tokenId].timeout) > block.timestamp ) { ownerOfSD[_tokenId] = _to; ownerBalance[_from]--; ownerBalance[_to]++; //Secure_Token[_tokenId].approved = address(0); Secure_Token[_tokenId].user = address(0); Secure_Token[_tokenId].state = States.waitingForOwner; //Erase old key exchange data between device with old Owner Secure_Token[_tokenId].dataEngagement = 0; Secure_Token[_tokenId].hashK_UD = 0; Secure_Token[_tokenId].hashK_OD = 0; emit Transfer(_from, _to, _tokenId); } else { Secure_Token[_tokenId].user = address(0); emit TimeoutAlarm(_tokenId); } } function approve(address _approved, uint256 _tokenId) public payable virtual override {} function setApprovalForAll(address _operator, bool _approved) public virtual override {} function getApproved(uint256 _tokenId) public view virtual override returns (address) {} function isApprovedForAll(address _owner, address _operator) public view virtual override returns (bool) {} function checkTimeout(uint256 _tokenId) public virtual override returns (bool) { require(ownerOfSD[_tokenId] == msg.sender); if ( (Secure_Token[_tokenId].timestamp + Secure_Token[_tokenId].timeout) > block.timestamp ) { return true; } else { Secure_Token[_tokenId].user = address(0); emit TimeoutAlarm(_tokenId); return false; } } function updateTimestamp() public virtual override { Secure_Token[tokenFromBCA(msg.sender)].timestamp = block.timestamp; } function setTimeout(uint256 _tokenId, uint256 _timeout) public virtual override { require(ownerOfSD[_tokenId] == msg.sender); Secure_Token[_tokenId].timeout = _timeout; } }
To know how many tokens an owner has.
mapping(address => uint256) ownerBalance;
13,085,064
[ 1, 774, 5055, 3661, 4906, 2430, 392, 3410, 711, 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, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 3410, 13937, 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 ]
./partial_match/1/0xec6eD05f61E2e8230081eaD6362ebCf2AC505126/sources/Stogie.sol
accumulated cig per share
uint256 _acps = accCigPerShare;
15,723,388
[ 1, 8981, 5283, 690, 276, 360, 1534, 7433, 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, 3639, 2254, 5034, 389, 1077, 1121, 273, 4078, 39, 360, 2173, 9535, 31, 5397, 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 ]
// SPDX-License-Identifier: MIT copyright © 2021 gparap pragma solidity ^0.8.7; /** * @title ERC20_Token * @dev A token template of the ERC-20 Token Standard. */ contract ERC20_Token { string tokenName = "ERC-20 Token Name"; string tokenSymbol = "ERC"; uint8 tokenDecimals = 8; uint256 tokenSupply = 100000000; mapping(address => uint256) tokenBalance; mapping(address => mapping(address => uint)) tokenAllowance; event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval(address indexed _owner, address indexed _spender, uint256 _value); //returns the name of the token function name() public view returns (string memory) { return tokenName; } //returns the symbol of the token function symbol() public view returns (string memory) { return tokenSymbol; } //returns the number of decimals the token uses function decimals() public view returns (uint8) { return tokenDecimals; } //returns the total token supply function totalSupply() public view returns (uint256) { return tokenSupply; } //returns the account balance of another account with address _owner function balanceOf(address _owner) public view returns (uint256 balance) { return tokenBalance[_owner]; } //transfers _value amount of tokens to address _to function transfer(address _to, uint256 _value) public returns (bool success) { //the message caller’s account balance must have enough tokens to spend assert(tokenBalance[msg.sender] > _value); //fire the Transfer event emit Transfer(msg.sender, _to, _value); //handle token balance tokenBalance[msg.sender] -= _value; tokenBalance[_to] += _value; //token transaction is successful return true; } //transfers _value amount of tokens from address _from to address _to function transferFrom(address _from, address _to, uint256 _value) public returns (bool success) { //the message caller’s account balance must have enough tokens to spend assert(tokenBalance[_from] > _value); //the message caller’s account balance must have enough allowance tokens to spend assert(tokenAllowance[_from][msg.sender] > _value); //fire the Transfer event emit Transfer(msg.sender, _to, _value); //handle token balance tokenBalance[_from] -= _value; tokenBalance[_to] += _value; //handle token allowance tokenAllowance[_from][msg.sender] -= _value; //token transaction is successful return true; } //allows _spender to withdraw _value amount of tokens on behalf of the msg.sender function approve(address _spender, uint256 _value) public returns (bool success) { tokenAllowance[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); //token approval is successful return true; } //returns the amount that _spender is allowed to withdraw from _owner function allowance(address _owner, address _spender) public view returns (uint256 remaining) { return tokenAllowance[_owner][_spender]; } }
transfers _value amount of tokens to address _tothe message caller’s account balance must have enough tokens to spendfire the Transfer eventhandle token balancetoken transaction is successful
function transfer(address _to, uint256 _value) public returns (bool success) { assert(tokenBalance[msg.sender] > _value); emit Transfer(msg.sender, _to, _value); tokenBalance[msg.sender] -= _value; tokenBalance[_to] += _value; return true; }
12,634,586
[ 1, 2338, 18881, 389, 1132, 3844, 434, 2430, 358, 1758, 389, 3307, 580, 883, 4894, 163, 227, 252, 87, 2236, 11013, 1297, 1240, 7304, 2430, 358, 17571, 12179, 326, 12279, 871, 4110, 1147, 324, 4316, 71, 278, 969, 2492, 353, 6873, 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, 7412, 12, 2867, 389, 869, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 203, 3639, 1815, 12, 2316, 13937, 63, 3576, 18, 15330, 65, 405, 389, 1132, 1769, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 1132, 1769, 203, 540, 203, 3639, 1147, 13937, 63, 3576, 18, 15330, 65, 3947, 389, 1132, 31, 203, 3639, 1147, 13937, 63, 67, 869, 65, 1011, 389, 1132, 31, 203, 540, 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 ]
// Sources flattened with buidler v1.4.4 https://buidler.dev // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library UnstructuredStorage { function getStorageBool(bytes32 position) internal view returns (bool data) { assembly { data := sload(position) } } function getStorageAddress(bytes32 position) internal view returns (address data) { assembly { data := sload(position) } } function getStorageBytes32(bytes32 position) internal view returns (bytes32 data) { assembly { data := sload(position) } } function getStorageUint256(bytes32 position) internal view returns (uint256 data) { assembly { data := sload(position) } } function setStorageBool(bytes32 position, bool data) internal { assembly { sstore(position, data) } } function setStorageAddress(bytes32 position, address data) internal { assembly { sstore(position, data) } } function setStorageBytes32(bytes32 position, bytes32 data) internal { assembly { sstore(position, data) } } function setStorageUint256(bytes32 position, uint256 data) internal { assembly { sstore(position, data) } } } // File @aragon/os/contracts/acl/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACL { function initialize(address permissionsCreator) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IVaultRecoverable { event RecoverToVault(address indexed vault, address indexed token, uint256 amount); function transferToVault(address token) external; function allowRecoverability(address token) external view returns (bool); function getRecoveryVault() external view returns (address); } // File @aragon/os/contracts/kernel/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IKernelEvents { event SetApp(bytes32 indexed namespace, bytes32 indexed appId, address app); } // This should be an interface, but interfaces can't inherit yet :( contract IKernel is IKernelEvents, IVaultRecoverable { function acl() public view returns (IACL); function hasPermission(address who, address where, bytes32 what, bytes how) public view returns (bool); function setApp(bytes32 namespace, bytes32 appId, address app) public; function getApp(bytes32 namespace, bytes32 appId) public view returns (address); } // File @aragon/os/contracts/apps/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract AppStorage { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant KERNEL_POSITION = keccak256("aragonOS.appStorage.kernel"); bytes32 internal constant APP_ID_POSITION = keccak256("aragonOS.appStorage.appId"); */ bytes32 internal constant KERNEL_POSITION = 0x4172f0f7d2289153072b0a6ca36959e0cbe2efc3afe50fc81636caa96338137b; bytes32 internal constant APP_ID_POSITION = 0xd625496217aa6a3453eecb9c3489dc5a53e6c67b444329ea2b2cbc9ff547639b; function kernel() public view returns (IKernel) { return IKernel(KERNEL_POSITION.getStorageAddress()); } function appId() public view returns (bytes32) { return APP_ID_POSITION.getStorageBytes32(); } function setKernel(IKernel _kernel) internal { KERNEL_POSITION.setStorageAddress(address(_kernel)); } function setAppId(bytes32 _appId) internal { APP_ID_POSITION.setStorageBytes32(_appId); } } // File @aragon/os/contracts/acl/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ACLSyntaxSugar { function arr() internal pure returns (uint256[]) { return new uint256[](0); } function arr(bytes32 _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(bytes32 _a, bytes32 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a) internal pure returns (uint256[] r) { return arr(uint256(_a)); } function arr(address _a, address _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c); } function arr(address _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { return arr(uint256(_a), _b, _c, _d); } function arr(address _a, uint256 _b) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b)); } function arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), _c, _d, _e); } function arr(address _a, address _b, address _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(address _a, address _b, uint256 _c) internal pure returns (uint256[] r) { return arr(uint256(_a), uint256(_b), uint256(_c)); } function arr(uint256 _a) internal pure returns (uint256[] r) { r = new uint256[](1); r[0] = _a; } function arr(uint256 _a, uint256 _b) internal pure returns (uint256[] r) { r = new uint256[](2); r[0] = _a; r[1] = _b; } function arr(uint256 _a, uint256 _b, uint256 _c) internal pure returns (uint256[] r) { r = new uint256[](3); r[0] = _a; r[1] = _b; r[2] = _c; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d) internal pure returns (uint256[] r) { r = new uint256[](4); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; } function arr(uint256 _a, uint256 _b, uint256 _c, uint256 _d, uint256 _e) internal pure returns (uint256[] r) { r = new uint256[](5); r[0] = _a; r[1] = _b; r[2] = _c; r[3] = _d; r[4] = _e; } } contract ACLHelpers { function decodeParamOp(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 30)); } function decodeParamId(uint256 _x) internal pure returns (uint8 b) { return uint8(_x >> (8 * 31)); } function decodeParamsList(uint256 _x) internal pure returns (uint32 a, uint32 b, uint32 c) { a = uint32(_x); b = uint32(_x >> (8 * 4)); c = uint32(_x >> (8 * 8)); } } // File @aragon/os/contracts/common/[email protected] pragma solidity ^0.4.24; library Uint256Helpers { uint256 private constant MAX_UINT64 = uint64(-1); string private constant ERROR_NUMBER_TOO_BIG = "UINT64_NUMBER_TOO_BIG"; function toUint64(uint256 a) internal pure returns (uint64) { require(a <= MAX_UINT64, ERROR_NUMBER_TOO_BIG); return uint64(a); } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract TimeHelpers { using Uint256Helpers for uint256; /** * @dev Returns the current block number. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber() internal view returns (uint256) { return block.number; } /** * @dev Returns the current block number, converted to uint64. * Using a function rather than `block.number` allows us to easily mock the block number in * tests. */ function getBlockNumber64() internal view returns (uint64) { return getBlockNumber().toUint64(); } /** * @dev Returns the current timestamp. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp() internal view returns (uint256) { return block.timestamp; // solium-disable-line security/no-block-members } /** * @dev Returns the current timestamp, converted to uint64. * Using a function rather than `block.timestamp` allows us to easily mock it in * tests. */ function getTimestamp64() internal view returns (uint64) { return getTimestamp().toUint64(); } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Initializable is TimeHelpers { using UnstructuredStorage for bytes32; // keccak256("aragonOS.initializable.initializationBlock") bytes32 internal constant INITIALIZATION_BLOCK_POSITION = 0xebb05b386a8d34882b8711d156f463690983dc47815980fb82aeeff1aa43579e; string private constant ERROR_ALREADY_INITIALIZED = "INIT_ALREADY_INITIALIZED"; string private constant ERROR_NOT_INITIALIZED = "INIT_NOT_INITIALIZED"; modifier onlyInit { require(getInitializationBlock() == 0, ERROR_ALREADY_INITIALIZED); _; } modifier isInitialized { require(hasInitialized(), ERROR_NOT_INITIALIZED); _; } /** * @return Block number in which the contract was initialized */ function getInitializationBlock() public view returns (uint256) { return INITIALIZATION_BLOCK_POSITION.getStorageUint256(); } /** * @return Whether the contract has been initialized by the time of the current block */ function hasInitialized() public view returns (bool) { uint256 initializationBlock = getInitializationBlock(); return initializationBlock != 0 && getBlockNumber() >= initializationBlock; } /** * @dev Function to be called by top level contract after initialization has finished. */ function initialized() internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(getBlockNumber()); } /** * @dev Function to be called by top level contract after initialization to enable the contract * at a future block number rather than immediately. */ function initializedAt(uint256 _blockNumber) internal onlyInit { INITIALIZATION_BLOCK_POSITION.setStorageUint256(_blockNumber); } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Petrifiable is Initializable { // Use block UINT256_MAX (which should be never) as the initializable date uint256 internal constant PETRIFIED_BLOCK = uint256(-1); function isPetrified() public view returns (bool) { return getInitializationBlock() == PETRIFIED_BLOCK; } /** * @dev Function to be called by top level contract to prevent being initialized. * Useful for freezing base contracts when they're used behind proxies. */ function petrify() internal onlyInit { initializedAt(PETRIFIED_BLOCK); } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract Autopetrified is Petrifiable { constructor() public { // Immediately petrify base (non-proxy) instances of inherited contracts on deploy. // This renders them uninitializable (and unusable without a proxy). petrify(); } } // File @aragon/os/contracts/common/[email protected] pragma solidity ^0.4.24; library ConversionHelpers { string private constant ERROR_IMPROPER_LENGTH = "CONVERSION_IMPROPER_LENGTH"; function dangerouslyCastUintArrayToBytes(uint256[] memory _input) internal pure returns (bytes memory output) { // Force cast the uint256[] into a bytes array, by overwriting its length // Note that the bytes array doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 byteLength = _input.length * 32; assembly { output := _input mstore(output, byteLength) } } function dangerouslyCastBytesToUintArray(bytes memory _input) internal pure returns (uint256[] memory output) { // Force cast the bytes array into a uint256[], by overwriting its length // Note that the uint256[] doesn't need to be initialized as we immediately overwrite it // with the input and a new length. The input becomes invalid from this point forward. uint256 intsLength = _input.length / 32; require(_input.length == intsLength * 32, ERROR_IMPROPER_LENGTH); assembly { output := _input mstore(output, intsLength) } } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 internal constant REENTRANCY_MUTEX_POSITION = keccak256("aragonOS.reentrancyGuard.mutex"); */ bytes32 private constant REENTRANCY_MUTEX_POSITION = 0xe855346402235fdd185c890e68d2c4ecad599b88587635ee285bce2fda58dacb; string private constant ERROR_REENTRANT = "REENTRANCY_REENTRANT_CALL"; modifier nonReentrant() { // Ensure mutex is unlocked require(!REENTRANCY_MUTEX_POSITION.getStorageBool(), ERROR_REENTRANT); // Lock mutex before function call REENTRANCY_MUTEX_POSITION.setStorageBool(true); // Perform function call _; // Unlock mutex after function call REENTRANCY_MUTEX_POSITION.setStorageBool(false); } } // File @aragon/os/contracts/lib/token/[email protected] // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/a9f910d34f0ab33a1ae5e714f69f9596a02b4d91/contracts/token/ERC20/ERC20.sol pragma solidity ^0.4.24; /** * @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 ); } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // aragonOS and aragon-apps rely on address(0) to denote native ETH, in // contracts where both tokens and ETH are accepted contract EtherTokenConstant { address internal constant ETH = address(0); } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract IsContract { /* * NOTE: this should NEVER be used for authentication * (see pitfalls: https://github.com/fergarrui/ethereum-security/tree/master/contracts/extcodesize). * * This is only intended to be used as a sanity check that an address is actually a contract, * RATHER THAN an address not being a contract. */ function isContract(address _target) internal view returns (bool) { if (_target == address(0)) { return false; } uint256 size; assembly { size := extcodesize(_target) } return size > 0; } } // File @aragon/os/contracts/common/[email protected] // Inspired by AdEx (https://github.com/AdExNetwork/adex-protocol-eth/blob/b9df617829661a7518ee10f4cb6c4108659dd6d5/contracts/libs/SafeERC20.sol) // and 0x (https://github.com/0xProject/0x-monorepo/blob/737d1dc54d72872e24abce5a1dbe1b66d35fa21a/contracts/protocol/contracts/protocol/AssetProxy/ERC20Proxy.sol#L143) pragma solidity ^0.4.24; library SafeERC20 { // Before 0.5, solidity has a mismatch between `address.transfer()` and `token.transfer()`: // https://github.com/ethereum/solidity/issues/3544 bytes4 private constant TRANSFER_SELECTOR = 0xa9059cbb; string private constant ERROR_TOKEN_BALANCE_REVERTED = "SAFE_ERC_20_BALANCE_REVERTED"; string private constant ERROR_TOKEN_ALLOWANCE_REVERTED = "SAFE_ERC_20_ALLOWANCE_REVERTED"; function invokeAndCheckSuccess(address _addr, bytes memory _calldata) private returns (bool) { bool ret; assembly { let ptr := mload(0x40) // free memory pointer let success := call( gas, // forward all gas _addr, // address 0, // no value add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { // Check number of bytes returned from last function call switch returndatasize // No bytes returned: assume success case 0 { ret := 1 } // 32 bytes returned: check if non-zero case 0x20 { // Only return success if returned data was true // Already have output in ptr ret := eq(mload(ptr), 1) } // Not sure what was returned: don't mark as success default { } } } return ret; } function staticInvoke(address _addr, bytes memory _calldata) private view returns (bool, uint256) { bool success; uint256 ret; assembly { let ptr := mload(0x40) // free memory pointer success := staticcall( gas, // forward all gas _addr, // address add(_calldata, 0x20), // calldata start mload(_calldata), // calldata length ptr, // write output over free memory 0x20 // uint256 return ) if gt(success, 0) { ret := mload(ptr) } } return (success, ret); } /** * @dev Same as a standards-compliant ERC20.transfer() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransfer(ERC20 _token, address _to, uint256 _amount) internal returns (bool) { bytes memory transferCallData = abi.encodeWithSelector( TRANSFER_SELECTOR, _to, _amount ); return invokeAndCheckSuccess(_token, transferCallData); } /** * @dev Same as a standards-compliant ERC20.transferFrom() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeTransferFrom(ERC20 _token, address _from, address _to, uint256 _amount) internal returns (bool) { bytes memory transferFromCallData = abi.encodeWithSelector( _token.transferFrom.selector, _from, _to, _amount ); return invokeAndCheckSuccess(_token, transferFromCallData); } /** * @dev Same as a standards-compliant ERC20.approve() that never reverts (returns false). * Note that this makes an external call to the token. */ function safeApprove(ERC20 _token, address _spender, uint256 _amount) internal returns (bool) { bytes memory approveCallData = abi.encodeWithSelector( _token.approve.selector, _spender, _amount ); return invokeAndCheckSuccess(_token, approveCallData); } /** * @dev Static call into ERC20.balanceOf(). * Reverts if the call fails for some reason (should never fail). */ function staticBalanceOf(ERC20 _token, address _owner) internal view returns (uint256) { bytes memory balanceOfCallData = abi.encodeWithSelector( _token.balanceOf.selector, _owner ); (bool success, uint256 tokenBalance) = staticInvoke(_token, balanceOfCallData); require(success, ERROR_TOKEN_BALANCE_REVERTED); return tokenBalance; } /** * @dev Static call into ERC20.allowance(). * Reverts if the call fails for some reason (should never fail). */ function staticAllowance(ERC20 _token, address _owner, address _spender) internal view returns (uint256) { bytes memory allowanceCallData = abi.encodeWithSelector( _token.allowance.selector, _owner, _spender ); (bool success, uint256 allowance) = staticInvoke(_token, allowanceCallData); require(success, ERROR_TOKEN_ALLOWANCE_REVERTED); return allowance; } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract VaultRecoverable is IVaultRecoverable, EtherTokenConstant, IsContract { using SafeERC20 for ERC20; string private constant ERROR_DISALLOWED = "RECOVER_DISALLOWED"; string private constant ERROR_VAULT_NOT_CONTRACT = "RECOVER_VAULT_NOT_CONTRACT"; string private constant ERROR_TOKEN_TRANSFER_FAILED = "RECOVER_TOKEN_TRANSFER_FAILED"; /** * @notice Send funds to recovery Vault. This contract should never receive funds, * but in case it does, this function allows one to recover them. * @param _token Token balance to be sent to recovery vault. */ function transferToVault(address _token) external { require(allowRecoverability(_token), ERROR_DISALLOWED); address vault = getRecoveryVault(); require(isContract(vault), ERROR_VAULT_NOT_CONTRACT); uint256 balance; if (_token == ETH) { balance = address(this).balance; vault.transfer(balance); } else { ERC20 token = ERC20(_token); balance = token.staticBalanceOf(this); require(token.safeTransfer(vault, balance), ERROR_TOKEN_TRANSFER_FAILED); } emit RecoverToVault(vault, _token, balance); } /** * @dev By default deriving from AragonApp makes it recoverable * @param token Token address that would be recovered * @return bool whether the app allows the recovery */ function allowRecoverability(address token) public view returns (bool) { return true; } // Cast non-implemented interface to be public so we can use it internally function getRecoveryVault() public view returns (address); } // File @aragon/os/contracts/evmscript/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IEVMScriptExecutor { function execScript(bytes script, bytes input, address[] blacklist) external returns (bytes); function executorType() external pure returns (bytes32); } // File @aragon/os/contracts/evmscript/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRegistryConstants { /* Hardcoded constants to save gas bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = apmNamehash("evmreg"); */ bytes32 internal constant EVMSCRIPT_REGISTRY_APP_ID = 0xddbcfd564f642ab5627cf68b9b7d374fb4f8a36e941a75d89c87998cef03bd61; } interface IEVMScriptRegistry { function addScriptExecutor(IEVMScriptExecutor executor) external returns (uint id); function disableScriptExecutor(uint256 executorId) external; // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function getScriptExecutor(bytes script) public view returns (IEVMScriptExecutor); } // File @aragon/os/contracts/kernel/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract KernelAppIds { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_APP_ID = apmNamehash("kernel"); bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = apmNamehash("acl"); bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = apmNamehash("vault"); */ bytes32 internal constant KERNEL_CORE_APP_ID = 0x3b4bf6bf3ad5000ecf0f989d5befde585c6860fea3e574a4fab4c49d1c177d9c; bytes32 internal constant KERNEL_DEFAULT_ACL_APP_ID = 0xe3262375f45a6e2026b7e7b18c2b807434f2508fe1a2a3dfb493c7df8f4aad6a; bytes32 internal constant KERNEL_DEFAULT_VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; } contract KernelNamespaceConstants { /* Hardcoded constants to save gas bytes32 internal constant KERNEL_CORE_NAMESPACE = keccak256("core"); bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = keccak256("base"); bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = keccak256("app"); */ bytes32 internal constant KERNEL_CORE_NAMESPACE = 0xc681a85306374a5ab27f0bbc385296a54bcd314a1948b6cf61c4ea1bc44bb9f8; bytes32 internal constant KERNEL_APP_BASES_NAMESPACE = 0xf1f3eb40f5bc1ad1344716ced8b8a0431d840b5783aea1fd01786bc26f35ac0f; bytes32 internal constant KERNEL_APP_ADDR_NAMESPACE = 0xd6f028ca0e8edb4a8c9757ca4fdccab25fa1e0317da1188108f7d2dee14902fb; } // File @aragon/os/contracts/evmscript/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract EVMScriptRunner is AppStorage, Initializable, EVMScriptRegistryConstants, KernelNamespaceConstants { string private constant ERROR_EXECUTOR_UNAVAILABLE = "EVMRUN_EXECUTOR_UNAVAILABLE"; string private constant ERROR_PROTECTED_STATE_MODIFIED = "EVMRUN_PROTECTED_STATE_MODIFIED"; /* This is manually crafted in assembly string private constant ERROR_EXECUTOR_INVALID_RETURN = "EVMRUN_EXECUTOR_INVALID_RETURN"; */ event ScriptResult(address indexed executor, bytes script, bytes input, bytes returnData); function getEVMScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { return IEVMScriptExecutor(getEVMScriptRegistry().getScriptExecutor(_script)); } function getEVMScriptRegistry() public view returns (IEVMScriptRegistry) { address registryAddr = kernel().getApp(KERNEL_APP_ADDR_NAMESPACE, EVMSCRIPT_REGISTRY_APP_ID); return IEVMScriptRegistry(registryAddr); } function runScript(bytes _script, bytes _input, address[] _blacklist) internal isInitialized protectState returns (bytes) { IEVMScriptExecutor executor = getEVMScriptExecutor(_script); require(address(executor) != address(0), ERROR_EXECUTOR_UNAVAILABLE); bytes4 sig = executor.execScript.selector; bytes memory data = abi.encodeWithSelector(sig, _script, _input, _blacklist); bytes memory output; assembly { let success := delegatecall( gas, // forward all gas executor, // address add(data, 0x20), // calldata start mload(data), // calldata length 0, // don't write output (we'll handle this ourselves) 0 // don't write output ) output := mload(0x40) // free mem ptr get switch success case 0 { // If the call errored, forward its full error data returndatacopy(output, 0, returndatasize) revert(output, returndatasize) } default { switch gt(returndatasize, 0x3f) case 0 { // Need at least 0x40 bytes returned for properly ABI-encoded bytes values, // revert with "EVMRUN_EXECUTOR_INVALID_RETURN" // See remix: doing a `revert("EVMRUN_EXECUTOR_INVALID_RETURN")` always results in // this memory layout mstore(output, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(output, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(output, 0x24), 0x000000000000000000000000000000000000000000000000000000000000001e) // reason length mstore(add(output, 0x44), 0x45564d52554e5f4558454355544f525f494e56414c49445f52455455524e0000) // reason revert(output, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Copy result // // Needs to perform an ABI decode for the expected `bytes` return type of // `executor.execScript()` as solidity will automatically ABI encode the returned bytes as: // [ position of the first dynamic length return value = 0x20 (32 bytes) ] // [ output length (32 bytes) ] // [ output content (N bytes) ] // // Perform the ABI decode by ignoring the first 32 bytes of the return data let copysize := sub(returndatasize, 0x20) returndatacopy(output, 0x20, copysize) mstore(0x40, add(output, copysize)) // free mem ptr set } } } emit ScriptResult(address(executor), _script, _input, output); return output; } modifier protectState { address preKernel = address(kernel()); bytes32 preAppId = appId(); _; // exec require(address(kernel()) == preKernel, ERROR_PROTECTED_STATE_MODIFIED); require(appId() == preAppId, ERROR_PROTECTED_STATE_MODIFIED); } } // File @aragon/os/contracts/apps/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; // Contracts inheriting from AragonApp are, by default, immediately petrified upon deployment so // that they can never be initialized. // Unless overriden, this behaviour enforces those contracts to be usable only behind an AppProxy. // ReentrancyGuard, EVMScriptRunner, and ACLSyntaxSugar are not directly used by this contract, but // are included so that they are automatically usable by subclassing contracts contract AragonApp is AppStorage, Autopetrified, VaultRecoverable, ReentrancyGuard, EVMScriptRunner, ACLSyntaxSugar { string private constant ERROR_AUTH_FAILED = "APP_AUTH_FAILED"; modifier auth(bytes32 _role) { require(canPerform(msg.sender, _role, new uint256[](0)), ERROR_AUTH_FAILED); _; } modifier authP(bytes32 _role, uint256[] _params) { require(canPerform(msg.sender, _role, _params), ERROR_AUTH_FAILED); _; } /** * @dev Check whether an action can be performed by a sender for a particular role on this app * @param _sender Sender of the call * @param _role Role on this app * @param _params Permission params for the role * @return Boolean indicating whether the sender has the permissions to perform the action. * Always returns false if the app hasn't been initialized yet. */ function canPerform(address _sender, bytes32 _role, uint256[] _params) public view returns (bool) { if (!hasInitialized()) { return false; } IKernel linkedKernel = kernel(); if (address(linkedKernel) == address(0)) { return false; } return linkedKernel.hasPermission( _sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params) ); } /** * @dev Get the recovery vault for the app * @return Recovery vault address for the app */ function getRecoveryVault() public view returns (address) { // Funds recovery via a vault is only available when used with a kernel return kernel().getRecoveryVault(); // if kernel is not set, it will revert } } // File @aragon/os/contracts/common/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IForwarder { function isForwarder() external pure returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function canForward(address sender, bytes evmCallScript) public view returns (bool); // TODO: this should be external // See https://github.com/ethereum/solidity/issues/4832 function forward(bytes evmCallScript) public; } // File @aragon/os/contracts/lib/math/[email protected] // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted to use pragma ^0.4.24 and satisfy our linter rules pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { string private constant ERROR_ADD_OVERFLOW = "MATH_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH_DIV_ZERO"; /** * @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 = _a * _b; require(c / _a == _b, ERROR_MUL_OVERFLOW); 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, ERROR_DIV_ZERO); // 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, ERROR_SUB_UNDERFLOW); 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, ERROR_ADD_OVERFLOW); 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, ERROR_DIV_ZERO); return a % b; } } // File @aragon/apps-shared-minime/contracts/[email protected] pragma solidity ^0.4.24; /// @dev The token controller contract must implement these functions interface ITokenController { /// @notice Called when `_owner` sends ether to the MiniMe Token contract /// @param _owner The address that sent the ether to create tokens /// @return True if the ether is accepted, false if it throws function proxyPayment(address _owner) external payable returns(bool); /// @notice Notifies the controller about a token transfer allowing the /// controller to react if desired /// @param _from The origin of the transfer /// @param _to The destination of the transfer /// @param _amount The amount of the transfer /// @return False if the controller does not authorize the transfer function onTransfer(address _from, address _to, uint _amount) external returns(bool); /// @notice Notifies the controller about an approval allowing the /// controller to react if desired /// @param _owner The address that calls `approve()` /// @param _spender The spender in the `approve()` call /// @param _amount The amount in the `approve()` call /// @return False if the controller does not authorize the approval function onApprove(address _owner, address _spender, uint _amount) external returns(bool); } // File @aragon/apps-shared-minime/contracts/[email protected] pragma solidity ^0.4.24; /* Copyright 2016, Jordi Baylina This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program 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 General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ /// @title MiniMeToken Contract /// @author Jordi Baylina /// @dev This token contract's goal is to make it easy for anyone to clone this /// token using the token distribution at a given block, this will allow DAO's /// and DApps to upgrade their features in a decentralized manner without /// affecting the original token /// @dev It is ERC20 compliant, but still needs to under go further testing. contract Controlled { /// @notice The address of the controller is the only address that can call /// a function with this modifier modifier onlyController { require(msg.sender == controller); _; } address public controller; function Controlled() public { controller = msg.sender;} /// @notice Changes the controller of the contract /// @param _newController The new controller of the contract function changeController(address _newController) onlyController public { controller = _newController; } } contract ApproveAndCallFallBack { function receiveApproval( address from, uint256 _amount, address _token, bytes _data ) public; } /// @dev The actual token contract, the default controller is the msg.sender /// that deploys the contract, so usually this token will be deployed by a /// token controller contract, which Giveth will call a "Campaign" contract MiniMeToken is Controlled { string public name; //The Token's name: e.g. DigixDAO Tokens uint8 public decimals; //Number of decimals of the smallest unit string public symbol; //An identifier: e.g. REP string public version = "MMT_0.1"; //An arbitrary versioning scheme /// @dev `Checkpoint` is the structure that attaches a block number to a /// given value, the block number attached is the one that last changed the /// value struct Checkpoint { // `fromBlock` is the block number that the value was generated from uint128 fromBlock; // `value` is the amount of tokens at a specific block number uint128 value; } // `parentToken` is the Token address that was cloned to produce this token; // it will be 0x0 for a token that was not cloned MiniMeToken public parentToken; // `parentSnapShotBlock` is the block number from the Parent Token that was // used to determine the initial distribution of the Clone Token uint public parentSnapShotBlock; // `creationBlock` is the block number that the Clone Token was created uint public creationBlock; // `balances` is the map that tracks the balance of each address, in this // contract when the balance changes the block number that the change // occurred is also included in the map mapping (address => Checkpoint[]) balances; // `allowed` tracks any extra transfer rights as in all ERC20 tokens mapping (address => mapping (address => uint256)) allowed; // Tracks the history of the `totalSupply` of the token Checkpoint[] totalSupplyHistory; // Flag that determines if the token is transferable or not. bool public transfersEnabled; // The factory used to create new clone tokens MiniMeTokenFactory public tokenFactory; //////////////// // Constructor //////////////// /// @notice Constructor to create a MiniMeToken /// @param _tokenFactory The address of the MiniMeTokenFactory contract that /// will create the Clone token contracts, the token factory needs to be /// deployed first /// @param _parentToken Address of the parent token, set to 0x0 if it is a /// new token /// @param _parentSnapShotBlock Block of the parent token that will /// determine the initial distribution of the clone token, set to 0 if it /// is a new token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred function MiniMeToken( MiniMeTokenFactory _tokenFactory, MiniMeToken _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = _tokenFactory; name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = _parentToken; parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } /////////////////// // ERC20 Methods /////////////////// /// @notice Send `_amount` tokens to `_to` from `msg.sender` /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return Whether the transfer was successful or not function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); return doTransfer(msg.sender, _to, _amount); } /// @notice Send `_amount` tokens to `_to` from `_from` on the condition it /// is approved by `_from` /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function transferFrom(address _from, address _to, uint256 _amount) public returns (bool success) { // The controller of this contract can move tokens around at will, // this is important to recognize! Confirm that you trust the // controller of this contract, which in most situations should be // another open source smart contract or 0x0 if (msg.sender != controller) { require(transfersEnabled); // The standard ERC 20 transferFrom functionality if (allowed[_from][msg.sender] < _amount) return false; allowed[_from][msg.sender] -= _amount; } return doTransfer(_from, _to, _amount); } /// @dev This is the actual transfer function in the token contract, it can /// only be called by other functions in this contract. /// @param _from The address holding the tokens being transferred /// @param _to The address of the recipient /// @param _amount The amount of tokens to be transferred /// @return True if the transfer was successful function doTransfer(address _from, address _to, uint _amount) internal returns(bool) { if (_amount == 0) { return true; } require(parentSnapShotBlock < block.number); // Do not allow transfer to 0x0 or the token contract itself require((_to != 0) && (_to != address(this))); // If the amount being transfered is more than the balance of the // account the transfer returns false var previousBalanceFrom = balanceOfAt(_from, block.number); if (previousBalanceFrom < _amount) { return false; } // Alerts the token controller of the transfer if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onTransfer(_from, _to, _amount) == true); } // First update the balance array with the new value for the address // sending the tokens updateValueAtNow(balances[_from], previousBalanceFrom - _amount); // Then update the balance array with the new value for the address // receiving the tokens var previousBalanceTo = balanceOfAt(_to, block.number); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(balances[_to], previousBalanceTo + _amount); // An event to make the transfer easy to find on the blockchain Transfer(_from, _to, _amount); return true; } /// @param _owner The address that's balance is being requested /// @return The balance of `_owner` at the current block function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } /// @notice `msg.sender` approves `_spender` to spend `_amount` tokens on /// its behalf. This is a modified version of the ERC20 approve function /// to be a little bit safer /// @param _spender The address of the account able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the approval was successful function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); // 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((_amount == 0) || (allowed[msg.sender][_spender] == 0)); // Alerts the token controller of the approve function call if (isContract(controller)) { // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).onApprove(msg.sender, _spender, _amount) == true); } allowed[msg.sender][_spender] = _amount; Approval(msg.sender, _spender, _amount); return true; } /// @dev This function makes it easy to read the `allowed[]` map /// @param _owner The address of the account that owns the token /// @param _spender The address of the account able to transfer the tokens /// @return Amount of remaining tokens of _owner that _spender is allowed /// to spend function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } /// @notice `msg.sender` approves `_spender` to send `_amount` tokens on /// its behalf, and then a function is triggered in the contract that is /// being approved, `_spender`. This allows users to use their tokens to /// interact with contracts in one function call instead of two /// @param _spender The address of the contract able to transfer the tokens /// @param _amount The amount of tokens to be approved for transfer /// @return True if the function call was successful function approveAndCall(ApproveAndCallFallBack _spender, uint256 _amount, bytes _extraData) public returns (bool success) { require(approve(_spender, _amount)); _spender.receiveApproval( msg.sender, _amount, this, _extraData ); return true; } /// @dev This function makes it easy to get the total number of tokens /// @return The total number of tokens function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } //////////////// // Query balance and totalSupply in History //////////////// /// @dev Queries the balance of `_owner` at a specific `_blockNumber` /// @param _owner The address from which the balance will be retrieved /// @param _blockNumber The block number when the balance is queried /// @return The balance at `_blockNumber` function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { // These next few lines are used when the balance of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.balanceOfAt` be queried at the // genesis block for that token as this contains initial balance of // this token if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); } else { // Has no parent return 0; } // This will return the expected balance during normal situations } else { return getValueAt(balances[_owner], _blockNumber); } } /// @notice Total amount of tokens at a specific `_blockNumber`. /// @param _blockNumber The block number when the totalSupply is queried /// @return The total amount of tokens at `_blockNumber` function totalSupplyAt(uint _blockNumber) public constant returns(uint) { // These next few lines are used when the totalSupply of the token is // requested before a check point was ever created for this token, it // requires that the `parentToken.totalSupplyAt` be queried at the // genesis block for this token as that contains totalSupply of this // token at this block number. if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); } else { return 0; } // This will return the expected totalSupply during normal situations } else { return getValueAt(totalSupplyHistory, _blockNumber); } } //////////////// // Clone Token Method //////////////// /// @notice Creates a new clone token with the initial distribution being /// this token at `_snapshotBlock` /// @param _cloneTokenName Name of the clone token /// @param _cloneDecimalUnits Number of decimals of the smallest unit /// @param _cloneTokenSymbol Symbol of the clone token /// @param _snapshotBlock Block when the distribution of the parent token is /// copied to set the initial distribution of the new clone token; /// if the block is zero than the actual block, the current block is used /// @param _transfersEnabled True if transfers are allowed in the clone /// @return The address of the new MiniMeToken Contract function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(MiniMeToken) { uint256 snapshot = _snapshotBlock == 0 ? block.number - 1 : _snapshotBlock; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, snapshot, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain NewCloneToken(address(cloneToken), snapshot); return cloneToken; } //////////////// // Generate and destroy tokens //////////////// /// @notice Generates `_amount` tokens that are assigned to `_owner` /// @param _owner The address that will be assigned the new tokens /// @param _amount The quantity of tokens generated /// @return True if the tokens are generated correctly function generateTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply + _amount >= curTotalSupply); // Check for overflow uint previousBalanceTo = balanceOf(_owner); require(previousBalanceTo + _amount >= previousBalanceTo); // Check for overflow updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); Transfer(0, _owner, _amount); return true; } /// @notice Burns `_amount` tokens from `_owner` /// @param _owner The address that will lose the tokens /// @param _amount The quantity of tokens to burn /// @return True if the tokens are burned correctly function destroyTokens(address _owner, uint _amount) onlyController public returns (bool) { uint curTotalSupply = totalSupply(); require(curTotalSupply >= _amount); uint previousBalanceFrom = balanceOf(_owner); require(previousBalanceFrom >= _amount); updateValueAtNow(totalSupplyHistory, curTotalSupply - _amount); updateValueAtNow(balances[_owner], previousBalanceFrom - _amount); Transfer(_owner, 0, _amount); return true; } //////////////// // Enable tokens transfers //////////////// /// @notice Enables token holders to transfer their tokens freely if true /// @param _transfersEnabled True if transfers are allowed in the clone function enableTransfers(bool _transfersEnabled) onlyController public { transfersEnabled = _transfersEnabled; } //////////////// // Internal helper functions to query and set a value in a snapshot array //////////////// /// @dev `getValueAt` retrieves the number of tokens at a given block number /// @param checkpoints The history of values being queried /// @param _block The block number to retrieve the value at /// @return The number of tokens being queried function getValueAt(Checkpoint[] storage checkpoints, uint _block) constant internal returns (uint) { if (checkpoints.length == 0) return 0; // Shortcut for the actual value if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; // Binary search of the value in the array uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1) / 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; } else { max = mid-1; } } return checkpoints[min].value; } /// @dev `updateValueAtNow` used to update the `balances` map and the /// `totalSupplyHistory` /// @param checkpoints The history of data being updated /// @param _value The new number of tokens function updateValueAtNow(Checkpoint[] storage checkpoints, uint _value) internal { if ((checkpoints.length == 0) || (checkpoints[checkpoints.length - 1].fromBlock < block.number)) { Checkpoint storage newCheckPoint = checkpoints[checkpoints.length++]; newCheckPoint.fromBlock = uint128(block.number); newCheckPoint.value = uint128(_value); } else { Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length - 1]; oldCheckPoint.value = uint128(_value); } } /// @dev Internal function to determine if an address is a contract /// @param _addr The address being queried /// @return True if `_addr` is a contract function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } /// @dev Helper function to return a min betwen the two uints function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } /// @notice The fallback function: If the contract's controller has not been /// set to 0, then the `proxyPayment` method is called which relays the /// ether and creates tokens as described in the token controller contract function () external payable { require(isContract(controller)); // Adding the ` == true` makes the linter shut up so... require(ITokenController(controller).proxyPayment.value(msg.value)(msg.sender) == true); } ////////// // Safety Methods ////////// /// @notice This method can be used by the controller to extract mistakenly /// sent tokens to this contract. /// @param _token The address of the token contract that you want to recover /// set to 0 in case you want to extract ether. function claimTokens(address _token) onlyController public { if (_token == 0x0) { controller.transfer(this.balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); ClaimedTokens(_token, controller, balance); } //////////////// // Events //////////////// event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); event Transfer(address indexed _from, address indexed _to, uint256 _amount); event NewCloneToken(address indexed _cloneToken, uint _snapshotBlock); event Approval( address indexed _owner, address indexed _spender, uint256 _amount ); } //////////////// // MiniMeTokenFactory //////////////// /// @dev This contract is used to generate clone contracts from a contract. /// In solidity this is the way to create a contract from a contract of the /// same class contract MiniMeTokenFactory { /// @notice Update the DApp by creating a new token with new functionalities /// the msg.sender becomes the controller of this clone token /// @param _parentToken Address of the token being cloned /// @param _snapshotBlock Block of the parent token that will /// determine the initial distribution of the clone token /// @param _tokenName Name of the new token /// @param _decimalUnits Number of decimals of the new token /// @param _tokenSymbol Token Symbol for the new token /// @param _transfersEnabled If true, tokens will be able to be transferred /// @return The address of the new token contract function createCloneToken( MiniMeToken _parentToken, uint _snapshotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public returns (MiniMeToken) { MiniMeToken newToken = new MiniMeToken( this, _parentToken, _snapshotBlock, _tokenName, _decimalUnits, _tokenSymbol, _transfersEnabled ); newToken.changeController(msg.sender); return newToken; } } // File contracts/TokenManagerHook.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; /** * @dev When creating a subcontract, we recommend overriding the _internal_ functions that you want to hook. */ contract TokenManagerHook is ReentrancyGuard { using UnstructuredStorage for bytes32; /* Hardcoded constants to save gas bytes32 public constant TOKEN_MANAGER_POSITION = keccak256("hookedTokenManager.tokenManagerHook.tokenManager"); */ bytes32 private constant TOKEN_MANAGER_POSITION = 0x5c513b2347f66d33af9d68f4a0ed7fbb73ce364889b2af7f3ee5764440da6a8a; modifier onlyTokenManager () { require (TOKEN_MANAGER_POSITION.getStorageAddress() == msg.sender, "Hooks must be called from Token Manager"); _; } /* * @dev Called when this contract has been included as a Token Manager hook * @param _hookId The position in which the hook is going to be called * @param _token The token controlled by the Token Manager */ function onRegisterAsHook(uint256 _hookId, address _token) external nonReentrant { require(TOKEN_MANAGER_POSITION.getStorageAddress() == 0x0, "Hook already registered by Token Manager"); TOKEN_MANAGER_POSITION.setStorageAddress(msg.sender); _onRegisterAsHook(msg.sender, _hookId, _token); } /* * @dev Called when this hook is being removed from the Token Manager * @param _hookId The position in which the hook is going to be called * @param _token The token controlled by the Token Manager */ function onRevokeAsHook(uint256 _hookId, address _token) external onlyTokenManager nonReentrant { _onRevokeAsHook(msg.sender, _hookId, _token); } /* * @dev Notifies the hook about a token transfer allowing the hook to react if desired. It should return * true if left unimplemented, otherwise it will prevent some functions in the TokenManager from * executing successfully. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyTokenManager nonReentrant returns (bool) { return _onTransfer(_from, _to, _amount); } /* * @dev Notifies the hook about an approval allowing the hook to react if desired. It should return * true if left unimplemented, otherwise it will prevent some functions in the TokenManager from * executing successfully. * @param _holder The account that is allowing to spend * @param _spender The account that is allowed to spend * @param _amount The amount being allowed */ function onApprove(address _holder, address _spender, uint _amount) external onlyTokenManager nonReentrant returns (bool) { return _onApprove(_holder, _spender, _amount); } // Function to override if necessary: function _onRegisterAsHook(address _tokenManager, uint256 _hookId, address _token) internal { return; } function _onRevokeAsHook(address _tokenManager, uint256 _hookId, address _token) internal { return; } function _onTransfer(address _from, address _to, uint256 _amount) internal returns (bool) { return true; } function _onApprove(address _holder, address _spender, uint _amount) internal returns (bool) { return true; } } // File contracts/HookedTokenManager.sol /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract HookedTokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); bytes32 public constant SET_HOOK_ROLE = keccak256("SET_HOOK_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; mapping (uint256 => TokenManagerHook) internal hooks; uint256 internal hooksLength; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `_transferable ? '' : 'not'` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Create a new Token Manager hook for `_hook` * @param _hook Contract that will be used as Token Manager hook */ function registerHook(address _hook) external authP(SET_HOOK_ROLE, arr(_hook)) returns (uint256) { uint256 hookId = hooksLength++; hooks[hookId] = TokenManagerHook(_hook); hooks[hookId].onRegisterAsHook(hookId, token); return hookId; } /** * @notice Revoke Token Manager hook #`_hookId` * @param _hookId Position of the hook to be removed */ function revokeHook(uint256 _hookId) external authP(SET_HOOK_ROLE, arr(_hookId)) { hooks[_hookId].onRevokeAsHook(_hookId, token); delete hooks[_hookId]; } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { _burn(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { if (_isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount) { return _triggerOnTransferHook(_from, _to, _amount); } return false; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address _holder, address _spender, uint _amount) external onlyToken returns (bool) { return _triggerOnApproveHook(_holder, _spender, _amount); } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); _triggerOnTransferHook(0x0, _receiver, _amount); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _burn(address _holder, uint256 _amount) internal { _triggerOnTransferHook(_holder, 0x0, _amount); // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } function _triggerOnApproveHook(address _holder, address _spender, uint _amount) internal returns (bool approved) { approved = true; uint256 i = 0; while (approved && i < hooksLength) { if (address(hooks[i]) != 0) { approved = hooks[i].onApprove(_holder, _spender, _amount); } i++; } } function _triggerOnTransferHook(address _from, address _to, uint256 _amount) internal returns (bool transferable) { transferable = true; uint256 i = 0; while (transferable && i < hooksLength) { if (address(hooks[i]) != 0) { transferable = hooks[i].onTransfer(_from, _to, _amount); } i++; } } } // File @aragon/templates-shared/contracts/[email protected] pragma solidity 0.4.24; contract TokenCache { string constant private ERROR_MISSING_TOKEN_CACHE = "TEMPLATE_MISSING_TOKEN_CACHE"; mapping (address => address) internal tokenCache; function _cacheToken(MiniMeToken _token, address _owner) internal { tokenCache[_owner] = _token; } function _popTokenCache(address _owner) internal returns (MiniMeToken) { require(tokenCache[_owner] != address(0), ERROR_MISSING_TOKEN_CACHE); MiniMeToken token = MiniMeToken(tokenCache[_owner]); delete tokenCache[_owner]; return token; } } // File @aragon/apps-agent/contracts/standards/[email protected] pragma solidity 0.4.24; // ERC1271 on Feb 12th, 2019: https://github.com/ethereum/EIPs/blob/a97dc434930d0ccc4461c97d8c7a920dc585adf2/EIPS/eip-1271.md // Using `isValidSignature(bytes32,bytes)` even though the standard still hasn't been modified // Rationale: https://github.com/ethereum/EIPs/issues/1271#issuecomment-462719728 contract ERC1271 { bytes4 constant public ERC1271_INTERFACE_ID = 0xfb855dc9; // this.isValidSignature.selector bytes4 constant public ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; // TODO: Likely needs to be updated bytes4 constant public ERC1271_RETURN_INVALID_SIGNATURE = 0x00000000; /** * @dev Function must be implemented by deriving contract * @param _hash Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes32 _hash, bytes memory _signature) public view returns (bytes4); function returnIsValidSignatureMagicNumber(bool isValid) internal pure returns (bytes4) { return isValid ? ERC1271_RETURN_VALID_SIGNATURE : ERC1271_RETURN_INVALID_SIGNATURE; } } contract ERC1271Bytes is ERC1271 { /** * @dev Default behavior of `isValidSignature(bytes,bytes)`, can be overloaded for custom validation * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return A bytes4 magic value 0x20c13b0b if the signature check passes, 0x00000000 if not * * MUST NOT modify state (using STATICCALL for solc < 0.5, view modifier for solc > 0.5) * MUST allow external calls */ function isValidSignature(bytes _data, bytes _signature) public view returns (bytes4) { return isValidSignature(keccak256(_data), _signature); } } // File @aragon/apps-agent/contracts/[email protected] pragma solidity 0.4.24; // Inspired by https://github.com/horizon-games/multi-token-standard/blob/319740cf2a78b8816269ae49a09c537b3fd7303b/contracts/utils/SignatureValidator.sol // This should probably be moved into aOS: https://github.com/aragon/aragonOS/pull/442 library SignatureValidator { enum SignatureMode { Invalid, // 0x00 EIP712, // 0x01 EthSign, // 0x02 ERC1271, // 0x03 NMode // 0x04, to check if mode is specified, leave at the end } // bytes4(keccak256("isValidSignature(bytes,bytes)") bytes4 public constant ERC1271_RETURN_VALID_SIGNATURE = 0x20c13b0b; uint256 internal constant ERC1271_ISVALIDSIG_MAX_GAS = 250000; string private constant ERROR_INVALID_LENGTH_POP_BYTE = "SIGVAL_INVALID_LENGTH_POP_BYTE"; /// @dev Validates that a hash was signed by a specified signer. /// @param hash Hash which was signed. /// @param signer Address of the signer. /// @param signature ECDSA signature along with the mode (0 = Invalid, 1 = EIP712, 2 = EthSign, 3 = ERC1271) {mode}{r}{s}{v}. /// @return Returns whether signature is from a specified user. function isValidSignature(bytes32 hash, address signer, bytes signature) internal view returns (bool) { if (signature.length == 0) { return false; } uint8 modeByte = uint8(signature[0]); if (modeByte >= uint8(SignatureMode.NMode)) { return false; } SignatureMode mode = SignatureMode(modeByte); if (mode == SignatureMode.EIP712) { return ecVerify(hash, signer, signature); } else if (mode == SignatureMode.EthSign) { return ecVerify( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), signer, signature ); } else if (mode == SignatureMode.ERC1271) { // Pop the mode byte before sending it down the validation chain return safeIsValidSignature(signer, hash, popFirstByte(signature)); } else { return false; } } function ecVerify(bytes32 hash, address signer, bytes memory signature) private pure returns (bool) { (bool badSig, bytes32 r, bytes32 s, uint8 v) = unpackEcSig(signature); if (badSig) { return false; } return signer == ecrecover(hash, v, r, s); } function unpackEcSig(bytes memory signature) private pure returns (bool badSig, bytes32 r, bytes32 s, uint8 v) { if (signature.length != 66) { badSig = true; return; } v = uint8(signature[65]); assembly { r := mload(add(signature, 33)) s := mload(add(signature, 65)) } // Allow signature version to be 0 or 1 if (v < 27) { v += 27; } if (v != 27 && v != 28) { badSig = true; } } function popFirstByte(bytes memory input) private pure returns (bytes memory output) { uint256 inputLength = input.length; require(inputLength > 0, ERROR_INVALID_LENGTH_POP_BYTE); output = new bytes(inputLength - 1); if (output.length == 0) { return output; } uint256 inputPointer; uint256 outputPointer; assembly { inputPointer := add(input, 0x21) outputPointer := add(output, 0x20) } memcpy(outputPointer, inputPointer, output.length); } function safeIsValidSignature(address validator, bytes32 hash, bytes memory signature) private view returns (bool) { bytes memory data = abi.encodeWithSelector(ERC1271(validator).isValidSignature.selector, hash, signature); bytes4 erc1271Return = safeBytes4StaticCall(validator, data, ERC1271_ISVALIDSIG_MAX_GAS); return erc1271Return == ERC1271_RETURN_VALID_SIGNATURE; } function safeBytes4StaticCall(address target, bytes data, uint256 maxGas) private view returns (bytes4 ret) { uint256 gasLeft = gasleft(); uint256 callGas = gasLeft > maxGas ? maxGas : gasLeft; bool ok; assembly { ok := staticcall(callGas, target, add(data, 0x20), mload(data), 0, 0) } if (!ok) { return; } uint256 size; assembly { size := returndatasize } if (size != 32) { return; } assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` ret := mload(ptr) // read data at ptr and set it to be returned } return ret; } // From: https://github.com/Arachnid/solidity-stringutils/blob/01e955c1d6/src/strings.sol function memcpy(uint256 dest, uint256 src, uint256 len) private pure { // Copy word-length chunks while possible for (; len >= 32; len -= 32) { assembly { mstore(dest, mload(src)) } dest += 32; src += 32; } // Copy remaining bytes 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)) } } } // File @aragon/apps-agent/contracts/standards/[email protected] pragma solidity 0.4.24; interface IERC165 { function supportsInterface(bytes4 interfaceId) external pure returns (bool); } // File @aragon/apps-agent/contracts/standards/[email protected] pragma solidity 0.4.24; interface IERC721Receiver { /** * @notice Handle the receipt of an NFT * @dev The ERC721 smart contract calls this function on the recipient * after a {IERC721-safeTransferFrom}. 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 data) external returns (bytes4); } // File @aragon/os/contracts/common/[email protected] pragma solidity 0.4.24; contract DepositableStorage { using UnstructuredStorage for bytes32; // keccak256("aragonOS.depositableStorage.depositable") bytes32 internal constant DEPOSITABLE_POSITION = 0x665fd576fbbe6f247aff98f5c94a561e3f71ec2d3c988d56f12d342396c50cea; function isDepositable() public view returns (bool) { return DEPOSITABLE_POSITION.getStorageBool(); } function setDepositable(bool _depositable) internal { DEPOSITABLE_POSITION.setStorageBool(_depositable); } } // File @aragon/apps-vault/contracts/[email protected] pragma solidity 0.4.24; contract Vault is EtherTokenConstant, AragonApp, DepositableStorage { using SafeERC20 for ERC20; bytes32 public constant TRANSFER_ROLE = keccak256("TRANSFER_ROLE"); string private constant ERROR_DATA_NON_ZERO = "VAULT_DATA_NON_ZERO"; string private constant ERROR_NOT_DEPOSITABLE = "VAULT_NOT_DEPOSITABLE"; string private constant ERROR_DEPOSIT_VALUE_ZERO = "VAULT_DEPOSIT_VALUE_ZERO"; string private constant ERROR_TRANSFER_VALUE_ZERO = "VAULT_TRANSFER_VALUE_ZERO"; string private constant ERROR_SEND_REVERTED = "VAULT_SEND_REVERTED"; string private constant ERROR_VALUE_MISMATCH = "VAULT_VALUE_MISMATCH"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "VAULT_TOKEN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_TRANSFER_REVERTED = "VAULT_TOKEN_TRANSFER_REVERTED"; event VaultTransfer(address indexed token, address indexed to, uint256 amount); event VaultDeposit(address indexed token, address indexed sender, uint256 amount); /** * @dev On a normal send() or transfer() this fallback is never executed as it will be * intercepted by the Proxy (see aragonOS#281) */ function () external payable isInitialized { require(msg.data.length == 0, ERROR_DATA_NON_ZERO); _deposit(ETH, msg.value); } /** * @notice Initialize Vault app * @dev As an AragonApp it needs to be initialized in order for roles (`auth` and `authP`) to work */ function initialize() external onlyInit { initialized(); setDepositable(true); } /** * @notice Deposit `_value` `_token` to the vault * @param _token Address of the token being transferred * @param _value Amount of tokens being transferred */ function deposit(address _token, uint256 _value) external payable isInitialized { _deposit(_token, _value); } /** * @notice Transfer `_value` `_token` from the Vault to `_to` * @param _token Address of the token being transferred * @param _to Address of the recipient of tokens * @param _value Amount of tokens being transferred */ /* solium-disable-next-line function-order */ function transfer(address _token, address _to, uint256 _value) external authP(TRANSFER_ROLE, arr(_token, _to, _value)) { require(_value > 0, ERROR_TRANSFER_VALUE_ZERO); if (_token == ETH) { require(_to.send(_value), ERROR_SEND_REVERTED); } else { require(ERC20(_token).safeTransfer(_to, _value), ERROR_TOKEN_TRANSFER_REVERTED); } emit VaultTransfer(_token, _to, _value); } function balance(address _token) public view returns (uint256) { if (_token == ETH) { return address(this).balance; } else { return ERC20(_token).staticBalanceOf(address(this)); } } /** * @dev Disable recovery escape hatch, as it could be used * maliciously to transfer funds away from the vault */ function allowRecoverability(address) public view returns (bool) { return false; } function _deposit(address _token, uint256 _value) internal { require(isDepositable(), ERROR_NOT_DEPOSITABLE); require(_value > 0, ERROR_DEPOSIT_VALUE_ZERO); if (_token == ETH) { // Deposit is implicit in this case require(msg.value == _value, ERROR_VALUE_MISMATCH); } else { require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _value), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } emit VaultDeposit(_token, msg.sender, _value); } } // File @aragon/apps-agent/contracts/[email protected] /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Agent is IERC165, IERC721Receiver, ERC1271Bytes, IForwarder, IsContract, Vault { /* Hardcoded constants to save gas bytes32 public constant EXECUTE_ROLE = keccak256("EXECUTE_ROLE"); bytes32 public constant SAFE_EXECUTE_ROLE = keccak256("SAFE_EXECUTE_ROLE"); bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = keccak256("ADD_PROTECTED_TOKEN_ROLE"); bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = keccak256("REMOVE_PROTECTED_TOKEN_ROLE"); bytes32 public constant ADD_PRESIGNED_HASH_ROLE = keccak256("ADD_PRESIGNED_HASH_ROLE"); bytes32 public constant DESIGNATE_SIGNER_ROLE = keccak256("DESIGNATE_SIGNER_ROLE"); bytes32 public constant RUN_SCRIPT_ROLE = keccak256("RUN_SCRIPT_ROLE"); */ bytes32 public constant EXECUTE_ROLE = 0xcebf517aa4440d1d125e0355aae64401211d0848a23c02cc5d29a14822580ba4; bytes32 public constant SAFE_EXECUTE_ROLE = 0x0a1ad7b87f5846153c6d5a1f761d71c7d0cfd122384f56066cd33239b7933694; bytes32 public constant ADD_PROTECTED_TOKEN_ROLE = 0x6eb2a499556bfa2872f5aa15812b956cc4a71b4d64eb3553f7073c7e41415aaa; bytes32 public constant REMOVE_PROTECTED_TOKEN_ROLE = 0x71eee93d500f6f065e38b27d242a756466a00a52a1dbcd6b4260f01a8640402a; bytes32 public constant ADD_PRESIGNED_HASH_ROLE = 0x0b29780bb523a130b3b01f231ef49ed2fa2781645591a0b0a44ca98f15a5994c; bytes32 public constant DESIGNATE_SIGNER_ROLE = 0x23ce341656c3f14df6692eebd4757791e33662b7dcf9970c8308303da5472b7c; bytes32 public constant RUN_SCRIPT_ROLE = 0xb421f7ad7646747f3051c50c0b8e2377839296cd4973e27f63821d73e390338f; uint256 public constant PROTECTED_TOKENS_CAP = 10; bytes4 private constant ERC165_INTERFACE_ID = 0x01ffc9a7; bytes4 private constant ERC721_RECEIVED_INTERFACE_ID = 0x150b7a02; // bytes4(keccak256("onERC721Received(address,address,uint256,bytes)")) string private constant ERROR_TARGET_PROTECTED = "AGENT_TARGET_PROTECTED"; string private constant ERROR_PROTECTED_TOKENS_MODIFIED = "AGENT_PROTECTED_TOKENS_MODIFIED"; string private constant ERROR_PROTECTED_BALANCE_LOWERED = "AGENT_PROTECTED_BALANCE_LOWERED"; string private constant ERROR_TOKENS_CAP_REACHED = "AGENT_TOKENS_CAP_REACHED"; string private constant ERROR_TOKEN_NOT_ERC20 = "AGENT_TOKEN_NOT_ERC20"; string private constant ERROR_TOKEN_ALREADY_PROTECTED = "AGENT_TOKEN_ALREADY_PROTECTED"; string private constant ERROR_TOKEN_NOT_PROTECTED = "AGENT_TOKEN_NOT_PROTECTED"; string private constant ERROR_DESIGNATED_TO_SELF = "AGENT_DESIGNATED_TO_SELF"; string private constant ERROR_CAN_NOT_FORWARD = "AGENT_CAN_NOT_FORWARD"; mapping (bytes32 => bool) public isPresigned; address public designatedSigner; address[] public protectedTokens; event SafeExecute(address indexed sender, address indexed target, bytes data); event Execute(address indexed sender, address indexed target, uint256 ethValue, bytes data); event AddProtectedToken(address indexed token); event RemoveProtectedToken(address indexed token); event PresignHash(address indexed sender, bytes32 indexed hash); event SetDesignatedSigner(address indexed sender, address indexed oldSigner, address indexed newSigner); event ReceiveERC721(address indexed token, address indexed operator, address indexed from, uint256 tokenId, bytes data); /** * @notice Execute '`@radspec(_target, _data)`' on `_target``_ethValue == 0 ? '' : ' (Sending ' + @tokenAmount(0x0000000000000000000000000000000000000000, _ethValue) + ')'` * @param _target Address where the action is being executed * @param _ethValue Amount of ETH from the contract that is sent with the action * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function execute(address _target, uint256 _ethValue, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(EXECUTE_ROLE, arr(_target, _ethValue, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { bool result = _target.call.value(_ethValue)(_data); if (result) { emit Execute(msg.sender, _target, _ethValue, _data); } assembly { let ptr := mload(0x40) returndatacopy(ptr, 0, returndatasize) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, returndatasize) } default { return(ptr, returndatasize) } } } /** * @notice Execute '`@radspec(_target, _data)`' on `_target`, ensuring that protected tokens can't be spent * @param _target Address where the action is being executed * @param _data Calldata for the action * @return Exits call frame forwarding the return data of the executed call (either error or success data) */ function safeExecute(address _target, bytes _data) external // This function MUST always be external as the function performs a low level return, exiting the Agent app execution context authP(SAFE_EXECUTE_ROLE, arr(_target, uint256(_getSig(_data)))) // bytes4 casted as uint256 sets the bytes as the LSBs { uint256 protectedTokensLength = protectedTokens.length; address[] memory protectedTokens_ = new address[](protectedTokensLength); uint256[] memory balances = new uint256[](protectedTokensLength); for (uint256 i = 0; i < protectedTokensLength; i++) { address token = protectedTokens[i]; require(_target != token, ERROR_TARGET_PROTECTED); // we copy the protected tokens array to check whether the storage array has been modified during the underlying call protectedTokens_[i] = token; // we copy the balances to check whether they have been modified during the underlying call balances[i] = balance(token); } bool result = _target.call(_data); bytes32 ptr; uint256 size; assembly { size := returndatasize ptr := mload(0x40) mstore(0x40, add(ptr, returndatasize)) returndatacopy(ptr, 0, returndatasize) } if (result) { // if the underlying call has succeeded, we check that the protected tokens // and their balances have not been modified and return the call's return data require(protectedTokens.length == protectedTokensLength, ERROR_PROTECTED_TOKENS_MODIFIED); for (uint256 j = 0; j < protectedTokensLength; j++) { require(protectedTokens[j] == protectedTokens_[j], ERROR_PROTECTED_TOKENS_MODIFIED); require(balance(protectedTokens[j]) >= balances[j], ERROR_PROTECTED_BALANCE_LOWERED); } emit SafeExecute(msg.sender, _target, _data); assembly { return(ptr, size) } } else { // if the underlying call has failed, we revert and forward returned error data assembly { revert(ptr, size) } } } /** * @notice Add `_token.symbol(): string` to the list of protected tokens * @param _token Address of the token to be protected */ function addProtectedToken(address _token) external authP(ADD_PROTECTED_TOKEN_ROLE, arr(_token)) { require(protectedTokens.length < PROTECTED_TOKENS_CAP, ERROR_TOKENS_CAP_REACHED); require(_isERC20(_token), ERROR_TOKEN_NOT_ERC20); require(!_tokenIsProtected(_token), ERROR_TOKEN_ALREADY_PROTECTED); _addProtectedToken(_token); } /** * @notice Remove `_token.symbol(): string` from the list of protected tokens * @param _token Address of the token to be unprotected */ function removeProtectedToken(address _token) external authP(REMOVE_PROTECTED_TOKEN_ROLE, arr(_token)) { require(_tokenIsProtected(_token), ERROR_TOKEN_NOT_PROTECTED); _removeProtectedToken(_token); } /** * @notice Pre-sign hash `_hash` * @param _hash Hash that will be considered signed regardless of the signature checked with 'isValidSignature()' */ function presignHash(bytes32 _hash) external authP(ADD_PRESIGNED_HASH_ROLE, arr(_hash)) { isPresigned[_hash] = true; emit PresignHash(msg.sender, _hash); } /** * @notice Set `_designatedSigner` as the designated signer of the app, which will be able to sign messages on behalf of the app * @param _designatedSigner Address that will be able to sign messages on behalf of the app */ function setDesignatedSigner(address _designatedSigner) external authP(DESIGNATE_SIGNER_ROLE, arr(_designatedSigner)) { // Prevent an infinite loop by setting the app itself as its designated signer. // An undetectable loop can be created by setting a different contract as the // designated signer which calls back into `isValidSignature`. // Given that `isValidSignature` is always called with just 50k gas, the max // damage of the loop is wasting 50k gas. require(_designatedSigner != address(this), ERROR_DESIGNATED_TO_SELF); address oldDesignatedSigner = designatedSigner; designatedSigner = _designatedSigner; emit SetDesignatedSigner(msg.sender, oldDesignatedSigner, _designatedSigner); } function onERC721Received(address _operator, address _from, uint256 _tokenId, bytes _data) external returns (bytes4) { emit ReceiveERC721(msg.sender, _operator, _from, _tokenId, _data); return ERC721_RECEIVED_INTERFACE_ID; } // Forwarding fns /** * @notice Tells whether the Agent app is a forwarder or not * @dev IForwarder interface conformance * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Tells whether this contract supports a given ERC-165 interface * @dev Implements conformance to ERC-165 * @param _interfaceId Interface bytes to check * @return True if this contract supports the interface */ function supportsInterface(bytes4 _interfaceId) external pure returns (bool) { return _interfaceId == ERC1271_INTERFACE_ID || _interfaceId == ERC721_RECEIVED_INTERFACE_ID || _interfaceId == ERC165_INTERFACE_ID; } /** * @notice Execute the script as the Agent app * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = ""; // no input address[] memory blacklist = new address[](0); // no addr blacklist, can interact with anything runScript(_evmScript, input, blacklist); // We don't need to emit an event here as EVMScriptRunner will emit ScriptResult if successful } /** * @notice Tells whether `_sender` can forward actions or not * @dev IForwarder interface conformance * @param _sender Address of the account intending to forward an action * @return True if the given address can run scripts, false otherwise */ function canForward(address _sender, bytes _evmScript) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, RUN_SCRIPT_ROLE, arr(_getScriptACLParam(_evmScript))); } // ERC-1271 conformance /** * @notice Tells whether a signature is seen as valid by this contract through ERC-1271 * @param _hash Arbitrary length data signed on the behalf of address (this) * @param _signature Signature byte array associated with _data * @return The ERC-1271 magic value if the signature is valid */ function isValidSignature(bytes32 _hash, bytes _signature) public view returns (bytes4) { // Short-circuit in case the hash was presigned. Optimization as performing calls // and ecrecover is more expensive than an SLOAD. if (isPresigned[_hash]) { return returnIsValidSignatureMagicNumber(true); } bool isValid; if (designatedSigner == address(0)) { isValid = false; } else { isValid = SignatureValidator.isValidSignature(_hash, designatedSigner, _signature); } return returnIsValidSignatureMagicNumber(isValid); } // Getters function getProtectedTokensLength() public view isInitialized returns (uint256) { return protectedTokens.length; } // Internal fns function _addProtectedToken(address _token) internal { protectedTokens.push(_token); emit AddProtectedToken(_token); } function _removeProtectedToken(address _token) internal { protectedTokens[_protectedTokenIndex(_token)] = protectedTokens[protectedTokens.length - 1]; protectedTokens.length--; emit RemoveProtectedToken(_token); } function _isERC20(address _token) internal view returns (bool) { if (!isContract(_token)) { return false; } // Throwaway sanity check to make sure the token's `balanceOf()` does not error (for now) balance(_token); return true; } function _protectedTokenIndex(address _token) internal view returns (uint256) { for (uint i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return i; } } revert(ERROR_TOKEN_NOT_PROTECTED); } function _tokenIsProtected(address _token) internal view returns (bool) { for (uint256 i = 0; i < protectedTokens.length; i++) { if (protectedTokens[i] == _token) { return true; } } return false; } function _getScriptACLParam(bytes _evmScript) internal pure returns (uint256) { return uint256(keccak256(abi.encodePacked(_evmScript))); } function _getSig(bytes _data) internal pure returns (bytes4 sig) { if (_data.length < 4) { return; } assembly { sig := mload(add(_data, 0x20)) } } } // File @aragon/os/contracts/lib/math/[email protected] // See https://github.com/OpenZeppelin/openzeppelin-solidity/blob/d51e38758e1d985661534534d5c61e27bece5042/contracts/math/SafeMath.sol // Adapted for uint64, pragma ^0.4.24, and satisfying our linter rules // Also optimized the mul() implementation, see https://github.com/aragon/aragonOS/pull/417 pragma solidity ^0.4.24; /** * @title SafeMath64 * @dev Math operations for uint64 with safety checks that revert on error */ library SafeMath64 { string private constant ERROR_ADD_OVERFLOW = "MATH64_ADD_OVERFLOW"; string private constant ERROR_SUB_UNDERFLOW = "MATH64_SUB_UNDERFLOW"; string private constant ERROR_MUL_OVERFLOW = "MATH64_MUL_OVERFLOW"; string private constant ERROR_DIV_ZERO = "MATH64_DIV_ZERO"; /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint64 _a, uint64 _b) internal pure returns (uint64) { uint256 c = uint256(_a) * uint256(_b); require(c < 0x010000000000000000, ERROR_MUL_OVERFLOW); // 2**64 (less gas this way) return uint64(c); } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b > 0, ERROR_DIV_ZERO); // Solidity only automatically asserts when dividing by 0 uint64 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(uint64 _a, uint64 _b) internal pure returns (uint64) { require(_b <= _a, ERROR_SUB_UNDERFLOW); uint64 c = _a - _b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint64 _a, uint64 _b) internal pure returns (uint64) { uint64 c = _a + _b; require(c >= _a, ERROR_ADD_OVERFLOW); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint64 a, uint64 b) internal pure returns (uint64) { require(b != 0, ERROR_DIV_ZERO); return a % b; } } // File @aragon/apps-voting/contracts/[email protected] /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Voting is IForwarder, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_VOTES_ROLE = keccak256("CREATE_VOTES_ROLE"); bytes32 public constant MODIFY_SUPPORT_ROLE = keccak256("MODIFY_SUPPORT_ROLE"); bytes32 public constant MODIFY_QUORUM_ROLE = keccak256("MODIFY_QUORUM_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 string private constant ERROR_NO_VOTE = "VOTING_NO_VOTE"; string private constant ERROR_INIT_PCTS = "VOTING_INIT_PCTS"; string private constant ERROR_CHANGE_SUPPORT_PCTS = "VOTING_CHANGE_SUPPORT_PCTS"; string private constant ERROR_CHANGE_QUORUM_PCTS = "VOTING_CHANGE_QUORUM_PCTS"; string private constant ERROR_INIT_SUPPORT_TOO_BIG = "VOTING_INIT_SUPPORT_TOO_BIG"; string private constant ERROR_CHANGE_SUPPORT_TOO_BIG = "VOTING_CHANGE_SUPP_TOO_BIG"; string private constant ERROR_CAN_NOT_VOTE = "VOTING_CAN_NOT_VOTE"; string private constant ERROR_CAN_NOT_EXECUTE = "VOTING_CAN_NOT_EXECUTE"; string private constant ERROR_CAN_NOT_FORWARD = "VOTING_CAN_NOT_FORWARD"; string private constant ERROR_NO_VOTING_POWER = "VOTING_NO_VOTING_POWER"; enum VoterState { Absent, Yea, Nay } struct Vote { bool executed; uint64 startDate; uint64 snapshotBlock; uint64 supportRequiredPct; uint64 minAcceptQuorumPct; uint256 yea; uint256 nay; uint256 votingPower; bytes executionScript; mapping (address => VoterState) voters; } MiniMeToken public token; uint64 public supportRequiredPct; uint64 public minAcceptQuorumPct; uint64 public voteTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => Vote) internal votes; uint256 public votesLength; event StartVote(uint256 indexed voteId, address indexed creator, string metadata); event CastVote(uint256 indexed voteId, address indexed voter, bool supports, uint256 stake); event ExecuteVote(uint256 indexed voteId); event ChangeSupportRequired(uint64 supportRequiredPct); event ChangeMinQuorum(uint64 minAcceptQuorumPct); modifier voteExists(uint256 _voteId) { require(_voteId < votesLength, ERROR_NO_VOTE); _; } /** * @notice Initialize Voting app with `_token.symbol(): string` for governance, minimum support of `@formatPct(_supportRequiredPct)`%, minimum acceptance quorum of `@formatPct(_minAcceptQuorumPct)`%, and a voting duration of `@transformTime(_voteTime)` * @param _token MiniMeToken Address that will be used as governance token * @param _supportRequiredPct Percentage of yeas in casted votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _minAcceptQuorumPct Percentage of yeas in total possible votes for a vote to succeed (expressed as a percentage of 10^18; eg. 10^16 = 1%, 10^18 = 100%) * @param _voteTime Seconds that a vote will be open for token holders to vote (unless enough yeas or nays have been cast to make an early decision) */ function initialize( MiniMeToken _token, uint64 _supportRequiredPct, uint64 _minAcceptQuorumPct, uint64 _voteTime ) external onlyInit { initialized(); require(_minAcceptQuorumPct <= _supportRequiredPct, ERROR_INIT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_INIT_SUPPORT_TOO_BIG); token = _token; supportRequiredPct = _supportRequiredPct; minAcceptQuorumPct = _minAcceptQuorumPct; voteTime = _voteTime; } /** * @notice Change required support to `@formatPct(_supportRequiredPct)`% * @param _supportRequiredPct New required support */ function changeSupportRequiredPct(uint64 _supportRequiredPct) external authP(MODIFY_SUPPORT_ROLE, arr(uint256(_supportRequiredPct), uint256(supportRequiredPct))) { require(minAcceptQuorumPct <= _supportRequiredPct, ERROR_CHANGE_SUPPORT_PCTS); require(_supportRequiredPct < PCT_BASE, ERROR_CHANGE_SUPPORT_TOO_BIG); supportRequiredPct = _supportRequiredPct; emit ChangeSupportRequired(_supportRequiredPct); } /** * @notice Change minimum acceptance quorum to `@formatPct(_minAcceptQuorumPct)`% * @param _minAcceptQuorumPct New acceptance quorum */ function changeMinAcceptQuorumPct(uint64 _minAcceptQuorumPct) external authP(MODIFY_QUORUM_ROLE, arr(uint256(_minAcceptQuorumPct), uint256(minAcceptQuorumPct))) { require(_minAcceptQuorumPct <= supportRequiredPct, ERROR_CHANGE_QUORUM_PCTS); minAcceptQuorumPct = _minAcceptQuorumPct; emit ChangeMinQuorum(_minAcceptQuorumPct); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @return voteId Id for newly created vote */ function newVote(bytes _executionScript, string _metadata) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, true, true); } /** * @notice Create a new vote about "`_metadata`" * @param _executionScript EVM script to be executed on approval * @param _metadata Vote metadata * @param _castVote Whether to also cast newly created vote * @param _executesIfDecided Whether to also immediately execute newly created vote if decided * @return voteId id for newly created vote */ function newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) external auth(CREATE_VOTES_ROLE) returns (uint256 voteId) { return _newVote(_executionScript, _metadata, _castVote, _executesIfDecided); } /** * @notice Vote `_supports ? 'yes' : 'no'` in vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote * @param _supports Whether voter supports the vote * @param _executesIfDecided Whether the vote should execute its action if it becomes decided */ function vote(uint256 _voteId, bool _supports, bool _executesIfDecided) external voteExists(_voteId) { require(_canVote(_voteId, msg.sender), ERROR_CAN_NOT_VOTE); _vote(_voteId, _supports, msg.sender, _executesIfDecided); } /** * @notice Execute vote #`_voteId` * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization * @param _voteId Id for vote */ function executeVote(uint256 _voteId) external voteExists(_voteId) { _executeVote(_voteId); } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Creates a vote to execute the desired action, and casts a support vote if possible * @dev IForwarder interface conformance * @param _evmScript Start vote with script */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); _newVote(_evmScript, "", true, true); } function canForward(address _sender, bytes) public view returns (bool) { // Note that `canPerform()` implicitly does an initialization check itself return canPerform(_sender, CREATE_VOTES_ROLE, arr()); } // Getter fns /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canExecute(uint256 _voteId) public view voteExists(_voteId) returns (bool) { return _canExecute(_voteId); } /** * @dev Initialization check is implicitly provided by `voteExists()` as new votes can only be * created via `newVote(),` which requires initialization */ function canVote(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (bool) { return _canVote(_voteId, _voter); } function getVote(uint256 _voteId) public view voteExists(_voteId) returns ( bool open, bool executed, uint64 startDate, uint64 snapshotBlock, uint64 supportRequired, uint64 minAcceptQuorum, uint256 yea, uint256 nay, uint256 votingPower, bytes script ) { Vote storage vote_ = votes[_voteId]; open = _isVoteOpen(vote_); executed = vote_.executed; startDate = vote_.startDate; snapshotBlock = vote_.snapshotBlock; supportRequired = vote_.supportRequiredPct; minAcceptQuorum = vote_.minAcceptQuorumPct; yea = vote_.yea; nay = vote_.nay; votingPower = vote_.votingPower; script = vote_.executionScript; } function getVoterState(uint256 _voteId, address _voter) public view voteExists(_voteId) returns (VoterState) { return votes[_voteId].voters[_voter]; } // Internal fns function _newVote(bytes _executionScript, string _metadata, bool _castVote, bool _executesIfDecided) internal returns (uint256 voteId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); voteId = votesLength++; Vote storage vote_ = votes[voteId]; vote_.startDate = getTimestamp64(); vote_.snapshotBlock = snapshotBlock; vote_.supportRequiredPct = supportRequiredPct; vote_.minAcceptQuorumPct = minAcceptQuorumPct; vote_.votingPower = votingPower; vote_.executionScript = _executionScript; emit StartVote(voteId, msg.sender, _metadata); if (_castVote && _canVote(voteId, msg.sender)) { _vote(voteId, true, msg.sender, _executesIfDecided); } } function _vote( uint256 _voteId, bool _supports, address _voter, bool _executesIfDecided ) internal { Vote storage vote_ = votes[_voteId]; // This could re-enter, though we can assume the governance token is not malicious uint256 voterStake = token.balanceOfAt(_voter, vote_.snapshotBlock); VoterState state = vote_.voters[_voter]; // If voter had previously voted, decrease count if (state == VoterState.Yea) { vote_.yea = vote_.yea.sub(voterStake); } else if (state == VoterState.Nay) { vote_.nay = vote_.nay.sub(voterStake); } if (_supports) { vote_.yea = vote_.yea.add(voterStake); } else { vote_.nay = vote_.nay.add(voterStake); } vote_.voters[_voter] = _supports ? VoterState.Yea : VoterState.Nay; emit CastVote(_voteId, _voter, _supports, voterStake); if (_executesIfDecided && _canExecute(_voteId)) { // We've already checked if the vote can be executed with `_canExecute()` _unsafeExecuteVote(_voteId); } } function _executeVote(uint256 _voteId) internal { require(_canExecute(_voteId), ERROR_CAN_NOT_EXECUTE); _unsafeExecuteVote(_voteId); } /** * @dev Unsafe version of _executeVote that assumes you have already checked if the vote can be executed */ function _unsafeExecuteVote(uint256 _voteId) internal { Vote storage vote_ = votes[_voteId]; vote_.executed = true; bytes memory input = new bytes(0); // TODO: Consider input for voting scripts runScript(vote_.executionScript, input, new address[](0)); emit ExecuteVote(_voteId); } function _canExecute(uint256 _voteId) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; if (vote_.executed) { return false; } // Voting is already decided if (_isValuePct(vote_.yea, vote_.votingPower, vote_.supportRequiredPct)) { return true; } // Vote ended? if (_isVoteOpen(vote_)) { return false; } // Has enough support? uint256 totalVotes = vote_.yea.add(vote_.nay); if (!_isValuePct(vote_.yea, totalVotes, vote_.supportRequiredPct)) { return false; } // Has min quorum? if (!_isValuePct(vote_.yea, vote_.votingPower, vote_.minAcceptQuorumPct)) { return false; } return true; } function _canVote(uint256 _voteId, address _voter) internal view returns (bool) { Vote storage vote_ = votes[_voteId]; return _isVoteOpen(vote_) && token.balanceOfAt(_voter, vote_.snapshotBlock) > 0; } function _isVoteOpen(Vote storage vote_) internal view returns (bool) { return getTimestamp64() < vote_.startDate.add(voteTime) && !vote_.executed; } /** * @dev Calculates whether `_value` is more than a percentage `_pct` of `_total` */ function _isValuePct(uint256 _value, uint256 _total, uint256 _pct) internal pure returns (bool) { if (_total == 0) { return false; } uint256 computedPct = _value.mul(PCT_BASE) / _total; return computedPct > _pct; } } // File @aragon/ppf-contracts/contracts/[email protected] pragma solidity ^0.4.18; interface IFeed { function ratePrecision() external pure returns (uint256); function get(address base, address quote) external view returns (uint128 xrt, uint64 when); } // File @aragon/apps-finance/contracts/[email protected] /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Finance is EtherTokenConstant, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; using SafeERC20 for ERC20; bytes32 public constant CREATE_PAYMENTS_ROLE = keccak256("CREATE_PAYMENTS_ROLE"); bytes32 public constant CHANGE_PERIOD_ROLE = keccak256("CHANGE_PERIOD_ROLE"); bytes32 public constant CHANGE_BUDGETS_ROLE = keccak256("CHANGE_BUDGETS_ROLE"); bytes32 public constant EXECUTE_PAYMENTS_ROLE = keccak256("EXECUTE_PAYMENTS_ROLE"); bytes32 public constant MANAGE_PAYMENTS_ROLE = keccak256("MANAGE_PAYMENTS_ROLE"); uint256 internal constant NO_SCHEDULED_PAYMENT = 0; uint256 internal constant NO_TRANSACTION = 0; uint256 internal constant MAX_SCHEDULED_PAYMENTS_PER_TX = 20; uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); uint64 internal constant MINIMUM_PERIOD = uint64(1 days); string private constant ERROR_COMPLETE_TRANSITION = "FINANCE_COMPLETE_TRANSITION"; string private constant ERROR_NO_SCHEDULED_PAYMENT = "FINANCE_NO_SCHEDULED_PAYMENT"; string private constant ERROR_NO_TRANSACTION = "FINANCE_NO_TRANSACTION"; string private constant ERROR_NO_PERIOD = "FINANCE_NO_PERIOD"; string private constant ERROR_VAULT_NOT_CONTRACT = "FINANCE_VAULT_NOT_CONTRACT"; string private constant ERROR_SET_PERIOD_TOO_SHORT = "FINANCE_SET_PERIOD_TOO_SHORT"; string private constant ERROR_NEW_PAYMENT_AMOUNT_ZERO = "FINANCE_NEW_PAYMENT_AMOUNT_ZERO"; string private constant ERROR_NEW_PAYMENT_INTERVAL_ZERO = "FINANCE_NEW_PAYMENT_INTRVL_ZERO"; string private constant ERROR_NEW_PAYMENT_EXECS_ZERO = "FINANCE_NEW_PAYMENT_EXECS_ZERO"; string private constant ERROR_NEW_PAYMENT_IMMEDIATE = "FINANCE_NEW_PAYMENT_IMMEDIATE"; string private constant ERROR_RECOVER_AMOUNT_ZERO = "FINANCE_RECOVER_AMOUNT_ZERO"; string private constant ERROR_DEPOSIT_AMOUNT_ZERO = "FINANCE_DEPOSIT_AMOUNT_ZERO"; string private constant ERROR_ETH_VALUE_MISMATCH = "FINANCE_ETH_VALUE_MISMATCH"; string private constant ERROR_BUDGET = "FINANCE_BUDGET"; string private constant ERROR_EXECUTE_PAYMENT_NUM = "FINANCE_EXECUTE_PAYMENT_NUM"; string private constant ERROR_EXECUTE_PAYMENT_TIME = "FINANCE_EXECUTE_PAYMENT_TIME"; string private constant ERROR_PAYMENT_RECEIVER = "FINANCE_PAYMENT_RECEIVER"; string private constant ERROR_TOKEN_TRANSFER_FROM_REVERTED = "FINANCE_TKN_TRANSFER_FROM_REVERT"; string private constant ERROR_TOKEN_APPROVE_FAILED = "FINANCE_TKN_APPROVE_FAILED"; string private constant ERROR_PAYMENT_INACTIVE = "FINANCE_PAYMENT_INACTIVE"; string private constant ERROR_REMAINING_BUDGET = "FINANCE_REMAINING_BUDGET"; // Order optimized for storage struct ScheduledPayment { address token; address receiver; address createdBy; bool inactive; uint256 amount; uint64 initialPaymentTime; uint64 interval; uint64 maxExecutions; uint64 executions; } // Order optimized for storage struct Transaction { address token; address entity; bool isIncoming; uint256 amount; uint256 paymentId; uint64 paymentExecutionNumber; uint64 date; uint64 periodId; } struct TokenStatement { uint256 expenses; uint256 income; } struct Period { uint64 startTime; uint64 endTime; uint256 firstTransactionId; uint256 lastTransactionId; mapping (address => TokenStatement) tokenStatement; } struct Settings { uint64 periodDuration; mapping (address => uint256) budgets; mapping (address => bool) hasBudget; } Vault public vault; Settings internal settings; // We are mimicing arrays, we use mappings instead to make app upgrade more graceful mapping (uint256 => ScheduledPayment) internal scheduledPayments; // Payments start at index 1, to allow us to use scheduledPayments[0] for transactions that are not // linked to a scheduled payment uint256 public paymentsNextIndex; mapping (uint256 => Transaction) internal transactions; uint256 public transactionsNextIndex; mapping (uint64 => Period) internal periods; uint64 public periodsLength; event NewPeriod(uint64 indexed periodId, uint64 periodStarts, uint64 periodEnds); event SetBudget(address indexed token, uint256 amount, bool hasBudget); event NewPayment(uint256 indexed paymentId, address indexed recipient, uint64 maxExecutions, string reference); event NewTransaction(uint256 indexed transactionId, bool incoming, address indexed entity, uint256 amount, string reference); event ChangePaymentState(uint256 indexed paymentId, bool active); event ChangePeriodDuration(uint64 newDuration); event PaymentFailure(uint256 paymentId); // Modifier used by all methods that impact accounting to make sure accounting period // is changed before the operation if needed // NOTE: its use **MUST** be accompanied by an initialization check modifier transitionsPeriod { bool completeTransition = _tryTransitionAccountingPeriod(getMaxPeriodTransitions()); require(completeTransition, ERROR_COMPLETE_TRANSITION); _; } modifier scheduledPaymentExists(uint256 _paymentId) { require(_paymentId > 0 && _paymentId < paymentsNextIndex, ERROR_NO_SCHEDULED_PAYMENT); _; } modifier transactionExists(uint256 _transactionId) { require(_transactionId > 0 && _transactionId < transactionsNextIndex, ERROR_NO_TRANSACTION); _; } modifier periodExists(uint64 _periodId) { require(_periodId < periodsLength, ERROR_NO_PERIOD); _; } /** * @notice Deposit ETH to the Vault, to avoid locking them in this Finance app forever * @dev Send ETH to Vault. Send all the available balance. */ function () external payable isInitialized transitionsPeriod { require(msg.value > 0, ERROR_DEPOSIT_AMOUNT_ZERO); _deposit( ETH, msg.value, "Ether transfer to Finance app", msg.sender, true ); } /** * @notice Initialize Finance app for Vault at `_vault` with period length of `@transformTime(_periodDuration)` * @param _vault Address of the vault Finance will rely on (non changeable) * @param _periodDuration Duration in seconds of each period */ function initialize(Vault _vault, uint64 _periodDuration) external onlyInit { initialized(); require(isContract(_vault), ERROR_VAULT_NOT_CONTRACT); vault = _vault; require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; // Reserve the first scheduled payment index as an unused index for transactions not linked // to a scheduled payment scheduledPayments[0].inactive = true; paymentsNextIndex = 1; // Reserve the first transaction index as an unused index for periods with no transactions transactionsNextIndex = 1; // Start the first period _newPeriod(getTimestamp64()); } /** * @notice Deposit `@tokenAmount(_token, _amount)` * @dev Deposit for approved ERC20 tokens or ETH * @param _token Address of deposited token * @param _amount Amount of tokens sent * @param _reference Reason for payment */ function deposit(address _token, uint256 _amount, string _reference) external payable isInitialized transitionsPeriod { require(_amount > 0, ERROR_DEPOSIT_AMOUNT_ZERO); if (_token == ETH) { // Ensure that the ETH sent with the transaction equals the amount in the deposit require(msg.value == _amount, ERROR_ETH_VALUE_MISMATCH); } _deposit( _token, _amount, _reference, msg.sender, true ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for '`_reference`' * @dev Note that this function is protected by the `CREATE_PAYMENTS_ROLE` but uses `MAX_UINT256` * as its interval auth parameter (as a sentinel value for "never repeating"). * While this protects against most cases (you typically want to set a baseline requirement * for interval time), it does mean users will have to explicitly check for this case when * granting a permission that includes a upperbound requirement on the interval time. * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _reference String detailing payment reason */ function newImmediatePayment(address _token, address _receiver, uint256 _amount, string _reference) external // Use MAX_UINT256 as the interval parameter, as this payment will never repeat // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, MAX_UINT256, uint256(1), getTimestamp())) transitionsPeriod { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); _makePaymentTransaction( _token, _receiver, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any payment id; it isn't created 0, // also unrelated to any payment executions _reference ); } /** * @notice Create a new payment of `@tokenAmount(_token, _amount)` to `_receiver` for `_reference`, executing `_maxExecutions` times at intervals of `@transformTime(_interval)` * @dev See `newImmediatePayment()` for limitations on how the interval auth parameter can be used * @param _token Address of token for payment * @param _receiver Address that will receive payment * @param _amount Tokens that are paid every time the payment is due * @param _initialPaymentTime Timestamp for when the first payment is done * @param _interval Number of seconds that need to pass between payment transactions * @param _maxExecutions Maximum instances a payment can be executed * @param _reference String detailing payment reason */ function newScheduledPayment( address _token, address _receiver, uint256 _amount, uint64 _initialPaymentTime, uint64 _interval, uint64 _maxExecutions, string _reference ) external // Payment time parameter is left as the last param as it was added later authP(CREATE_PAYMENTS_ROLE, _arr(_token, _receiver, _amount, uint256(_interval), uint256(_maxExecutions), uint256(_initialPaymentTime))) transitionsPeriod returns (uint256 paymentId) { require(_amount > 0, ERROR_NEW_PAYMENT_AMOUNT_ZERO); require(_interval > 0, ERROR_NEW_PAYMENT_INTERVAL_ZERO); require(_maxExecutions > 0, ERROR_NEW_PAYMENT_EXECS_ZERO); // Token budget must not be set at all or allow at least one instance of this payment each period require(!settings.hasBudget[_token] || settings.budgets[_token] >= _amount, ERROR_BUDGET); // Don't allow creating single payments that are immediately executable, use `newImmediatePayment()` instead if (_maxExecutions == 1) { require(_initialPaymentTime > getTimestamp64(), ERROR_NEW_PAYMENT_IMMEDIATE); } paymentId = paymentsNextIndex++; emit NewPayment(paymentId, _receiver, _maxExecutions, _reference); ScheduledPayment storage payment = scheduledPayments[paymentId]; payment.token = _token; payment.receiver = _receiver; payment.amount = _amount; payment.initialPaymentTime = _initialPaymentTime; payment.interval = _interval; payment.maxExecutions = _maxExecutions; payment.createdBy = msg.sender; // We skip checking how many times the new payment was executed to allow creating new // scheduled payments before having enough vault balance _executePayment(paymentId); } /** * @notice Change period duration to `@transformTime(_periodDuration)`, effective for next accounting period * @param _periodDuration Duration in seconds for accounting periods */ function setPeriodDuration(uint64 _periodDuration) external authP(CHANGE_PERIOD_ROLE, arr(uint256(_periodDuration), uint256(settings.periodDuration))) transitionsPeriod { require(_periodDuration >= MINIMUM_PERIOD, ERROR_SET_PERIOD_TOO_SHORT); settings.periodDuration = _periodDuration; emit ChangePeriodDuration(_periodDuration); } /** * @notice Set budget for `_token.symbol(): string` to `@tokenAmount(_token, _amount, false)`, effective immediately * @param _token Address for token * @param _amount New budget amount */ function setBudget( address _token, uint256 _amount ) external authP(CHANGE_BUDGETS_ROLE, arr(_token, _amount, settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = _amount; if (!settings.hasBudget[_token]) { settings.hasBudget[_token] = true; } emit SetBudget(_token, _amount, true); } /** * @notice Remove spending limit for `_token.symbol(): string`, effective immediately * @param _token Address for token */ function removeBudget(address _token) external authP(CHANGE_BUDGETS_ROLE, arr(_token, uint256(0), settings.budgets[_token], uint256(settings.hasBudget[_token] ? 1 : 0))) transitionsPeriod { settings.budgets[_token] = 0; settings.hasBudget[_token] = false; emit SetBudget(_token, 0, false); } /** * @notice Execute pending payment #`_paymentId` * @dev Executes any payment (requires role) * @param _paymentId Identifier for payment */ function executePayment(uint256 _paymentId) external authP(EXECUTE_PAYMENTS_ROLE, arr(_paymentId, scheduledPayments[_paymentId].amount)) scheduledPaymentExists(_paymentId) transitionsPeriod { _executePaymentAtLeastOnce(_paymentId); } /** * @notice Execute pending payment #`_paymentId` * @dev Always allow receiver of a payment to trigger execution * Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization * @param _paymentId Identifier for payment */ function receiverExecutePayment(uint256 _paymentId) external scheduledPaymentExists(_paymentId) transitionsPeriod { require(scheduledPayments[_paymentId].receiver == msg.sender, ERROR_PAYMENT_RECEIVER); _executePaymentAtLeastOnce(_paymentId); } /** * @notice `_active ? 'Activate' : 'Disable'` payment #`_paymentId` * @dev Note that we do not require this action to transition periods, as it doesn't directly * impact any accounting periods. * Not having to transition periods also makes disabling payments easier to prevent funds * from being pulled out in the event of a breach. * @param _paymentId Identifier for payment * @param _active Whether it will be active or inactive */ function setPaymentStatus(uint256 _paymentId, bool _active) external authP(MANAGE_PAYMENTS_ROLE, arr(_paymentId, uint256(_active ? 1 : 0))) scheduledPaymentExists(_paymentId) { scheduledPayments[_paymentId].inactive = !_active; emit ChangePaymentState(_paymentId, _active); } /** * @notice Send tokens held in this contract to the Vault * @dev Allows making a simple payment from this contract to the Vault, to avoid locked tokens. * This contract should never receive tokens with a simple transfer call, but in case it * happens, this function allows for their recovery. * @param _token Token whose balance is going to be transferred. */ function recoverToVault(address _token) external isInitialized transitionsPeriod { uint256 amount = _token == ETH ? address(this).balance : ERC20(_token).staticBalanceOf(address(this)); require(amount > 0, ERROR_RECOVER_AMOUNT_ZERO); _deposit( _token, amount, "Recover to Vault", address(this), false ); } /** * @notice Transition accounting period if needed * @dev Transitions accounting periods if needed. For preventing OOG attacks, a maxTransitions * param is provided. If more than the specified number of periods need to be transitioned, * it will return false. * @param _maxTransitions Maximum periods that can be transitioned * @return success Boolean indicating whether the accounting period is the correct one (if false, * maxTransitions was surpased and another call is needed) */ function tryTransitionAccountingPeriod(uint64 _maxTransitions) external isInitialized returns (bool success) { return _tryTransitionAccountingPeriod(_maxTransitions); } // Getter fns /** * @dev Disable recovery escape hatch if the app has been initialized, as it could be used * maliciously to transfer funds in the Finance app to another Vault * finance#recoverToVault() should be used to recover funds to the Finance's vault */ function allowRecoverability(address) public view returns (bool) { return !hasInitialized(); } function getPayment(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns ( address token, address receiver, uint256 amount, uint64 initialPaymentTime, uint64 interval, uint64 maxExecutions, bool inactive, uint64 executions, address createdBy ) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; token = payment.token; receiver = payment.receiver; amount = payment.amount; initialPaymentTime = payment.initialPaymentTime; interval = payment.interval; maxExecutions = payment.maxExecutions; executions = payment.executions; inactive = payment.inactive; createdBy = payment.createdBy; } function getTransaction(uint256 _transactionId) public view transactionExists(_transactionId) returns ( uint64 periodId, uint256 amount, uint256 paymentId, uint64 paymentExecutionNumber, address token, address entity, bool isIncoming, uint64 date ) { Transaction storage transaction = transactions[_transactionId]; token = transaction.token; entity = transaction.entity; isIncoming = transaction.isIncoming; date = transaction.date; periodId = transaction.periodId; amount = transaction.amount; paymentId = transaction.paymentId; paymentExecutionNumber = transaction.paymentExecutionNumber; } function getPeriod(uint64 _periodId) public view periodExists(_periodId) returns ( bool isCurrent, uint64 startTime, uint64 endTime, uint256 firstTransactionId, uint256 lastTransactionId ) { Period storage period = periods[_periodId]; isCurrent = _currentPeriodId() == _periodId; startTime = period.startTime; endTime = period.endTime; firstTransactionId = period.firstTransactionId; lastTransactionId = period.lastTransactionId; } function getPeriodTokenStatement(uint64 _periodId, address _token) public view periodExists(_periodId) returns (uint256 expenses, uint256 income) { TokenStatement storage tokenStatement = periods[_periodId].tokenStatement[_token]; expenses = tokenStatement.expenses; income = tokenStatement.income; } /** * @dev We have to check for initialization as periods are only valid after initializing */ function currentPeriodId() public view isInitialized returns (uint64) { return _currentPeriodId(); } /** * @dev We have to check for initialization as periods are only valid after initializing */ function getPeriodDuration() public view isInitialized returns (uint64) { return settings.periodDuration; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getBudget(address _token) public view isInitialized returns (uint256 budget, bool hasBudget) { budget = settings.budgets[_token]; hasBudget = settings.hasBudget[_token]; } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function getRemainingBudget(address _token) public view isInitialized returns (uint256) { return _getRemainingBudget(_token); } /** * @dev We have to check for initialization as budgets are only valid after initializing */ function canMakePayment(address _token, uint256 _amount) public view isInitialized returns (bool) { return _canMakePayment(_token, _amount); } /** * @dev Initialization check is implicitly provided by `scheduledPaymentExists()` as new * scheduled payments can only be created via `newScheduledPayment(),` which requires initialization */ function nextPaymentTime(uint256 _paymentId) public view scheduledPaymentExists(_paymentId) returns (uint64) { return _nextPaymentTime(_paymentId); } // Internal fns function _deposit(address _token, uint256 _amount, string _reference, address _sender, bool _isExternalDeposit) internal { _recordIncomingTransaction( _token, _sender, _amount, _reference ); if (_token == ETH) { vault.deposit.value(_amount)(ETH, _amount); } else { // First, transfer the tokens to Finance if necessary // External deposit will be false when the assets were already in the Finance app // and just need to be transferred to the Vault if (_isExternalDeposit) { // This assumes the sender has approved the tokens for Finance require( ERC20(_token).safeTransferFrom(msg.sender, address(this), _amount), ERROR_TOKEN_TRANSFER_FROM_REVERTED ); } // Approve the tokens for the Vault (it does the actual transferring) require(ERC20(_token).safeApprove(vault, _amount), ERROR_TOKEN_APPROVE_FAILED); // Finally, initiate the deposit vault.deposit(_token, _amount); } } function _executePayment(uint256 _paymentId) internal returns (uint256) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; require(!payment.inactive, ERROR_PAYMENT_INACTIVE); uint64 paid = 0; while (_nextPaymentTime(_paymentId) <= getTimestamp64() && paid < MAX_SCHEDULED_PAYMENTS_PER_TX) { if (!_canMakePayment(payment.token, payment.amount)) { emit PaymentFailure(_paymentId); break; } // The while() predicate prevents these two from ever overflowing payment.executions += 1; paid += 1; // We've already checked the remaining budget with `_canMakePayment()` _unsafeMakePaymentTransaction( payment.token, payment.receiver, payment.amount, _paymentId, payment.executions, "" ); } return paid; } function _executePaymentAtLeastOnce(uint256 _paymentId) internal { uint256 paid = _executePayment(_paymentId); if (paid == 0) { if (_nextPaymentTime(_paymentId) <= getTimestamp64()) { revert(ERROR_EXECUTE_PAYMENT_NUM); } else { revert(ERROR_EXECUTE_PAYMENT_TIME); } } } function _makePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { require(_getRemainingBudget(_token) >= _amount, ERROR_REMAINING_BUDGET); _unsafeMakePaymentTransaction(_token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference); } /** * @dev Unsafe version of _makePaymentTransaction that assumes you have already checked the * remaining budget */ function _unsafeMakePaymentTransaction( address _token, address _receiver, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { _recordTransaction( false, _token, _receiver, _amount, _paymentId, _paymentExecutionNumber, _reference ); vault.transfer(_token, _receiver, _amount); } function _newPeriod(uint64 _startTime) internal returns (Period storage) { // There should be no way for this to overflow since each period is at least one day uint64 newPeriodId = periodsLength++; Period storage period = periods[newPeriodId]; period.startTime = _startTime; // Be careful here to not overflow; if startTime + periodDuration overflows, we set endTime // to MAX_UINT64 (let's assume that's the end of time for now). uint64 endTime = _startTime + settings.periodDuration - 1; if (endTime < _startTime) { // overflowed endTime = MAX_UINT64; } period.endTime = endTime; emit NewPeriod(newPeriodId, period.startTime, period.endTime); return period; } function _recordIncomingTransaction( address _token, address _sender, uint256 _amount, string _reference ) internal { _recordTransaction( true, // incoming transaction _token, _sender, _amount, NO_SCHEDULED_PAYMENT, // unrelated to any existing payment 0, // and no payment executions _reference ); } function _recordTransaction( bool _incoming, address _token, address _entity, uint256 _amount, uint256 _paymentId, uint64 _paymentExecutionNumber, string _reference ) internal { uint64 periodId = _currentPeriodId(); TokenStatement storage tokenStatement = periods[periodId].tokenStatement[_token]; if (_incoming) { tokenStatement.income = tokenStatement.income.add(_amount); } else { tokenStatement.expenses = tokenStatement.expenses.add(_amount); } uint256 transactionId = transactionsNextIndex++; Transaction storage transaction = transactions[transactionId]; transaction.token = _token; transaction.entity = _entity; transaction.isIncoming = _incoming; transaction.amount = _amount; transaction.paymentId = _paymentId; transaction.paymentExecutionNumber = _paymentExecutionNumber; transaction.date = getTimestamp64(); transaction.periodId = periodId; Period storage period = periods[periodId]; if (period.firstTransactionId == NO_TRANSACTION) { period.firstTransactionId = transactionId; } emit NewTransaction(transactionId, _incoming, _entity, _amount, _reference); } function _tryTransitionAccountingPeriod(uint64 _maxTransitions) internal returns (bool success) { Period storage currentPeriod = periods[_currentPeriodId()]; uint64 timestamp = getTimestamp64(); // Transition periods if necessary while (timestamp > currentPeriod.endTime) { if (_maxTransitions == 0) { // Required number of transitions is over allowed number, return false indicating // it didn't fully transition return false; } // We're already protected from underflowing above _maxTransitions -= 1; // If there were any transactions in period, record which was the last // In case 0 transactions occured, first and last tx id will be 0 if (currentPeriod.firstTransactionId != NO_TRANSACTION) { currentPeriod.lastTransactionId = transactionsNextIndex.sub(1); } // New period starts at end time + 1 currentPeriod = _newPeriod(currentPeriod.endTime.add(1)); } return true; } function _canMakePayment(address _token, uint256 _amount) internal view returns (bool) { return _getRemainingBudget(_token) >= _amount && vault.balance(_token) >= _amount; } function _currentPeriodId() internal view returns (uint64) { // There is no way for this to overflow if protected by an initialization check return periodsLength - 1; } function _getRemainingBudget(address _token) internal view returns (uint256) { if (!settings.hasBudget[_token]) { return MAX_UINT256; } uint256 budget = settings.budgets[_token]; uint256 spent = periods[_currentPeriodId()].tokenStatement[_token].expenses; // A budget decrease can cause the spent amount to be greater than period budget // If so, return 0 to not allow more spending during period if (spent >= budget) { return 0; } // We're already protected from the overflow above return budget - spent; } function _nextPaymentTime(uint256 _paymentId) internal view returns (uint64) { ScheduledPayment storage payment = scheduledPayments[_paymentId]; if (payment.executions >= payment.maxExecutions) { return MAX_UINT64; // re-executes in some billions of years time... should not need to worry } // Split in multiple lines to circumvent linter warning uint64 increase = payment.executions.mul(payment.interval); uint64 nextPayment = payment.initialPaymentTime.add(increase); return nextPayment; } // Syntax sugar function _arr(address _a, address _b, uint256 _c, uint256 _d, uint256 _e, uint256 _f) internal pure returns (uint256[] r) { r = new uint256[](6); r[0] = uint256(_a); r[1] = uint256(_b); r[2] = _c; r[3] = _d; r[4] = _e; r[5] = _f; } // Mocked fns (overrided during testing) // Must be view for mocking purposes function getMaxPeriodTransitions() internal view returns (uint64) { return MAX_UINT64; } } // File @aragon/apps-payroll/contracts/[email protected] pragma solidity 0.4.24; /** * @title Payroll in multiple currencies */ contract Payroll is EtherTokenConstant, IForwarder, IsContract, AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; /* Hardcoded constants to save gas * bytes32 constant public ADD_EMPLOYEE_ROLE = keccak256("ADD_EMPLOYEE_ROLE"); * bytes32 constant public TERMINATE_EMPLOYEE_ROLE = keccak256("TERMINATE_EMPLOYEE_ROLE"); * bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = keccak256("SET_EMPLOYEE_SALARY_ROLE"); * bytes32 constant public ADD_BONUS_ROLE = keccak256("ADD_BONUS_ROLE"); * bytes32 constant public ADD_REIMBURSEMENT_ROLE = keccak256("ADD_REIMBURSEMENT_ROLE"); * bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = keccak256("MANAGE_ALLOWED_TOKENS_ROLE"); * bytes32 constant public MODIFY_PRICE_FEED_ROLE = keccak256("MODIFY_PRICE_FEED_ROLE"); * bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = keccak256("MODIFY_RATE_EXPIRY_ROLE"); */ bytes32 constant public ADD_EMPLOYEE_ROLE = 0x9ecdc3c63716b45d0756eece5fe1614cae1889ec5a1ce62b3127c1f1f1615d6e; bytes32 constant public TERMINATE_EMPLOYEE_ROLE = 0x69c67f914d12b6440e7ddf01961214818d9158fbcb19211e0ff42800fdea9242; bytes32 constant public SET_EMPLOYEE_SALARY_ROLE = 0xea9ac65018da2421cf419ee2152371440c08267a193a33ccc1e39545d197e44d; bytes32 constant public ADD_BONUS_ROLE = 0xceca7e2f5eb749a87aaf68f3f76d6b9251aa2f4600f13f93c5a4adf7a72df4ae; bytes32 constant public ADD_REIMBURSEMENT_ROLE = 0x90698b9d54427f1e41636025017309bdb1b55320da960c8845bab0a504b01a16; bytes32 constant public MANAGE_ALLOWED_TOKENS_ROLE = 0x0be34987c45700ee3fae8c55e270418ba903337decc6bacb1879504be9331c06; bytes32 constant public MODIFY_PRICE_FEED_ROLE = 0x74350efbcba8b85341c5bbf70cc34e2a585fc1463524773a12fa0a71d4eb9302; bytes32 constant public MODIFY_RATE_EXPIRY_ROLE = 0x79fe989a8899060dfbdabb174ebb96616fa9f1d9dadd739f8d814cbab452404e; uint256 internal constant MAX_ALLOWED_TOKENS = 20; // prevent OOG issues with `payday()` uint64 internal constant MIN_RATE_EXPIRY = uint64(1 minutes); // 1 min == ~4 block window to mine both a price feed update and a payout uint256 internal constant MAX_UINT256 = uint256(-1); uint64 internal constant MAX_UINT64 = uint64(-1); string private constant ERROR_EMPLOYEE_DOESNT_EXIST = "PAYROLL_EMPLOYEE_DOESNT_EXIST"; string private constant ERROR_NON_ACTIVE_EMPLOYEE = "PAYROLL_NON_ACTIVE_EMPLOYEE"; string private constant ERROR_SENDER_DOES_NOT_MATCH = "PAYROLL_SENDER_DOES_NOT_MATCH"; string private constant ERROR_FINANCE_NOT_CONTRACT = "PAYROLL_FINANCE_NOT_CONTRACT"; string private constant ERROR_TOKEN_ALREADY_SET = "PAYROLL_TOKEN_ALREADY_SET"; string private constant ERROR_MAX_ALLOWED_TOKENS = "PAYROLL_MAX_ALLOWED_TOKENS"; string private constant ERROR_MIN_RATES_MISMATCH = "PAYROLL_MIN_RATES_MISMATCH"; string private constant ERROR_TOKEN_ALLOCATION_MISMATCH = "PAYROLL_TOKEN_ALLOCATION_MISMATCH"; string private constant ERROR_NOT_ALLOWED_TOKEN = "PAYROLL_NOT_ALLOWED_TOKEN"; string private constant ERROR_DISTRIBUTION_NOT_FULL = "PAYROLL_DISTRIBUTION_NOT_FULL"; string private constant ERROR_INVALID_PAYMENT_TYPE = "PAYROLL_INVALID_PAYMENT_TYPE"; string private constant ERROR_NOTHING_PAID = "PAYROLL_NOTHING_PAID"; string private constant ERROR_CAN_NOT_FORWARD = "PAYROLL_CAN_NOT_FORWARD"; string private constant ERROR_EMPLOYEE_NULL_ADDRESS = "PAYROLL_EMPLOYEE_NULL_ADDRESS"; string private constant ERROR_EMPLOYEE_ALREADY_EXIST = "PAYROLL_EMPLOYEE_ALREADY_EXIST"; string private constant ERROR_FEED_NOT_CONTRACT = "PAYROLL_FEED_NOT_CONTRACT"; string private constant ERROR_EXPIRY_TIME_TOO_SHORT = "PAYROLL_EXPIRY_TIME_TOO_SHORT"; string private constant ERROR_PAST_TERMINATION_DATE = "PAYROLL_PAST_TERMINATION_DATE"; string private constant ERROR_EXCHANGE_RATE_TOO_LOW = "PAYROLL_EXCHANGE_RATE_TOO_LOW"; string private constant ERROR_LAST_PAYROLL_DATE_TOO_BIG = "PAYROLL_LAST_DATE_TOO_BIG"; string private constant ERROR_INVALID_REQUESTED_AMOUNT = "PAYROLL_INVALID_REQUESTED_AMT"; enum PaymentType { Payroll, Reimbursement, Bonus } struct Employee { address accountAddress; // unique, but can be changed over time uint256 denominationTokenSalary; // salary per second in denomination Token uint256 accruedSalary; // keep track of any leftover accrued salary when changing salaries uint256 bonus; uint256 reimbursements; uint64 lastPayroll; uint64 endDate; address[] allocationTokenAddresses; mapping(address => uint256) allocationTokens; } Finance public finance; address public denominationToken; IFeed public feed; uint64 public rateExpiryTime; // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees uint256 public nextEmployee; mapping(uint256 => Employee) internal employees; // employee ID -> employee mapping(address => uint256) internal employeeIds; // employee address -> employee ID mapping(address => bool) internal allowedTokens; event AddEmployee( uint256 indexed employeeId, address indexed accountAddress, uint256 initialDenominationSalary, uint64 startDate, string role ); event TerminateEmployee(uint256 indexed employeeId, uint64 endDate); event SetEmployeeSalary(uint256 indexed employeeId, uint256 denominationSalary); event AddEmployeeAccruedSalary(uint256 indexed employeeId, uint256 amount); event AddEmployeeBonus(uint256 indexed employeeId, uint256 amount); event AddEmployeeReimbursement(uint256 indexed employeeId, uint256 amount); event ChangeAddressByEmployee(uint256 indexed employeeId, address indexed newAccountAddress, address indexed oldAccountAddress); event DetermineAllocation(uint256 indexed employeeId); event SendPayment( uint256 indexed employeeId, address indexed accountAddress, address indexed token, uint256 amount, uint256 exchangeRate, string paymentReference ); event SetAllowedToken(address indexed token, bool allowed); event SetPriceFeed(address indexed feed); event SetRateExpiryTime(uint64 time); // Check employee exists by ID modifier employeeIdExists(uint256 _employeeId) { require(_employeeExists(_employeeId), ERROR_EMPLOYEE_DOESNT_EXIST); _; } // Check employee exists and is still active modifier employeeActive(uint256 _employeeId) { // No need to check for existence as _isEmployeeIdActive() is false for non-existent employees require(_isEmployeeIdActive(_employeeId), ERROR_NON_ACTIVE_EMPLOYEE); _; } // Check sender matches an existing employee modifier employeeMatches { require(employees[employeeIds[msg.sender]].accountAddress == msg.sender, ERROR_SENDER_DOES_NOT_MATCH); _; } /** * @notice Initialize Payroll app for Finance at `_finance` and price feed at `_priceFeed`, setting denomination token to `_token` and exchange rate expiry time to `@transformTime(_rateExpiryTime)` * @dev Note that we do not require _denominationToken to be a contract, as it may be a "fake" * address used by the price feed to denominate fiat currencies * @param _finance Address of the Finance app this Payroll app will rely on for payments (non-changeable) * @param _denominationToken Address of the denomination token used for salary accounting * @param _priceFeed Address of the price feed * @param _rateExpiryTime Acceptable expiry time in seconds for the price feed's exchange rates */ function initialize(Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime) external onlyInit { initialized(); require(isContract(_finance), ERROR_FINANCE_NOT_CONTRACT); finance = _finance; denominationToken = _denominationToken; _setPriceFeed(_priceFeed); _setRateExpiryTime(_rateExpiryTime); // Employees start at index 1, to allow us to use employees[0] to check for non-existent employees nextEmployee = 1; } /** * @notice `_allowed ? 'Add' : 'Remove'` `_token.symbol(): string` `_allowed ? 'to' : 'from'` the set of allowed tokens * @param _token Address of the token to be added or removed from the list of allowed tokens for payments * @param _allowed Boolean to tell whether the given token should be added or removed from the list */ function setAllowedToken(address _token, bool _allowed) external authP(MANAGE_ALLOWED_TOKENS_ROLE, arr(_token)) { require(allowedTokens[_token] != _allowed, ERROR_TOKEN_ALREADY_SET); allowedTokens[_token] = _allowed; emit SetAllowedToken(_token, _allowed); } /** * @notice Set the price feed for exchange rates to `_feed` * @param _feed Address of the new price feed instance */ function setPriceFeed(IFeed _feed) external authP(MODIFY_PRICE_FEED_ROLE, arr(_feed, feed)) { _setPriceFeed(_feed); } /** * @notice Set the acceptable expiry time for the price feed's exchange rates to `@transformTime(_time)` * @dev Exchange rates older than the given value won't be accepted for payments and will cause payouts to revert * @param _time The expiration time in seconds for exchange rates */ function setRateExpiryTime(uint64 _time) external authP(MODIFY_RATE_EXPIRY_ROLE, arr(uint256(_time), uint256(rateExpiryTime))) { _setRateExpiryTime(_time); } /** * @notice Add employee with address `_accountAddress` to payroll with an salary of `_initialDenominationSalary` per second, starting on `@formatDate(_startDate)` * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds (it actually sets their initial lastPayroll value) * @param _role Employee's role */ function addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) external authP(ADD_EMPLOYEE_ROLE, arr(_accountAddress, _initialDenominationSalary, uint256(_startDate))) { _addEmployee(_accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @notice Add `_amount` to bonus for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's bonuses in denomination token */ function addBonus(uint256 _employeeId, uint256 _amount) external authP(ADD_BONUS_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addBonus(_employeeId, _amount); } /** * @notice Add `_amount` to reimbursements for employee #`_employeeId` * @param _employeeId Employee's identifier * @param _amount Amount to be added to the employee's reimbursements in denomination token */ function addReimbursement(uint256 _employeeId, uint256 _amount) external authP(ADD_REIMBURSEMENT_ROLE, arr(_employeeId, _amount)) employeeActive(_employeeId) { _addReimbursement(_employeeId, _amount); } /** * @notice Set employee #`_employeeId`'s salary to `_denominationSalary` per second * @dev This reverts if either the employee's owed salary or accrued salary overflows, to avoid * losing any accrued salary for an employee due to the employer changing their salary. * @param _employeeId Employee's identifier * @param _denominationSalary Employee's new salary, per second in denomination token */ function setEmployeeSalary(uint256 _employeeId, uint256 _denominationSalary) external authP(SET_EMPLOYEE_SALARY_ROLE, arr(_employeeId, _denominationSalary, employees[_employeeId].denominationTokenSalary)) employeeActive(_employeeId) { Employee storage employee = employees[_employeeId]; // Accrue employee's owed salary; don't cap to revert on overflow uint256 owed = _getOwedSalarySinceLastPayroll(employee, false); _addAccruedSalary(_employeeId, owed); // Update employee to track the new salary and payment date employee.lastPayroll = getTimestamp64(); employee.denominationTokenSalary = _denominationSalary; emit SetEmployeeSalary(_employeeId, _denominationSalary); } /** * @notice Terminate employee #`_employeeId` on `@formatDate(_endDate)` * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function terminateEmployee(uint256 _employeeId, uint64 _endDate) external authP(TERMINATE_EMPLOYEE_ROLE, arr(_employeeId, uint256(_endDate))) employeeActive(_employeeId) { _terminateEmployee(_employeeId, _endDate); } /** * @notice Change your employee account address to `_newAccountAddress` * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _newAccountAddress New address to receive payments for the requesting employee */ function changeAddressByEmployee(address _newAccountAddress) external employeeMatches nonReentrant { uint256 employeeId = employeeIds[msg.sender]; address oldAddress = employees[employeeId].accountAddress; _setEmployeeAddress(employeeId, _newAccountAddress); // Don't delete the old address until after setting the new address to check that the // employee specified a new address delete employeeIds[oldAddress]; emit ChangeAddressByEmployee(employeeId, _newAccountAddress, oldAddress); } /** * @notice Set the token distribution for your payments * @dev Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _tokens Array of token addresses; they must belong to the list of allowed tokens * @param _distribution Array with each token's corresponding proportions (must be integers summing to 100) */ function determineAllocation(address[] _tokens, uint256[] _distribution) external employeeMatches nonReentrant { // Check array lengthes match require(_tokens.length <= MAX_ALLOWED_TOKENS, ERROR_MAX_ALLOWED_TOKENS); require(_tokens.length == _distribution.length, ERROR_TOKEN_ALLOCATION_MISMATCH); uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; // Delete previous token allocations address[] memory previousAllowedTokenAddresses = employee.allocationTokenAddresses; for (uint256 j = 0; j < previousAllowedTokenAddresses.length; j++) { delete employee.allocationTokens[previousAllowedTokenAddresses[j]]; } delete employee.allocationTokenAddresses; // Set distributions only if given tokens are allowed for (uint256 i = 0; i < _tokens.length; i++) { employee.allocationTokenAddresses.push(_tokens[i]); employee.allocationTokens[_tokens[i]] = _distribution[i]; } _ensureEmployeeTokenAllocationsIsValid(employee); emit DetermineAllocation(employeeId); } /** * @notice Request your `_type == 0 ? 'salary' : _type == 1 ? 'reimbursements' : 'bonus'` * @dev Reverts if no payments were made. * Initialization check is implicitly provided by `employeeMatches` as new employees can * only be added via `addEmployee(),` which requires initialization. * As the employee is allowed to call this, we enforce non-reentrancy. * @param _type Payment type being requested (Payroll, Reimbursement or Bonus) * @param _requestedAmount Requested amount to pay for the payment type. Must be less than or equal to total owed amount for the payment type, or zero to request all. * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens */ function payday(PaymentType _type, uint256 _requestedAmount, uint256[] _minRates) external employeeMatches nonReentrant { uint256 paymentAmount; uint256 employeeId = employeeIds[msg.sender]; Employee storage employee = employees[employeeId]; _ensureEmployeeTokenAllocationsIsValid(employee); require(_minRates.length == 0 || _minRates.length == employee.allocationTokenAddresses.length, ERROR_MIN_RATES_MISMATCH); // Do internal employee accounting if (_type == PaymentType.Payroll) { // Salary is capped here to avoid reverting at this point if it becomes too big // (so employees aren't DDOSed if their salaries get too large) // If we do use a capped value, the employee's lastPayroll date will be adjusted accordingly uint256 totalOwedSalary = _getTotalOwedCappedSalary(employee); paymentAmount = _ensurePaymentAmount(totalOwedSalary, _requestedAmount); _updateEmployeeAccountingBasedOnPaidSalary(employee, paymentAmount); } else if (_type == PaymentType.Reimbursement) { uint256 owedReimbursements = employee.reimbursements; paymentAmount = _ensurePaymentAmount(owedReimbursements, _requestedAmount); employee.reimbursements = owedReimbursements.sub(paymentAmount); } else if (_type == PaymentType.Bonus) { uint256 owedBonusAmount = employee.bonus; paymentAmount = _ensurePaymentAmount(owedBonusAmount, _requestedAmount); employee.bonus = owedBonusAmount.sub(paymentAmount); } else { revert(ERROR_INVALID_PAYMENT_TYPE); } // Actually transfer the owed funds require(_transferTokensAmount(employeeId, _type, paymentAmount, _minRates), ERROR_NOTHING_PAID); _removeEmployeeIfTerminatedAndPaidOut(employeeId); } // Forwarding fns /** * @dev IForwarder interface conformance. Tells whether the Payroll app is a forwarder or not. * @return Always true */ function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as an active employee * @dev IForwarder interface conformance. Allows active employees to run EVMScripts in the context of the Payroll app. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the Finance app to the blacklist to disallow employees from executing actions on the // Finance app from Payroll's context (since Payroll requires permissions on Finance) address[] memory blacklist = new address[](1); blacklist[0] = address(finance); runScript(_evmScript, input, blacklist); } /** * @dev IForwarder interface conformance. Tells whether a given address can forward actions or not. * @param _sender Address of the account intending to forward an action * @return True if the given address is an active employee, false otherwise */ function canForward(address _sender, bytes) public view returns (bool) { return _isEmployeeIdActive(employeeIds[_sender]); } // Getter fns /** * @dev Return employee's identifier by their account address * @param _accountAddress Employee's address to receive payments * @return Employee's identifier */ function getEmployeeIdByAddress(address _accountAddress) public view returns (uint256) { require(employeeIds[_accountAddress] != uint256(0), ERROR_EMPLOYEE_DOESNT_EXIST); return employeeIds[_accountAddress]; } /** * @dev Return all information for employee by their ID * @param _employeeId Employee's identifier * @return Employee's address to receive payments * @return Employee's salary, per second in denomination token * @return Employee's accrued salary * @return Employee's bonus amount * @return Employee's reimbursements amount * @return Employee's last payment date * @return Employee's termination date (max uint64 if none) * @return Employee's allowed payment tokens */ function getEmployee(uint256 _employeeId) public view employeeIdExists(_employeeId) returns ( address accountAddress, uint256 denominationSalary, uint256 accruedSalary, uint256 bonus, uint256 reimbursements, uint64 lastPayroll, uint64 endDate, address[] allocationTokens ) { Employee storage employee = employees[_employeeId]; accountAddress = employee.accountAddress; denominationSalary = employee.denominationTokenSalary; accruedSalary = employee.accruedSalary; bonus = employee.bonus; reimbursements = employee.reimbursements; lastPayroll = employee.lastPayroll; endDate = employee.endDate; allocationTokens = employee.allocationTokenAddresses; } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function getTotalOwedSalary(uint256 _employeeId) public view employeeIdExists(_employeeId) returns (uint256) { return _getTotalOwedCappedSalary(employees[_employeeId]); } /** * @dev Get an employee's payment allocation for a token * @param _employeeId Employee's identifier * @param _token Token to query the payment allocation for * @return Employee's payment allocation for the token being queried */ function getAllocation(uint256 _employeeId, address _token) public view employeeIdExists(_employeeId) returns (uint256) { return employees[_employeeId].allocationTokens[_token]; } /** * @dev Check if a token is allowed to be used for payments * @param _token Address of the token to be checked * @return True if the given token is allowed, false otherwise */ function isTokenAllowed(address _token) public view isInitialized returns (bool) { return allowedTokens[_token]; } // Internal fns /** * @dev Set the price feed used for exchange rates * @param _feed Address of the new price feed instance */ function _setPriceFeed(IFeed _feed) internal { require(isContract(_feed), ERROR_FEED_NOT_CONTRACT); feed = _feed; emit SetPriceFeed(feed); } /** * @dev Set the exchange rate expiry time in seconds. * Exchange rates older than the given value won't be accepted for payments and will cause * payouts to revert. * @param _time The expiration time in seconds for exchange rates */ function _setRateExpiryTime(uint64 _time) internal { // Require a sane minimum for the rate expiry time require(_time >= MIN_RATE_EXPIRY, ERROR_EXPIRY_TIME_TOO_SHORT); rateExpiryTime = _time; emit SetRateExpiryTime(rateExpiryTime); } /** * @dev Add a new employee to Payroll * @param _accountAddress Employee's address to receive payroll * @param _initialDenominationSalary Employee's salary, per second in denomination token * @param _startDate Employee's starting timestamp in seconds * @param _role Employee's role */ function _addEmployee(address _accountAddress, uint256 _initialDenominationSalary, uint64 _startDate, string _role) internal { uint256 employeeId = nextEmployee++; _setEmployeeAddress(employeeId, _accountAddress); Employee storage employee = employees[employeeId]; employee.denominationTokenSalary = _initialDenominationSalary; employee.lastPayroll = _startDate; employee.endDate = MAX_UINT64; emit AddEmployee(employeeId, _accountAddress, _initialDenominationSalary, _startDate, _role); } /** * @dev Add amount to an employee's bonuses * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's bonuses in denomination token */ function _addBonus(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.bonus = employee.bonus.add(_amount); emit AddEmployeeBonus(_employeeId, _amount); } /** * @dev Add amount to an employee's reimbursements * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's reimbursements in denomination token */ function _addReimbursement(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.reimbursements = employee.reimbursements.add(_amount); emit AddEmployeeReimbursement(_employeeId, _amount); } /** * @dev Add amount to an employee's accrued salary * @param _employeeId Employee's identifier * @param _amount Amount be added to the employee's accrued salary in denomination token */ function _addAccruedSalary(uint256 _employeeId, uint256 _amount) internal { Employee storage employee = employees[_employeeId]; employee.accruedSalary = employee.accruedSalary.add(_amount); emit AddEmployeeAccruedSalary(_employeeId, _amount); } /** * @dev Set an employee's account address * @param _employeeId Employee's identifier * @param _accountAddress Employee's address to receive payroll */ function _setEmployeeAddress(uint256 _employeeId, address _accountAddress) internal { // Check address is non-null require(_accountAddress != address(0), ERROR_EMPLOYEE_NULL_ADDRESS); // Check address isn't already being used require(employeeIds[_accountAddress] == uint256(0), ERROR_EMPLOYEE_ALREADY_EXIST); employees[_employeeId].accountAddress = _accountAddress; // Create IDs mapping employeeIds[_accountAddress] = _employeeId; } /** * @dev Terminate employee on end date * @param _employeeId Employee's identifier * @param _endDate Termination timestamp in seconds */ function _terminateEmployee(uint256 _employeeId, uint64 _endDate) internal { // Prevent past termination dates require(_endDate >= getTimestamp64(), ERROR_PAST_TERMINATION_DATE); employees[_employeeId].endDate = _endDate; emit TerminateEmployee(_employeeId, _endDate); } /** * @dev Loop over allowed tokens to send requested amount to the employee in their desired allocation * @param _employeeId Employee's identifier * @param _totalAmount Total amount to be transferred to the employee distributed in accordance to the employee's token allocation. * @param _type Payment type being transferred (Payroll, Reimbursement or Bonus) * @param _minRates Array of employee's minimum acceptable rates for their allowed payment tokens * @return True if there was at least one token transfer */ function _transferTokensAmount(uint256 _employeeId, PaymentType _type, uint256 _totalAmount, uint256[] _minRates) internal returns (bool somethingPaid) { if (_totalAmount == 0) { return false; } Employee storage employee = employees[_employeeId]; address employeeAddress = employee.accountAddress; string memory paymentReference = _paymentReferenceFor(_type); address[] storage allocationTokenAddresses = employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; uint256 tokenAllocation = employee.allocationTokens[token]; if (tokenAllocation != uint256(0)) { // Get the exchange rate for the payout token in denomination token, // as we do accounting in denomination tokens uint256 exchangeRate = _getExchangeRateInDenominationToken(token); require(_minRates.length > 0 ? exchangeRate >= _minRates[i] : exchangeRate > 0, ERROR_EXCHANGE_RATE_TOO_LOW); // Convert amount (in denomination tokens) to payout token and apply allocation uint256 tokenAmount = _totalAmount.mul(exchangeRate).mul(tokenAllocation); // Divide by 100 for the allocation percentage and by the exchange rate precision tokenAmount = tokenAmount.div(100).div(feed.ratePrecision()); // Finance reverts if the payment wasn't possible finance.newImmediatePayment(token, employeeAddress, tokenAmount, paymentReference); emit SendPayment(_employeeId, employeeAddress, token, tokenAmount, exchangeRate, paymentReference); somethingPaid = true; } } } /** * @dev Remove employee if there are no owed funds and employee's end date has been reached * @param _employeeId Employee's identifier */ function _removeEmployeeIfTerminatedAndPaidOut(uint256 _employeeId) internal { Employee storage employee = employees[_employeeId]; if ( employee.lastPayroll == employee.endDate && (employee.accruedSalary == 0 && employee.bonus == 0 && employee.reimbursements == 0) ) { delete employeeIds[employee.accountAddress]; delete employees[_employeeId]; } } /** * @dev Updates the accrued salary and payroll date of an employee based on a payment amount and * their currently owed salary since last payroll date * @param _employee Employee struct in storage * @param _paymentAmount Amount being paid to the employee */ function _updateEmployeeAccountingBasedOnPaidSalary(Employee storage _employee, uint256 _paymentAmount) internal { uint256 accruedSalary = _employee.accruedSalary; if (_paymentAmount <= accruedSalary) { // Employee is only cashing out some previously owed salary so we don't need to update // their last payroll date // No need to use SafeMath as we already know _paymentAmount <= accruedSalary _employee.accruedSalary = accruedSalary - _paymentAmount; return; } // Employee is cashing out some of their currently owed salary so their last payroll date // needs to be modified based on the amount of salary paid uint256 currentSalaryPaid = _paymentAmount; if (accruedSalary > 0) { // Employee is cashing out a mixed amount between previous and current owed salaries; // first use up their accrued salary // No need to use SafeMath here as we already know _paymentAmount > accruedSalary currentSalaryPaid = _paymentAmount - accruedSalary; // We finally need to clear their accrued salary _employee.accruedSalary = 0; } uint256 salary = _employee.denominationTokenSalary; uint256 timeDiff = currentSalaryPaid.div(salary); // If they're being paid an amount that doesn't match perfectly with the adjusted time // (up to a seconds' worth of salary), add the second and put the extra remaining salary // into their accrued salary uint256 extraSalary = currentSalaryPaid % salary; if (extraSalary > 0) { timeDiff = timeDiff.add(1); _employee.accruedSalary = salary - extraSalary; } uint256 lastPayrollDate = uint256(_employee.lastPayroll).add(timeDiff); // Even though this function should never receive a currentSalaryPaid value that would // result in the lastPayrollDate being higher than the current time, // let's double check to be safe require(lastPayrollDate <= uint256(getTimestamp64()), ERROR_LAST_PAYROLL_DATE_TOO_BIG); // Already know lastPayrollDate must fit in uint64 from above _employee.lastPayroll = uint64(lastPayrollDate); } /** * @dev Tell whether an employee is registered in this Payroll or not * @param _employeeId Employee's identifier * @return True if the given employee ID belongs to an registered employee, false otherwise */ function _employeeExists(uint256 _employeeId) internal view returns (bool) { return employees[_employeeId].accountAddress != address(0); } /** * @dev Tell whether an employee has a valid token allocation or not. * A valid allocation is one that sums to 100 and only includes allowed tokens. * @param _employee Employee struct in storage * @return Reverts if employee's allocation is invalid */ function _ensureEmployeeTokenAllocationsIsValid(Employee storage _employee) internal view { uint256 sum = 0; address[] memory allocationTokenAddresses = _employee.allocationTokenAddresses; for (uint256 i = 0; i < allocationTokenAddresses.length; i++) { address token = allocationTokenAddresses[i]; require(allowedTokens[token], ERROR_NOT_ALLOWED_TOKEN); sum = sum.add(_employee.allocationTokens[token]); } require(sum == 100, ERROR_DISTRIBUTION_NOT_FULL); } /** * @dev Tell whether an employee is still active or not * @param _employee Employee struct in storage * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeActive(Employee storage _employee) internal view returns (bool) { return _employee.endDate >= getTimestamp64(); } /** * @dev Tell whether an employee id is still active or not * @param _employeeId Employee's identifier * @return True if the employee exists and has an end date that has not been reached yet, false otherwise */ function _isEmployeeIdActive(uint256 _employeeId) internal view returns (bool) { return _isEmployeeActive(employees[_employeeId]); } /** * @dev Get exchange rate for a token based on the denomination token. * As an example, if the denomination token was USD and ETH's price was 100USD, * this would return 0.01 * precision rate for ETH. * @param _token Token to get price of in denomination tokens * @return Exchange rate (multiplied by the PPF rate precision) */ function _getExchangeRateInDenominationToken(address _token) internal view returns (uint256) { // xrt is the number of `_token` that can be exchanged for one `denominationToken` (uint128 xrt, uint64 when) = feed.get( denominationToken, // Base (e.g. USD) _token // Quote (e.g. ETH) ); // Check the price feed is recent enough if (getTimestamp64().sub(when) >= rateExpiryTime) { return 0; } return uint256(xrt); } /** * @dev Get owed salary since last payroll for an employee * @param _employee Employee struct in storage * @param _capped Safely cap the owed salary at max uint * @return Owed salary in denomination tokens since last payroll for the employee. * If _capped is false, it reverts in case of an overflow. */ function _getOwedSalarySinceLastPayroll(Employee storage _employee, bool _capped) internal view returns (uint256) { uint256 timeDiff = _getOwedPayrollPeriod(_employee); if (timeDiff == 0) { return 0; } uint256 salary = _employee.denominationTokenSalary; if (_capped) { // Return max uint if the result overflows uint256 result = salary * timeDiff; return (result / timeDiff != salary) ? MAX_UINT256 : result; } else { return salary.mul(timeDiff); } } /** * @dev Get owed payroll period for an employee * @param _employee Employee struct in storage * @return Owed time in seconds since the employee's last payroll date */ function _getOwedPayrollPeriod(Employee storage _employee) internal view returns (uint256) { // Get the min of current date and termination date uint64 date = _isEmployeeActive(_employee) ? getTimestamp64() : _employee.endDate; // Make sure we don't revert if we try to get the owed salary for an employee whose last // payroll date is now or in the future // This can happen either by adding new employees with start dates in the future, to allow // us to change their salary before their start date, or by terminating an employee and // paying out their full owed salary if (date <= _employee.lastPayroll) { return 0; } // Return time diff in seconds, no need to use SafeMath as the underflow was covered by the previous check return uint256(date - _employee.lastPayroll); } /** * @dev Get owed salary since last payroll for an employee. It will take into account the accrued salary as well. * The result will be capped to max uint256 to avoid having an overflow. * @param _employee Employee struct in storage * @return Employee's total owed salary: current owed payroll since the last payroll date, plus the accrued salary. */ function _getTotalOwedCappedSalary(Employee storage _employee) internal view returns (uint256) { uint256 currentOwedSalary = _getOwedSalarySinceLastPayroll(_employee, true); // cap amount uint256 totalOwedSalary = currentOwedSalary + _employee.accruedSalary; if (totalOwedSalary < currentOwedSalary) { totalOwedSalary = MAX_UINT256; } return totalOwedSalary; } /** * @dev Get payment reference for a given payment type * @param _type Payment type to query the reference of * @return Payment reference for the given payment type */ function _paymentReferenceFor(PaymentType _type) internal pure returns (string memory) { if (_type == PaymentType.Payroll) { return "Employee salary"; } else if (_type == PaymentType.Reimbursement) { return "Employee reimbursement"; } if (_type == PaymentType.Bonus) { return "Employee bonus"; } revert(ERROR_INVALID_PAYMENT_TYPE); } function _ensurePaymentAmount(uint256 _owedAmount, uint256 _requestedAmount) private pure returns (uint256) { require(_owedAmount > 0, ERROR_NOTHING_PAID); require(_owedAmount >= _requestedAmount, ERROR_INVALID_REQUESTED_AMOUNT); return _requestedAmount > 0 ? _requestedAmount : _owedAmount; } } // File @aragon/apps-token-manager/contracts/[email protected] /* * SPDX-License-Identitifer: GPL-3.0-or-later */ /* solium-disable function-order */ pragma solidity 0.4.24; contract TokenManager is ITokenController, IForwarder, AragonApp { using SafeMath for uint256; bytes32 public constant MINT_ROLE = keccak256("MINT_ROLE"); bytes32 public constant ISSUE_ROLE = keccak256("ISSUE_ROLE"); bytes32 public constant ASSIGN_ROLE = keccak256("ASSIGN_ROLE"); bytes32 public constant REVOKE_VESTINGS_ROLE = keccak256("REVOKE_VESTINGS_ROLE"); bytes32 public constant BURN_ROLE = keccak256("BURN_ROLE"); uint256 public constant MAX_VESTINGS_PER_ADDRESS = 50; string private constant ERROR_CALLER_NOT_TOKEN = "TM_CALLER_NOT_TOKEN"; string private constant ERROR_NO_VESTING = "TM_NO_VESTING"; string private constant ERROR_TOKEN_CONTROLLER = "TM_TOKEN_CONTROLLER"; string private constant ERROR_MINT_RECEIVER_IS_TM = "TM_MINT_RECEIVER_IS_TM"; string private constant ERROR_VESTING_TO_TM = "TM_VESTING_TO_TM"; string private constant ERROR_TOO_MANY_VESTINGS = "TM_TOO_MANY_VESTINGS"; string private constant ERROR_WRONG_CLIFF_DATE = "TM_WRONG_CLIFF_DATE"; string private constant ERROR_VESTING_NOT_REVOKABLE = "TM_VESTING_NOT_REVOKABLE"; string private constant ERROR_REVOKE_TRANSFER_FROM_REVERTED = "TM_REVOKE_TRANSFER_FROM_REVERTED"; string private constant ERROR_CAN_NOT_FORWARD = "TM_CAN_NOT_FORWARD"; string private constant ERROR_BALANCE_INCREASE_NOT_ALLOWED = "TM_BALANCE_INC_NOT_ALLOWED"; string private constant ERROR_ASSIGN_TRANSFER_FROM_REVERTED = "TM_ASSIGN_TRANSFER_FROM_REVERTED"; struct TokenVesting { uint256 amount; uint64 start; uint64 cliff; uint64 vesting; bool revokable; } // Note that we COMPLETELY trust this MiniMeToken to not be malicious for proper operation of this contract MiniMeToken public token; uint256 public maxAccountTokens; // We are mimicing an array in the inner mapping, we use a mapping instead to make app upgrade more graceful mapping (address => mapping (uint256 => TokenVesting)) internal vestings; mapping (address => uint256) public vestingsLengths; // Other token specific events can be watched on the token address directly (avoids duplication) event NewVesting(address indexed receiver, uint256 vestingId, uint256 amount); event RevokeVesting(address indexed receiver, uint256 vestingId, uint256 nonVestedAmount); modifier onlyToken() { require(msg.sender == address(token), ERROR_CALLER_NOT_TOKEN); _; } modifier vestingExists(address _holder, uint256 _vestingId) { // TODO: it's not checking for gaps that may appear because of deletes in revokeVesting function require(_vestingId < vestingsLengths[_holder], ERROR_NO_VESTING); _; } /** * @notice Initialize Token Manager for `_token.symbol(): string`, whose tokens are `transferable ? 'not' : ''` transferable`_maxAccountTokens > 0 ? ' and limited to a maximum of ' + @tokenAmount(_token, _maxAccountTokens, false) + ' per account' : ''` * @param _token MiniMeToken address for the managed token (Token Manager instance must be already set as the token controller) * @param _transferable whether the token can be transferred by holders * @param _maxAccountTokens Maximum amount of tokens an account can have (0 for infinite tokens) */ function initialize( MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) external onlyInit { initialized(); require(_token.controller() == address(this), ERROR_TOKEN_CONTROLLER); token = _token; maxAccountTokens = _maxAccountTokens == 0 ? uint256(-1) : _maxAccountTokens; if (token.transfersEnabled() != _transferable) { token.enableTransfers(_transferable); } } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for `_receiver` * @param _receiver The address receiving the tokens, cannot be the Token Manager itself (use `issue()` instead) * @param _amount Number of tokens minted */ function mint(address _receiver, uint256 _amount) external authP(MINT_ROLE, arr(_receiver, _amount)) { require(_receiver != address(this), ERROR_MINT_RECEIVER_IS_TM); _mint(_receiver, _amount); } /** * @notice Mint `@tokenAmount(self.token(): address, _amount, false)` tokens for the Token Manager * @param _amount Number of tokens minted */ function issue(uint256 _amount) external authP(ISSUE_ROLE, arr(_amount)) { _mint(address(this), _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings * @param _receiver The address receiving the tokens * @param _amount Number of tokens transferred */ function assign(address _receiver, uint256 _amount) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) { _assign(_receiver, _amount); } /** * @notice Burn `@tokenAmount(self.token(): address, _amount, false)` tokens from `_holder` * @param _holder Holder of tokens being burned * @param _amount Number of tokens being burned */ function burn(address _holder, uint256 _amount) external authP(BURN_ROLE, arr(_holder, _amount)) { // minime.destroyTokens() never returns false, only reverts on failure token.destroyTokens(_holder, _amount); } /** * @notice Assign `@tokenAmount(self.token(): address, _amount, false)` tokens to `_receiver` from the Token Manager's holdings with a `_revokable : 'revokable' : ''` vesting starting at `@formatDate(_start)`, cliff at `@formatDate(_cliff)` (first portion of tokens transferable), and completed vesting at `@formatDate(_vested)` (all tokens transferable) * @param _receiver The address receiving the tokens, cannot be Token Manager itself * @param _amount Number of tokens vested * @param _start Date the vesting calculations start * @param _cliff Date when the initial portion of tokens are transferable * @param _vested Date when all tokens are transferable * @param _revokable Whether the vesting can be revoked by the Token Manager */ function assignVested( address _receiver, uint256 _amount, uint64 _start, uint64 _cliff, uint64 _vested, bool _revokable ) external authP(ASSIGN_ROLE, arr(_receiver, _amount)) returns (uint256) { require(_receiver != address(this), ERROR_VESTING_TO_TM); require(vestingsLengths[_receiver] < MAX_VESTINGS_PER_ADDRESS, ERROR_TOO_MANY_VESTINGS); require(_start <= _cliff && _cliff <= _vested, ERROR_WRONG_CLIFF_DATE); uint256 vestingId = vestingsLengths[_receiver]++; vestings[_receiver][vestingId] = TokenVesting( _amount, _start, _cliff, _vested, _revokable ); _assign(_receiver, _amount); emit NewVesting(_receiver, vestingId, _amount); return vestingId; } /** * @notice Revoke vesting #`_vestingId` from `_holder`, returning unvested tokens to the Token Manager * @param _holder Address whose vesting to revoke * @param _vestingId Numeric id of the vesting */ function revokeVesting(address _holder, uint256 _vestingId) external authP(REVOKE_VESTINGS_ROLE, arr(_holder)) vestingExists(_holder, _vestingId) { TokenVesting storage v = vestings[_holder][_vestingId]; require(v.revokable, ERROR_VESTING_NOT_REVOKABLE); uint256 nonVested = _calculateNonVestedTokens( v.amount, getTimestamp(), v.start, v.cliff, v.vesting ); // To make vestingIds immutable over time, we just zero out the revoked vesting // Clearing this out also allows the token transfer back to the Token Manager to succeed delete vestings[_holder][_vestingId]; // transferFrom always works as controller // onTransfer hook always allows if transfering to token controller require(token.transferFrom(_holder, address(this), nonVested), ERROR_REVOKE_TRANSFER_FROM_REVERTED); emit RevokeVesting(_holder, _vestingId, nonVested); } // ITokenController fns // `onTransfer()`, `onApprove()`, and `proxyPayment()` are callbacks from the MiniMe token // contract and are only meant to be called through the managed MiniMe token that gets assigned // during initialization. /* * @dev Notifies the controller about a token transfer allowing the controller to decide whether * to allow it or react if desired (only callable from the token). * Initialization check is implicitly provided by `onlyToken()`. * @param _from The origin of the transfer * @param _to The destination of the transfer * @param _amount The amount of the transfer * @return False if the controller does not authorize the transfer */ function onTransfer(address _from, address _to, uint256 _amount) external onlyToken returns (bool) { return _isBalanceIncreaseAllowed(_to, _amount) && _transferableBalance(_from, getTimestamp()) >= _amount; } /** * @dev Notifies the controller about an approval allowing the controller to react if desired * Initialization check is implicitly provided by `onlyToken()`. * @return False if the controller does not authorize the approval */ function onApprove(address, address, uint) external onlyToken returns (bool) { return true; } /** * @dev Called when ether is sent to the MiniMe Token contract * Initialization check is implicitly provided by `onlyToken()`. * @return True if the ether is accepted, false for it to throw */ function proxyPayment(address) external payable onlyToken returns (bool) { return false; } // Forwarding fns function isForwarder() external pure returns (bool) { return true; } /** * @notice Execute desired action as a token holder * @dev IForwarder interface conformance. Forwards any token holder action. * @param _evmScript Script being executed */ function forward(bytes _evmScript) public { require(canForward(msg.sender, _evmScript), ERROR_CAN_NOT_FORWARD); bytes memory input = new bytes(0); // TODO: Consider input for this // Add the managed token to the blacklist to disallow a token holder from executing actions // on the token controller's (this contract) behalf address[] memory blacklist = new address[](1); blacklist[0] = address(token); runScript(_evmScript, input, blacklist); } function canForward(address _sender, bytes) public view returns (bool) { return hasInitialized() && token.balanceOf(_sender) > 0; } // Getter fns function getVesting( address _recipient, uint256 _vestingId ) public view vestingExists(_recipient, _vestingId) returns ( uint256 amount, uint64 start, uint64 cliff, uint64 vesting, bool revokable ) { TokenVesting storage tokenVesting = vestings[_recipient][_vestingId]; amount = tokenVesting.amount; start = tokenVesting.start; cliff = tokenVesting.cliff; vesting = tokenVesting.vesting; revokable = tokenVesting.revokable; } function spendableBalanceOf(address _holder) public view isInitialized returns (uint256) { return _transferableBalance(_holder, getTimestamp()); } function transferableBalance(address _holder, uint256 _time) public view isInitialized returns (uint256) { return _transferableBalance(_holder, _time); } /** * @dev Disable recovery escape hatch for own token, * as the it has the concept of issuing tokens without assigning them */ function allowRecoverability(address _token) public view returns (bool) { return _token != address(token); } // Internal fns function _assign(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); // Must use transferFrom() as transfer() does not give the token controller full control require(token.transferFrom(address(this), _receiver, _amount), ERROR_ASSIGN_TRANSFER_FROM_REVERTED); } function _mint(address _receiver, uint256 _amount) internal { require(_isBalanceIncreaseAllowed(_receiver, _amount), ERROR_BALANCE_INCREASE_NOT_ALLOWED); token.generateTokens(_receiver, _amount); // minime.generateTokens() never returns false } function _isBalanceIncreaseAllowed(address _receiver, uint256 _inc) internal view returns (bool) { // Max balance doesn't apply to the token manager itself if (_receiver == address(this)) { return true; } return token.balanceOf(_receiver).add(_inc) <= maxAccountTokens; } /** * @dev Calculate amount of non-vested tokens at a specifc time * @param tokens The total amount of tokens vested * @param time The time at which to check * @param start The date vesting started * @param cliff The cliff period * @param vested The fully vested date * @return The amount of non-vested tokens of a specific grant * transferableTokens * | _/-------- vestedTokens rect * | _/ * | _/ * | _/ * | _/ * | / * | .| * | . | * | . | * | . | * | . | * | . | * +===+===========+---------+----------> time * Start Cliff Vested */ function _calculateNonVestedTokens( uint256 tokens, uint256 time, uint256 start, uint256 cliff, uint256 vested ) private pure returns (uint256) { // Shortcuts for before cliff and after vested cases. if (time >= vested) { return 0; } if (time < cliff) { return tokens; } // Interpolate all vested tokens. // As before cliff the shortcut returns 0, we can just calculate a value // in the vesting rect (as shown in above's figure) // vestedTokens = tokens * (time - start) / (vested - start) // In assignVesting we enforce start <= cliff <= vested // Here we shortcut time >= vested and time < cliff, // so no division by 0 is possible uint256 vestedTokens = tokens.mul(time.sub(start)) / vested.sub(start); // tokens - vestedTokens return tokens.sub(vestedTokens); } function _transferableBalance(address _holder, uint256 _time) internal view returns (uint256) { uint256 transferable = token.balanceOf(_holder); // This check is not strictly necessary for the current version of this contract, as // Token Managers now cannot assign vestings to themselves. // However, this was a possibility in the past, so in case there were vestings assigned to // themselves, this will still return the correct value (entire balance, as the Token // Manager does not have a spending limit on its own balance). if (_holder != address(this)) { uint256 vestingsCount = vestingsLengths[_holder]; for (uint256 i = 0; i < vestingsCount; i++) { TokenVesting storage v = vestings[_holder][i]; uint256 nonTransferable = _calculateNonVestedTokens( v.amount, _time, v.start, v.cliff, v.vesting ); transferable = transferable.sub(nonTransferable); } } return transferable; } } // File @aragon/apps-survey/contracts/[email protected] /* * SPDX-License-Identitifer: GPL-3.0-or-later */ pragma solidity 0.4.24; contract Survey is AragonApp { using SafeMath for uint256; using SafeMath64 for uint64; bytes32 public constant CREATE_SURVEYS_ROLE = keccak256("CREATE_SURVEYS_ROLE"); bytes32 public constant MODIFY_PARTICIPATION_ROLE = keccak256("MODIFY_PARTICIPATION_ROLE"); uint64 public constant PCT_BASE = 10 ** 18; // 0% = 0; 1% = 10^16; 100% = 10^18 uint256 public constant ABSTAIN_VOTE = 0; string private constant ERROR_MIN_PARTICIPATION = "SURVEY_MIN_PARTICIPATION"; string private constant ERROR_NO_SURVEY = "SURVEY_NO_SURVEY"; string private constant ERROR_NO_VOTING_POWER = "SURVEY_NO_VOTING_POWER"; string private constant ERROR_CAN_NOT_VOTE = "SURVEY_CAN_NOT_VOTE"; string private constant ERROR_VOTE_WRONG_INPUT = "SURVEY_VOTE_WRONG_INPUT"; string private constant ERROR_VOTE_WRONG_OPTION = "SURVEY_VOTE_WRONG_OPTION"; string private constant ERROR_NO_STAKE = "SURVEY_NO_STAKE"; string private constant ERROR_OPTIONS_NOT_ORDERED = "SURVEY_OPTIONS_NOT_ORDERED"; string private constant ERROR_NO_OPTION = "SURVEY_NO_OPTION"; struct OptionCast { uint256 optionId; uint256 stake; } /* Allows for multiple option votes. * Index 0 is always used for the ABSTAIN_VOTE option, that's calculated automatically by the * contract. */ struct MultiOptionVote { uint256 optionsCastedLength; // `castedVotes` simulates an array // Each OptionCast in `castedVotes` must be ordered by ascending option IDs mapping (uint256 => OptionCast) castedVotes; } struct SurveyStruct { uint64 startDate; uint64 snapshotBlock; uint64 minParticipationPct; uint256 options; uint256 votingPower; // total tokens that can cast a vote uint256 participation; // tokens that casted a vote // Note that option IDs are from 1 to `options`, due to ABSTAIN_VOTE taking 0 mapping (uint256 => uint256) optionPower; // option ID -> voting power for option mapping (address => MultiOptionVote) votes; // voter -> options voted, with its stakes } MiniMeToken public token; uint64 public minParticipationPct; uint64 public surveyTime; // We are mimicing an array, we use a mapping instead to make app upgrade more graceful mapping (uint256 => SurveyStruct) internal surveys; uint256 public surveysLength; event StartSurvey(uint256 indexed surveyId, address indexed creator, string metadata); event CastVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 stake, uint256 optionPower); event ResetVote(uint256 indexed surveyId, address indexed voter, uint256 option, uint256 previousStake, uint256 optionPower); event ChangeMinParticipation(uint64 minParticipationPct); modifier acceptableMinParticipationPct(uint64 _minParticipationPct) { require(_minParticipationPct > 0 && _minParticipationPct <= PCT_BASE, ERROR_MIN_PARTICIPATION); _; } modifier surveyExists(uint256 _surveyId) { require(_surveyId < surveysLength, ERROR_NO_SURVEY); _; } /** * @notice Initialize Survey app with `_token.symbol(): string` for governance, minimum acceptance participation of `@formatPct(_minParticipationPct)`%, and a voting duration of `@transformTime(_surveyTime)` * @param _token MiniMeToken address that will be used as governance token * @param _minParticipationPct Percentage of total voting power that must participate in a survey for it to be taken into account (expressed as a 10^18 percentage, (eg 10^16 = 1%, 10^18 = 100%) * @param _surveyTime Seconds that a survey will be open for token holders to vote */ function initialize( MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime ) external onlyInit acceptableMinParticipationPct(_minParticipationPct) { initialized(); token = _token; minParticipationPct = _minParticipationPct; surveyTime = _surveyTime; } /** * @notice Change minimum acceptance participation to `@formatPct(_minParticipationPct)`% * @param _minParticipationPct New acceptance participation */ function changeMinAcceptParticipationPct(uint64 _minParticipationPct) external authP(MODIFY_PARTICIPATION_ROLE, arr(uint256(_minParticipationPct), uint256(minParticipationPct))) acceptableMinParticipationPct(_minParticipationPct) { minParticipationPct = _minParticipationPct; emit ChangeMinParticipation(_minParticipationPct); } /** * @notice Create a new non-binding survey about "`_metadata`" * @param _metadata Survey metadata * @param _options Number of options voters can decide between * @return surveyId id for newly created survey */ function newSurvey(string _metadata, uint256 _options) external auth(CREATE_SURVEYS_ROLE) returns (uint256 surveyId) { uint64 snapshotBlock = getBlockNumber64() - 1; // avoid double voting in this very block uint256 votingPower = token.totalSupplyAt(snapshotBlock); require(votingPower > 0, ERROR_NO_VOTING_POWER); surveyId = surveysLength++; SurveyStruct storage survey = surveys[surveyId]; survey.startDate = getTimestamp64(); survey.snapshotBlock = snapshotBlock; // avoid double voting in this very block survey.minParticipationPct = minParticipationPct; survey.options = _options; survey.votingPower = votingPower; emit StartSurvey(surveyId, msg.sender, _metadata); } /** * @notice Reset previously casted vote in survey #`_surveyId`, if any. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey */ function resetVote(uint256 _surveyId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _resetVote(_surveyId); } /** * @notice Vote for multiple options in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @param _surveyId Id for survey * @param _optionIds Array with indexes of supported options * @param _stakes Number of tokens assigned to each option */ function voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) external surveyExists(_surveyId) { require(_optionIds.length == _stakes.length && _optionIds.length > 0, ERROR_VOTE_WRONG_INPUT); require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); _voteOptions(_surveyId, _optionIds, _stakes); } /** * @notice Vote option #`_optionId` in survey #`_surveyId`. * @dev Initialization check is implicitly provided by `surveyExists()` as new surveys can only * be created via `newSurvey(),` which requires initialization * @dev It will use the whole balance. * @param _surveyId Id for survey * @param _optionId Index of supported option */ function voteOption(uint256 _surveyId, uint256 _optionId) external surveyExists(_surveyId) { require(canVote(_surveyId, msg.sender), ERROR_CAN_NOT_VOTE); SurveyStruct storage survey = surveys[_surveyId]; // This could re-enter, though we can asume the governance token is not maliciuous uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256[] memory options = new uint256[](1); uint256[] memory stakes = new uint256[](1); options[0] = _optionId; stakes[0] = voterStake; _voteOptions(_surveyId, options, stakes); } // Getter fns function canVote(uint256 _surveyId, address _voter) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; return _isSurveyOpen(survey) && token.balanceOfAt(_voter, survey.snapshotBlock) > 0; } function getSurvey(uint256 _surveyId) public view surveyExists(_surveyId) returns ( bool open, uint64 startDate, uint64 snapshotBlock, uint64 minParticipation, uint256 votingPower, uint256 participation, uint256 options ) { SurveyStruct storage survey = surveys[_surveyId]; open = _isSurveyOpen(survey); startDate = survey.startDate; snapshotBlock = survey.snapshotBlock; minParticipation = survey.minParticipationPct; votingPower = survey.votingPower; participation = survey.participation; options = survey.options; } /** * @dev This is not meant to be used on-chain */ /* solium-disable-next-line function-order */ function getVoterState(uint256 _surveyId, address _voter) external view surveyExists(_surveyId) returns (uint256[] options, uint256[] stakes) { MultiOptionVote storage vote = surveys[_surveyId].votes[_voter]; if (vote.optionsCastedLength == 0) { return (new uint256[](0), new uint256[](0)); } options = new uint256[](vote.optionsCastedLength + 1); stakes = new uint256[](vote.optionsCastedLength + 1); for (uint256 i = 0; i <= vote.optionsCastedLength; i++) { options[i] = vote.castedVotes[i].optionId; stakes[i] = vote.castedVotes[i].stake; } } function getOptionPower(uint256 _surveyId, uint256 _optionId) public view surveyExists(_surveyId) returns (uint256) { SurveyStruct storage survey = surveys[_surveyId]; require(_optionId <= survey.options, ERROR_NO_OPTION); return survey.optionPower[_optionId]; } function isParticipationAchieved(uint256 _surveyId) public view surveyExists(_surveyId) returns (bool) { SurveyStruct storage survey = surveys[_surveyId]; // votingPower is always > 0 uint256 participationPct = survey.participation.mul(PCT_BASE) / survey.votingPower; return participationPct >= survey.minParticipationPct; } // Internal fns /* * @dev Assumes the survey exists and that msg.sender can vote */ function _resetVote(uint256 _surveyId) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage previousVote = survey.votes[msg.sender]; if (previousVote.optionsCastedLength > 0) { // Voter removes their vote (index 0 is the abstain vote) for (uint256 i = 1; i <= previousVote.optionsCastedLength; i++) { OptionCast storage previousOptionCast = previousVote.castedVotes[i]; uint256 previousOptionPower = survey.optionPower[previousOptionCast.optionId]; uint256 currentOptionPower = previousOptionPower.sub(previousOptionCast.stake); survey.optionPower[previousOptionCast.optionId] = currentOptionPower; emit ResetVote(_surveyId, msg.sender, previousOptionCast.optionId, previousOptionCast.stake, currentOptionPower); } // Compute previously casted votes (i.e. substract non-used tokens from stake) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); uint256 previousParticipation = voterStake.sub(previousVote.castedVotes[0].stake); // And remove it from total participation survey.participation = survey.participation.sub(previousParticipation); // Reset previously voted options delete survey.votes[msg.sender]; } } /* * @dev Assumes the survey exists and that msg.sender can vote */ function _voteOptions(uint256 _surveyId, uint256[] _optionIds, uint256[] _stakes) internal { SurveyStruct storage survey = surveys[_surveyId]; MultiOptionVote storage senderVotes = survey.votes[msg.sender]; // Revert previous votes, if any _resetVote(_surveyId); uint256 totalVoted = 0; // Reserve first index for ABSTAIN_VOTE senderVotes.castedVotes[0] = OptionCast({ optionId: ABSTAIN_VOTE, stake: 0 }); for (uint256 optionIndex = 1; optionIndex <= _optionIds.length; optionIndex++) { // Voters don't specify that they're abstaining, // but we still keep track of this by reserving the first index of a survey's votes. // We subtract 1 from the indexes of the arrays passed in by the voter to account for this. uint256 optionId = _optionIds[optionIndex - 1]; uint256 stake = _stakes[optionIndex - 1]; require(optionId != ABSTAIN_VOTE && optionId <= survey.options, ERROR_VOTE_WRONG_OPTION); require(stake > 0, ERROR_NO_STAKE); // Let's avoid repeating an option by making sure that ascending order is preserved in // the options array by checking that the current optionId is larger than the last one // we added require(senderVotes.castedVotes[optionIndex - 1].optionId < optionId, ERROR_OPTIONS_NOT_ORDERED); // Register voter amount senderVotes.castedVotes[optionIndex] = OptionCast({ optionId: optionId, stake: stake }); // Add to total option support survey.optionPower[optionId] = survey.optionPower[optionId].add(stake); // Keep track of stake used so far totalVoted = totalVoted.add(stake); emit CastVote(_surveyId, msg.sender, optionId, stake, survey.optionPower[optionId]); } // Compute and register non used tokens // Implictly we are doing require(totalVoted <= voterStake) too // (as stated before, index 0 is for ABSTAIN_VOTE option) uint256 voterStake = token.balanceOfAt(msg.sender, survey.snapshotBlock); senderVotes.castedVotes[0].stake = voterStake.sub(totalVoted); // Register number of options voted senderVotes.optionsCastedLength = _optionIds.length; // Add voter tokens to participation survey.participation = survey.participation.add(totalVoted); assert(survey.participation <= survey.votingPower); } function _isSurveyOpen(SurveyStruct storage _survey) internal view returns (bool) { return getTimestamp64() < _survey.startDate.add(surveyTime); } } // File @aragon/os/contracts/acl/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; interface IACLOracle { function canPerform(address who, address where, bytes32 what, uint256[] how) external view returns (bool); } // File @aragon/os/contracts/acl/[email protected] pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ACL is IACL, TimeHelpers, AragonApp, ACLHelpers { /* Hardcoded constants to save gas bytes32 public constant CREATE_PERMISSIONS_ROLE = keccak256("CREATE_PERMISSIONS_ROLE"); */ bytes32 public constant CREATE_PERMISSIONS_ROLE = 0x0b719b33c83b8e5d300c521cb8b54ae9bd933996a14bef8c2f4e0285d2d2400a; enum Op { NONE, EQ, NEQ, GT, LT, GTE, LTE, RET, NOT, AND, OR, XOR, IF_ELSE } // op types struct Param { uint8 id; uint8 op; uint240 value; // even though value is an uint240 it can store addresses // in the case of 32 byte hashes losing 2 bytes precision isn't a huge deal // op and id take less than 1 byte each so it can be kept in 1 sstore } uint8 internal constant BLOCK_NUMBER_PARAM_ID = 200; uint8 internal constant TIMESTAMP_PARAM_ID = 201; // 202 is unused uint8 internal constant ORACLE_PARAM_ID = 203; uint8 internal constant LOGIC_OP_PARAM_ID = 204; uint8 internal constant PARAM_VALUE_PARAM_ID = 205; // TODO: Add execution times param type? /* Hardcoded constant to save gas bytes32 public constant EMPTY_PARAM_HASH = keccak256(uint256(0)); */ bytes32 public constant EMPTY_PARAM_HASH = 0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563; bytes32 public constant NO_PERMISSION = bytes32(0); address public constant ANY_ENTITY = address(-1); address public constant BURN_ENTITY = address(1); // address(0) is already used as "no permission manager" uint256 internal constant ORACLE_CHECK_GAS = 30000; string private constant ERROR_AUTH_INIT_KERNEL = "ACL_AUTH_INIT_KERNEL"; string private constant ERROR_AUTH_NO_MANAGER = "ACL_AUTH_NO_MANAGER"; string private constant ERROR_EXISTENT_MANAGER = "ACL_EXISTENT_MANAGER"; // Whether someone has a permission mapping (bytes32 => bytes32) internal permissions; // permissions hash => params hash mapping (bytes32 => Param[]) internal permissionParams; // params hash => params // Who is the manager of a permission mapping (bytes32 => address) internal permissionManager; event SetPermission(address indexed entity, address indexed app, bytes32 indexed role, bool allowed); event SetPermissionParams(address indexed entity, address indexed app, bytes32 indexed role, bytes32 paramsHash); event ChangePermissionManager(address indexed app, bytes32 indexed role, address indexed manager); modifier onlyPermissionManager(address _app, bytes32 _role) { require(msg.sender == getPermissionManager(_app, _role), ERROR_AUTH_NO_MANAGER); _; } modifier noPermissionManager(address _app, bytes32 _role) { // only allow permission creation (or re-creation) when there is no manager require(getPermissionManager(_app, _role) == address(0), ERROR_EXISTENT_MANAGER); _; } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize an ACL instance and set `_permissionsCreator` as the entity that can create other permissions * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(address _permissionsCreator) public onlyInit { initialized(); require(msg.sender == address(kernel()), ERROR_AUTH_INIT_KERNEL); _createPermission(_permissionsCreator, this, CREATE_PERMISSIONS_ROLE, _permissionsCreator); } /** * @dev Creates a permission that wasn't previously set and managed. * If a created permission is removed it is possible to reset it with createPermission. * This is the **ONLY** way to create permissions and set managers to permissions that don't * have a manager. * In terms of the ACL being initialized, this function implicitly protects all the other * state-changing external functions, as they all require the sender to be a manager. * @notice Create a new permission granting `_entity` the ability to perform actions requiring `_role` on `_app`, setting `_manager` as the permission's manager * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _manager Address of the entity that will be able to grant and revoke the permission further. */ function createPermission(address _entity, address _app, bytes32 _role, address _manager) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _createPermission(_entity, _app, _role, _manager); } /** * @dev Grants permission if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform */ function grantPermission(address _entity, address _app, bytes32 _role) external { grantPermissionP(_entity, _app, _role, new uint256[](0)); } /** * @dev Grants a permission with parameters if allowed. This requires `msg.sender` to be the permission manager * @notice Grant `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app in which the role will be allowed (requires app to depend on kernel for ACL) * @param _role Identifier for the group of actions in app given access to perform * @param _params Permission parameters */ function grantPermissionP(address _entity, address _app, bytes32 _role, uint256[] _params) public onlyPermissionManager(_app, _role) { bytes32 paramsHash = _params.length > 0 ? _saveParams(_params) : EMPTY_PARAM_HASH; _setPermission(_entity, _app, _role, paramsHash); } /** * @dev Revokes permission if allowed. This requires `msg.sender` to be the the permission manager * @notice Revoke from `_entity` the ability to perform actions requiring `_role` on `_app` * @param _entity Address of the whitelisted entity to revoke access from * @param _app Address of the app in which the role will be revoked * @param _role Identifier for the group of actions in app being revoked */ function revokePermission(address _entity, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermission(_entity, _app, _role, NO_PERMISSION); } /** * @notice Set `_newManager` as the manager of `_role` in `_app` * @param _newManager Address for the new manager * @param _app Address of the app in which the permission management is being transferred * @param _role Identifier for the group of actions being transferred */ function setPermissionManager(address _newManager, address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(_newManager, _app, _role); } /** * @notice Remove the manager of `_role` in `_app` * @param _app Address of the app in which the permission is being unmanaged * @param _role Identifier for the group of actions being unmanaged */ function removePermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(address(0), _app, _role); } /** * @notice Burn non-existent `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function createBurnedPermission(address _app, bytes32 _role) external auth(CREATE_PERMISSIONS_ROLE) noPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Burn `_role` in `_app`, so no modification can be made to it (grant, revoke, permission manager) * @param _app Address of the app in which the permission is being burned * @param _role Identifier for the group of actions being burned */ function burnPermissionManager(address _app, bytes32 _role) external onlyPermissionManager(_app, _role) { _setPermissionManager(BURN_ENTITY, _app, _role); } /** * @notice Get parameters for permission array length * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return Length of the array */ function getPermissionParamsLength(address _entity, address _app, bytes32 _role) external view returns (uint) { return permissionParams[permissions[permissionHash(_entity, _app, _role)]].length; } /** * @notice Get parameter for permission * @param _entity Address of the whitelisted entity that will be able to perform the role * @param _app Address of the app * @param _role Identifier for a group of actions in app * @param _index Index of parameter in the array * @return Parameter (id, op, value) */ function getPermissionParam(address _entity, address _app, bytes32 _role, uint _index) external view returns (uint8, uint8, uint240) { Param storage param = permissionParams[permissions[permissionHash(_entity, _app, _role)]][_index]; return (param.id, param.op, param.value); } /** * @dev Get manager for permission * @param _app Address of the app * @param _role Identifier for a group of actions in app * @return address of the manager for the permission */ function getPermissionManager(address _app, bytes32 _role) public view returns (address) { return permissionManager[roleHash(_app, _role)]; } /** * @dev Function called by apps to check ACL on kernel or to check permission statu * @param _who Sender of the original call * @param _where Address of the app * @param _where Identifier for a group of actions in app * @param _how Permission parameters * @return boolean indicating whether the ACL allows the role or not */ function hasPermission(address _who, address _where, bytes32 _what, bytes memory _how) public view returns (bool) { return hasPermission(_who, _where, _what, ConversionHelpers.dangerouslyCastBytesToUintArray(_how)); } function hasPermission(address _who, address _where, bytes32 _what, uint256[] memory _how) public view returns (bool) { bytes32 whoParams = permissions[permissionHash(_who, _where, _what)]; if (whoParams != NO_PERMISSION && evalParams(whoParams, _who, _where, _what, _how)) { return true; } bytes32 anyParams = permissions[permissionHash(ANY_ENTITY, _where, _what)]; if (anyParams != NO_PERMISSION && evalParams(anyParams, ANY_ENTITY, _where, _what, _how)) { return true; } return false; } function hasPermission(address _who, address _where, bytes32 _what) public view returns (bool) { uint256[] memory empty = new uint256[](0); return hasPermission(_who, _where, _what, empty); } function evalParams( bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how ) public view returns (bool) { if (_paramsHash == EMPTY_PARAM_HASH) { return true; } return _evalParam(_paramsHash, 0, _who, _where, _what, _how); } /** * @dev Internal createPermission for access inside the kernel (on instantiation) */ function _createPermission(address _entity, address _app, bytes32 _role, address _manager) internal { _setPermission(_entity, _app, _role, EMPTY_PARAM_HASH); _setPermissionManager(_manager, _app, _role); } /** * @dev Internal function called to actually save the permission */ function _setPermission(address _entity, address _app, bytes32 _role, bytes32 _paramsHash) internal { permissions[permissionHash(_entity, _app, _role)] = _paramsHash; bool entityHasPermission = _paramsHash != NO_PERMISSION; bool permissionHasParams = entityHasPermission && _paramsHash != EMPTY_PARAM_HASH; emit SetPermission(_entity, _app, _role, entityHasPermission); if (permissionHasParams) { emit SetPermissionParams(_entity, _app, _role, _paramsHash); } } function _saveParams(uint256[] _encodedParams) internal returns (bytes32) { bytes32 paramHash = keccak256(abi.encodePacked(_encodedParams)); Param[] storage params = permissionParams[paramHash]; if (params.length == 0) { // params not saved before for (uint256 i = 0; i < _encodedParams.length; i++) { uint256 encodedParam = _encodedParams[i]; Param memory param = Param(decodeParamId(encodedParam), decodeParamOp(encodedParam), uint240(encodedParam)); params.push(param); } } return paramHash; } function _evalParam( bytes32 _paramsHash, uint32 _paramId, address _who, address _where, bytes32 _what, uint256[] _how ) internal view returns (bool) { if (_paramId >= permissionParams[_paramsHash].length) { return false; // out of bounds } Param memory param = permissionParams[_paramsHash][_paramId]; if (param.id == LOGIC_OP_PARAM_ID) { return _evalLogic(param, _paramsHash, _who, _where, _what, _how); } uint256 value; uint256 comparedTo = uint256(param.value); // get value if (param.id == ORACLE_PARAM_ID) { value = checkOracle(IACLOracle(param.value), _who, _where, _what, _how) ? 1 : 0; comparedTo = 1; } else if (param.id == BLOCK_NUMBER_PARAM_ID) { value = getBlockNumber(); } else if (param.id == TIMESTAMP_PARAM_ID) { value = getTimestamp(); } else if (param.id == PARAM_VALUE_PARAM_ID) { value = uint256(param.value); } else { if (param.id >= _how.length) { return false; } value = uint256(uint240(_how[param.id])); // force lost precision } if (Op(param.op) == Op.RET) { return uint256(value) > 0; } return compare(value, Op(param.op), comparedTo); } function _evalLogic(Param _param, bytes32 _paramsHash, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { if (Op(_param.op) == Op.IF_ELSE) { uint32 conditionParam; uint32 successParam; uint32 failureParam; (conditionParam, successParam, failureParam) = decodeParamsList(uint256(_param.value)); bool result = _evalParam(_paramsHash, conditionParam, _who, _where, _what, _how); return _evalParam(_paramsHash, result ? successParam : failureParam, _who, _where, _what, _how); } uint32 param1; uint32 param2; (param1, param2,) = decodeParamsList(uint256(_param.value)); bool r1 = _evalParam(_paramsHash, param1, _who, _where, _what, _how); if (Op(_param.op) == Op.NOT) { return !r1; } if (r1 && Op(_param.op) == Op.OR) { return true; } if (!r1 && Op(_param.op) == Op.AND) { return false; } bool r2 = _evalParam(_paramsHash, param2, _who, _where, _what, _how); if (Op(_param.op) == Op.XOR) { return r1 != r2; } return r2; // both or and and depend on result of r2 after checks } function compare(uint256 _a, Op _op, uint256 _b) internal pure returns (bool) { if (_op == Op.EQ) return _a == _b; // solium-disable-line lbrace if (_op == Op.NEQ) return _a != _b; // solium-disable-line lbrace if (_op == Op.GT) return _a > _b; // solium-disable-line lbrace if (_op == Op.LT) return _a < _b; // solium-disable-line lbrace if (_op == Op.GTE) return _a >= _b; // solium-disable-line lbrace if (_op == Op.LTE) return _a <= _b; // solium-disable-line lbrace return false; } function checkOracle(IACLOracle _oracleAddr, address _who, address _where, bytes32 _what, uint256[] _how) internal view returns (bool) { bytes4 sig = _oracleAddr.canPerform.selector; // a raw call is required so we can return false if the call reverts, rather than reverting bytes memory checkCalldata = abi.encodeWithSelector(sig, _who, _where, _what, _how); uint256 oracleCheckGas = ORACLE_CHECK_GAS; bool ok; assembly { ok := staticcall(oracleCheckGas, _oracleAddr, add(checkCalldata, 0x20), mload(checkCalldata), 0, 0) } if (!ok) { return false; } uint256 size; assembly { size := returndatasize } if (size != 32) { return false; } bool result; assembly { let ptr := mload(0x40) // get next free memory ptr returndatacopy(ptr, 0, size) // copy return from above `staticcall` result := mload(ptr) // read data at ptr and set it to result mstore(ptr, 0) // set pointer memory to 0 so it still is the next free ptr } return result; } /** * @dev Internal function that sets management */ function _setPermissionManager(address _newManager, address _app, bytes32 _role) internal { permissionManager[roleHash(_app, _role)] = _newManager; emit ChangePermissionManager(_app, _role, _newManager); } function roleHash(address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("ROLE", _where, _what)); } function permissionHash(address _who, address _where, bytes32 _what) internal pure returns (bytes32) { return keccak256(abi.encodePacked("PERMISSION", _who, _where, _what)); } } // File @aragon/os/contracts/apm/[email protected] pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract Repo is AragonApp { /* Hardcoded constants to save gas bytes32 public constant CREATE_VERSION_ROLE = keccak256("CREATE_VERSION_ROLE"); */ bytes32 public constant CREATE_VERSION_ROLE = 0x1f56cfecd3595a2e6cc1a7e6cb0b20df84cdbd92eff2fee554e70e4e45a9a7d8; string private constant ERROR_INVALID_BUMP = "REPO_INVALID_BUMP"; string private constant ERROR_INVALID_VERSION = "REPO_INVALID_VERSION"; string private constant ERROR_INEXISTENT_VERSION = "REPO_INEXISTENT_VERSION"; struct Version { uint16[3] semanticVersion; address contractAddress; bytes contentURI; } uint256 internal versionsNextIndex; mapping (uint256 => Version) internal versions; mapping (bytes32 => uint256) internal versionIdForSemantic; mapping (address => uint256) internal latestVersionIdForContract; event NewVersion(uint256 versionId, uint16[3] semanticVersion); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this Repo */ function initialize() public onlyInit { initialized(); versionsNextIndex = 1; } /** * @notice Create new version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _newSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newVersion( uint16[3] _newSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_VERSION_ROLE) { address contractAddress = _contractAddress; uint256 lastVersionIndex = versionsNextIndex - 1; uint16[3] memory lastSematicVersion; if (lastVersionIndex > 0) { Version storage lastVersion = versions[lastVersionIndex]; lastSematicVersion = lastVersion.semanticVersion; if (contractAddress == address(0)) { contractAddress = lastVersion.contractAddress; } // Only allows smart contract change on major version bumps require( lastVersion.contractAddress == contractAddress || _newSemanticVersion[0] > lastVersion.semanticVersion[0], ERROR_INVALID_VERSION ); } require(isValidBump(lastSematicVersion, _newSemanticVersion), ERROR_INVALID_BUMP); uint256 versionId = versionsNextIndex++; versions[versionId] = Version(_newSemanticVersion, contractAddress, _contentURI); versionIdForSemantic[semanticVersionHash(_newSemanticVersion)] = versionId; latestVersionIdForContract[contractAddress] = versionId; emit NewVersion(versionId, _newSemanticVersion); } function getLatest() public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionsNextIndex - 1); } function getLatestForContractAddress(address _contractAddress) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(latestVersionIdForContract[_contractAddress]); } function getBySemanticVersion(uint16[3] _semanticVersion) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { return getByVersionId(versionIdForSemantic[semanticVersionHash(_semanticVersion)]); } function getByVersionId(uint _versionId) public view returns (uint16[3] semanticVersion, address contractAddress, bytes contentURI) { require(_versionId > 0 && _versionId < versionsNextIndex, ERROR_INEXISTENT_VERSION); Version storage version = versions[_versionId]; return (version.semanticVersion, version.contractAddress, version.contentURI); } function getVersionsCount() public view returns (uint256) { return versionsNextIndex - 1; } function isValidBump(uint16[3] _oldVersion, uint16[3] _newVersion) public pure returns (bool) { bool hasBumped; uint i = 0; while (i < 3) { if (hasBumped) { if (_newVersion[i] != 0) { return false; } } else if (_newVersion[i] != _oldVersion[i]) { if (_oldVersion[i] > _newVersion[i] || _newVersion[i] - _oldVersion[i] != 1) { return false; } hasBumped = true; } i++; } return hasBumped; } function semanticVersionHash(uint16[3] version) internal pure returns (bytes32) { return keccak256(abi.encodePacked(version[0], version[1], version[2])); } } // File @aragon/os/contracts/apm/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract APMNamehash { /* Hardcoded constants to save gas bytes32 internal constant APM_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, keccak256(abi.encodePacked("aragonpm")))); */ bytes32 internal constant APM_NODE = 0x9065c3e7f7b7ef1ef4e53d2d0b8e0cef02874ab020c1ece79d5f0d3d0111c0ba; function apmNamehash(string name) internal pure returns (bytes32) { return keccak256(abi.encodePacked(APM_NODE, keccak256(bytes(name)))); } } // File @aragon/os/contracts/kernel/[email protected] pragma solidity 0.4.24; contract KernelStorage { // namespace => app id => address mapping (bytes32 => mapping (bytes32 => address)) public apps; bytes32 public recoveryVaultAppId; } // File @aragon/os/contracts/lib/misc/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ERCProxy { uint256 internal constant FORWARDING = 1; uint256 internal constant UPGRADEABLE = 2; function proxyType() public pure returns (uint256 proxyTypeId); function implementation() public view returns (address codeAddr); } // File @aragon/os/contracts/common/[email protected] pragma solidity 0.4.24; contract DelegateProxy is ERCProxy, IsContract { uint256 internal constant FWD_GAS_LIMIT = 10000; /** * @dev Performs a delegatecall and returns whatever the delegatecall returned (entire context execution will return!) * @param _dst Destination address to perform the delegatecall * @param _calldata Calldata for the delegatecall */ function delegatedFwd(address _dst, bytes _calldata) internal { require(isContract(_dst)); uint256 fwdGasLimit = FWD_GAS_LIMIT; assembly { let result := delegatecall(sub(gas, fwdGasLimit), _dst, add(_calldata, 0x20), mload(_calldata), 0, 0) let size := returndatasize let ptr := mload(0x40) returndatacopy(ptr, 0, size) // revert instead of invalid() bc if the underlying call failed with invalid() it already wasted gas. // if the call returned error data, forward it switch result case 0 { revert(ptr, size) } default { return(ptr, size) } } } } // File @aragon/os/contracts/common/[email protected] pragma solidity 0.4.24; contract DepositableDelegateProxy is DepositableStorage, DelegateProxy { event ProxyDeposit(address sender, uint256 value); function () external payable { // send / transfer if (gasleft() < FWD_GAS_LIMIT) { require(msg.value > 0 && msg.data.length == 0); require(isDepositable()); emit ProxyDeposit(msg.sender, msg.value); } else { // all calls except for send or transfer address target = implementation(); delegatedFwd(target, msg.data); } } } // File @aragon/os/contracts/apps/[email protected] pragma solidity 0.4.24; contract AppProxyBase is AppStorage, DepositableDelegateProxy, KernelNamespaceConstants { /** * @dev Initialize AppProxy * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public { setKernel(_kernel); setAppId(_appId); // Implicit check that kernel is actually a Kernel // The EVM doesn't actually provide a way for us to make sure, but we can force a revert to // occur if the kernel is set to 0x0 or a non-code address when we try to call a method on // it. address appCode = getAppBase(_appId); // If initialize payload is provided, it will be executed if (_initializePayload.length > 0) { require(isContract(appCode)); // Cannot make delegatecall as a delegateproxy.delegatedFwd as it // returns ending execution context and halts contract deployment require(appCode.delegatecall(_initializePayload)); } } function getAppBase(bytes32 _appId) internal view returns (address) { return kernel().getApp(KERNEL_APP_BASES_NAMESPACE, _appId); } } // File @aragon/os/contracts/apps/[email protected] pragma solidity 0.4.24; contract AppProxyUpgradeable is AppProxyBase { /** * @dev Initialize AppProxyUpgradeable (makes it an upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { // solium-disable-previous-line no-empty-blocks } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return getAppBase(appId()); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } } // File @aragon/os/contracts/apps/[email protected] pragma solidity 0.4.24; contract AppProxyPinned is IsContract, AppProxyBase { using UnstructuredStorage for bytes32; // keccak256("aragonOS.appStorage.pinnedCode") bytes32 internal constant PINNED_CODE_POSITION = 0xdee64df20d65e53d7f51cb6ab6d921a0a6a638a91e942e1d8d02df28e31c038e; /** * @dev Initialize AppProxyPinned (makes it an un-upgradeable Aragon app) * @param _kernel Reference to organization kernel for the app * @param _appId Identifier for app * @param _initializePayload Payload for call to be made after setup to initialize */ constructor(IKernel _kernel, bytes32 _appId, bytes _initializePayload) AppProxyBase(_kernel, _appId, _initializePayload) public // solium-disable-line visibility-first { setPinnedCode(getAppBase(_appId)); require(isContract(pinnedCode())); } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return pinnedCode(); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return FORWARDING; } function setPinnedCode(address _pinnedCode) internal { PINNED_CODE_POSITION.setStorageAddress(_pinnedCode); } function pinnedCode() internal view returns (address) { return PINNED_CODE_POSITION.getStorageAddress(); } } // File @aragon/os/contracts/factory/[email protected] pragma solidity 0.4.24; contract AppProxyFactory { event NewAppProxy(address proxy, bool isUpgradeable, bytes32 appId); /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId) public returns (AppProxyUpgradeable) { return newAppProxy(_kernel, _appId, new bytes(0)); } /** * @notice Create a new upgradeable app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyUpgradeable */ function newAppProxy(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyUpgradeable) { AppProxyUpgradeable proxy = new AppProxyUpgradeable(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), true, _appId); return proxy; } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId) public returns (AppProxyPinned) { return newAppProxyPinned(_kernel, _appId, new bytes(0)); } /** * @notice Create a new pinned app instance on `_kernel` with identifier `_appId` and initialization payload `_initializePayload` * @param _kernel App's Kernel reference * @param _appId Identifier for app * @param _initializePayload Proxy initialization payload * @return AppProxyPinned */ function newAppProxyPinned(IKernel _kernel, bytes32 _appId, bytes _initializePayload) public returns (AppProxyPinned) { AppProxyPinned proxy = new AppProxyPinned(_kernel, _appId, _initializePayload); emit NewAppProxy(address(proxy), false, _appId); return proxy; } } // File @aragon/os/contracts/kernel/[email protected] pragma solidity 0.4.24; // solium-disable-next-line max-len contract Kernel is IKernel, KernelStorage, KernelAppIds, KernelNamespaceConstants, Petrifiable, IsContract, VaultRecoverable, AppProxyFactory, ACLSyntaxSugar { /* Hardcoded constants to save gas bytes32 public constant APP_MANAGER_ROLE = keccak256("APP_MANAGER_ROLE"); */ bytes32 public constant APP_MANAGER_ROLE = 0xb6d92708f3d4817afc106147d969e229ced5c46e65e0a5002a0d391287762bd0; string private constant ERROR_APP_NOT_CONTRACT = "KERNEL_APP_NOT_CONTRACT"; string private constant ERROR_INVALID_APP_CHANGE = "KERNEL_INVALID_APP_CHANGE"; string private constant ERROR_AUTH_FAILED = "KERNEL_AUTH_FAILED"; /** * @dev Constructor that allows the deployer to choose if the base instance should be petrified immediately. * @param _shouldPetrify Immediately petrify this instance so that it can never be initialized */ constructor(bool _shouldPetrify) public { if (_shouldPetrify) { petrify(); } } /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. * @notice Initialize this kernel instance along with its ACL and set `_permissionsCreator` as the entity that can create other permissions * @param _baseAcl Address of base ACL app * @param _permissionsCreator Entity that will be given permission over createPermission */ function initialize(IACL _baseAcl, address _permissionsCreator) public onlyInit { initialized(); // Set ACL base _setApp(KERNEL_APP_BASES_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, _baseAcl); // Create ACL instance and attach it as the default ACL app IACL acl = IACL(newAppProxy(this, KERNEL_DEFAULT_ACL_APP_ID)); acl.initialize(_permissionsCreator); _setApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID, acl); recoveryVaultAppId = KERNEL_DEFAULT_VAULT_APP_ID; } /** * @dev Create a new instance of an app linked to this kernel * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new instance of an app linked to this kernel and set its base * implementation if it was not already set * @notice Create a new upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxy(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Create a new pinned instance of an app linked to this kernel * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { return newPinnedAppInstance(_appId, _appBase, new bytes(0), false); } /** * @dev Create a new pinned instance of an app linked to this kernel and set * its base implementation if it was not already set * @notice Create a new non-upgradeable instance of `_appId` app linked to the Kernel, setting its code to `_appBase`. `_setDefault ? 'Also sets it as the default app instance.':''` * @param _appId Identifier for app * @param _appBase Address of the app's base implementation * @param _initializePayload Payload for call made by the proxy during its construction to initialize * @param _setDefault Whether the app proxy app is the default one. * Useful when the Kernel needs to know of an instance of a particular app, * like Vault for escape hatch mechanism. * @return AppProxy instance */ function newPinnedAppInstance(bytes32 _appId, address _appBase, bytes _initializePayload, bool _setDefault) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_BASES_NAMESPACE, _appId)) returns (ERCProxy appProxy) { _setAppIfNew(KERNEL_APP_BASES_NAMESPACE, _appId, _appBase); appProxy = newAppProxyPinned(this, _appId, _initializePayload); // By calling setApp directly and not the internal functions, we make sure the params are checked // and it will only succeed if sender has permissions to set something to the namespace. if (_setDefault) { setApp(KERNEL_APP_ADDR_NAMESPACE, _appId, appProxy); } } /** * @dev Set the resolving address of an app instance or base implementation * @notice Set the resolving address of `_appId` in namespace `_namespace` to `_app` * @param _namespace App namespace to use * @param _appId Identifier for app * @param _app Address of the app instance or base implementation * @return ID of app */ function setApp(bytes32 _namespace, bytes32 _appId, address _app) public auth(APP_MANAGER_ROLE, arr(_namespace, _appId)) { _setApp(_namespace, _appId, _app); } /** * @dev Set the default vault id for the escape hatch mechanism * @param _recoveryVaultAppId Identifier of the recovery vault app */ function setRecoveryVaultAppId(bytes32 _recoveryVaultAppId) public auth(APP_MANAGER_ROLE, arr(KERNEL_APP_ADDR_NAMESPACE, _recoveryVaultAppId)) { recoveryVaultAppId = _recoveryVaultAppId; } // External access to default app id and namespace constants to mimic default getters for constants /* solium-disable function-order, mixedcase */ function CORE_NAMESPACE() external pure returns (bytes32) { return KERNEL_CORE_NAMESPACE; } function APP_BASES_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_BASES_NAMESPACE; } function APP_ADDR_NAMESPACE() external pure returns (bytes32) { return KERNEL_APP_ADDR_NAMESPACE; } function KERNEL_APP_ID() external pure returns (bytes32) { return KERNEL_CORE_APP_ID; } function DEFAULT_ACL_APP_ID() external pure returns (bytes32) { return KERNEL_DEFAULT_ACL_APP_ID; } /* solium-enable function-order, mixedcase */ /** * @dev Get the address of an app instance or base implementation * @param _namespace App namespace to use * @param _appId Identifier for app * @return Address of the app */ function getApp(bytes32 _namespace, bytes32 _appId) public view returns (address) { return apps[_namespace][_appId]; } /** * @dev Get the address of the recovery Vault instance (to recover funds) * @return Address of the Vault */ function getRecoveryVault() public view returns (address) { return apps[KERNEL_APP_ADDR_NAMESPACE][recoveryVaultAppId]; } /** * @dev Get the installed ACL app * @return ACL app */ function acl() public view returns (IACL) { return IACL(getApp(KERNEL_APP_ADDR_NAMESPACE, KERNEL_DEFAULT_ACL_APP_ID)); } /** * @dev Function called by apps to check ACL on kernel or to check permission status * @param _who Sender of the original call * @param _where Address of the app * @param _what Identifier for a group of actions in app * @param _how Extra data for ACL auth * @return Boolean indicating whether the ACL allows the role or not. * Always returns false if the kernel hasn't been initialized yet. */ function hasPermission(address _who, address _where, bytes32 _what, bytes _how) public view returns (bool) { IACL defaultAcl = acl(); return address(defaultAcl) != address(0) && // Poor man's initialization check (saves gas) defaultAcl.hasPermission(_who, _where, _what, _how); } function _setApp(bytes32 _namespace, bytes32 _appId, address _app) internal { require(isContract(_app), ERROR_APP_NOT_CONTRACT); apps[_namespace][_appId] = _app; emit SetApp(_namespace, _appId, _app); } function _setAppIfNew(bytes32 _namespace, bytes32 _appId, address _app) internal { address app = getApp(_namespace, _appId); if (app != address(0)) { // The only way to set an app is if it passes the isContract check, so no need to check it again require(app == _app, ERROR_INVALID_APP_CHANGE); } else { _setApp(_namespace, _appId, _app); } } modifier auth(bytes32 _role, uint256[] memory _params) { require( hasPermission(msg.sender, address(this), _role, ConversionHelpers.dangerouslyCastUintArrayToBytes(_params)), ERROR_AUTH_FAILED ); _; } } // File @aragon/os/contracts/lib/ens/[email protected] // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/AbstractENS.sol pragma solidity ^0.4.15; interface AbstractENS { function owner(bytes32 _node) public constant returns (address); function resolver(bytes32 _node) public constant returns (address); function ttl(bytes32 _node) public constant returns (uint64); function setOwner(bytes32 _node, address _owner) public; function setSubnodeOwner(bytes32 _node, bytes32 label, address _owner) public; function setResolver(bytes32 _node, address _resolver) public; function setTTL(bytes32 _node, uint64 _ttl) public; // Logged when the owner of a node assigns a new owner to a subnode. event NewOwner(bytes32 indexed _node, bytes32 indexed _label, address _owner); // Logged when the owner of a node transfers ownership to a new account. event Transfer(bytes32 indexed _node, address _owner); // Logged when the resolver for a node changes. event NewResolver(bytes32 indexed _node, address _resolver); // Logged when the TTL of a node changes event NewTTL(bytes32 indexed _node, uint64 _ttl); } // File @aragon/os/contracts/lib/ens/[email protected] // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/ENS.sol pragma solidity ^0.4.0; /** * The ENS registry contract. */ contract ENS is AbstractENS { struct Record { address owner; address resolver; uint64 ttl; } mapping(bytes32=>Record) records; // Permits modifications only by the owner of the specified node. modifier only_owner(bytes32 node) { if (records[node].owner != msg.sender) throw; _; } /** * Constructs a new ENS registrar. */ function ENS() public { records[0].owner = msg.sender; } /** * Returns the address that owns the specified node. */ function owner(bytes32 node) public constant returns (address) { return records[node].owner; } /** * Returns the address of the resolver for the specified node. */ function resolver(bytes32 node) public constant returns (address) { return records[node].resolver; } /** * Returns the TTL of a node, and any records associated with it. */ function ttl(bytes32 node) public constant returns (uint64) { return records[node].ttl; } /** * Transfers ownership of a node to a new address. May only be called by the current * owner of the node. * @param node The node to transfer ownership of. * @param owner The address of the new owner. */ function setOwner(bytes32 node, address owner) only_owner(node) public { Transfer(node, owner); records[node].owner = owner; } /** * Transfers ownership of a subnode keccak256(node, label) to a new address. May only be * called by the owner of the parent node. * @param node The parent node. * @param label The hash of the label specifying the subnode. * @param owner The address of the new owner. */ function setSubnodeOwner(bytes32 node, bytes32 label, address owner) only_owner(node) public { var subnode = keccak256(node, label); NewOwner(node, label, owner); records[subnode].owner = owner; } /** * Sets the resolver address for the specified node. * @param node The node to update. * @param resolver The address of the resolver. */ function setResolver(bytes32 node, address resolver) only_owner(node) public { NewResolver(node, resolver); records[node].resolver = resolver; } /** * Sets the TTL for the specified node. * @param node The node to update. * @param ttl The TTL in seconds. */ function setTTL(bytes32 node, uint64 ttl) only_owner(node) public { NewTTL(node, ttl); records[node].ttl = ttl; } } // File @aragon/os/contracts/lib/ens/[email protected] // See https://github.com/ensdomains/ens/blob/7e377df83f/contracts/PublicResolver.sol pragma solidity ^0.4.0; /** * A simple resolver anyone can use; only allows the owner of a node to set its * address. */ contract PublicResolver { bytes4 constant INTERFACE_META_ID = 0x01ffc9a7; bytes4 constant ADDR_INTERFACE_ID = 0x3b3b57de; bytes4 constant CONTENT_INTERFACE_ID = 0xd8389dc5; bytes4 constant NAME_INTERFACE_ID = 0x691f3431; bytes4 constant ABI_INTERFACE_ID = 0x2203ab56; bytes4 constant PUBKEY_INTERFACE_ID = 0xc8690233; bytes4 constant TEXT_INTERFACE_ID = 0x59d1d43c; event AddrChanged(bytes32 indexed node, address a); event ContentChanged(bytes32 indexed node, bytes32 hash); event NameChanged(bytes32 indexed node, string name); event ABIChanged(bytes32 indexed node, uint256 indexed contentType); event PubkeyChanged(bytes32 indexed node, bytes32 x, bytes32 y); event TextChanged(bytes32 indexed node, string indexed indexedKey, string key); struct PublicKey { bytes32 x; bytes32 y; } struct Record { address addr; bytes32 content; string name; PublicKey pubkey; mapping(string=>string) text; mapping(uint256=>bytes) abis; } AbstractENS ens; mapping(bytes32=>Record) records; modifier only_owner(bytes32 node) { if (ens.owner(node) != msg.sender) throw; _; } /** * Constructor. * @param ensAddr The ENS registrar contract. */ function PublicResolver(AbstractENS ensAddr) public { ens = ensAddr; } /** * Returns true if the resolver implements the interface specified by the provided hash. * @param interfaceID The ID of the interface to check for. * @return True if the contract implements the requested interface. */ function supportsInterface(bytes4 interfaceID) public pure returns (bool) { return interfaceID == ADDR_INTERFACE_ID || interfaceID == CONTENT_INTERFACE_ID || interfaceID == NAME_INTERFACE_ID || interfaceID == ABI_INTERFACE_ID || interfaceID == PUBKEY_INTERFACE_ID || interfaceID == TEXT_INTERFACE_ID || interfaceID == INTERFACE_META_ID; } /** * Returns the address associated with an ENS node. * @param node The ENS node to query. * @return The associated address. */ function addr(bytes32 node) public constant returns (address ret) { ret = records[node].addr; } /** * Sets the address associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param addr The address to set. */ function setAddr(bytes32 node, address addr) only_owner(node) public { records[node].addr = addr; AddrChanged(node, addr); } /** * Returns the content hash associated with an ENS node. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The ENS node to query. * @return The associated content hash. */ function content(bytes32 node) public constant returns (bytes32 ret) { ret = records[node].content; } /** * Sets the content hash associated with an ENS node. * May only be called by the owner of that node in the ENS registry. * Note that this resource type is not standardized, and will likely change * in future to a resource type based on multihash. * @param node The node to update. * @param hash The content hash to set */ function setContent(bytes32 node, bytes32 hash) only_owner(node) public { records[node].content = hash; ContentChanged(node, hash); } /** * Returns the name associated with an ENS node, for reverse records. * Defined in EIP181. * @param node The ENS node to query. * @return The associated name. */ function name(bytes32 node) public constant returns (string ret) { ret = records[node].name; } /** * Sets the name associated with an ENS node, for reverse records. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param name The name to set. */ function setName(bytes32 node, string name) only_owner(node) public { records[node].name = name; NameChanged(node, name); } /** * Returns the ABI associated with an ENS node. * Defined in EIP205. * @param node The ENS node to query * @param contentTypes A bitwise OR of the ABI formats accepted by the caller. * @return contentType The content type of the return value * @return data The ABI data */ function ABI(bytes32 node, uint256 contentTypes) public constant returns (uint256 contentType, bytes data) { var record = records[node]; for(contentType = 1; contentType <= contentTypes; contentType <<= 1) { if ((contentType & contentTypes) != 0 && record.abis[contentType].length > 0) { data = record.abis[contentType]; return; } } contentType = 0; } /** * Sets the ABI associated with an ENS node. * Nodes may have one ABI of each content type. To remove an ABI, set it to * the empty string. * @param node The node to update. * @param contentType The content type of the ABI * @param data The ABI data. */ function setABI(bytes32 node, uint256 contentType, bytes data) only_owner(node) public { // Content types must be powers of 2 if (((contentType - 1) & contentType) != 0) throw; records[node].abis[contentType] = data; ABIChanged(node, contentType); } /** * Returns the SECP256k1 public key associated with an ENS node. * Defined in EIP 619. * @param node The ENS node to query * @return x, y the X and Y coordinates of the curve point for the public key. */ function pubkey(bytes32 node) public constant returns (bytes32 x, bytes32 y) { return (records[node].pubkey.x, records[node].pubkey.y); } /** * Sets the SECP256k1 public key associated with an ENS node. * @param node The ENS node to query * @param x the X coordinate of the curve point for the public key. * @param y the Y coordinate of the curve point for the public key. */ function setPubkey(bytes32 node, bytes32 x, bytes32 y) only_owner(node) public { records[node].pubkey = PublicKey(x, y); PubkeyChanged(node, x, y); } /** * Returns the text data associated with an ENS node and key. * @param node The ENS node to query. * @param key The text data key to query. * @return The associated text data. */ function text(bytes32 node, string key) public constant returns (string ret) { ret = records[node].text[key]; } /** * Sets the text data associated with an ENS node and key. * May only be called by the owner of that node in the ENS registry. * @param node The node to update. * @param key The key to set. * @param value The text data value to set. */ function setText(bytes32 node, string key, string value) only_owner(node) public { records[node].text[key] = value; TextChanged(node, key, key); } } // File @aragon/os/contracts/kernel/[email protected] pragma solidity 0.4.24; contract KernelProxy is IKernelEvents, KernelStorage, KernelAppIds, KernelNamespaceConstants, IsContract, DepositableDelegateProxy { /** * @dev KernelProxy is a proxy contract to a kernel implementation. The implementation * can update the reference, which effectively upgrades the contract * @param _kernelImpl Address of the contract used as implementation for kernel */ constructor(IKernel _kernelImpl) public { require(isContract(address(_kernelImpl))); apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID] = _kernelImpl; // Note that emitting this event is important for verifying that a KernelProxy instance // was never upgraded to a malicious Kernel logic contract over its lifespan. // This starts the "chain of trust", that can be followed through later SetApp() events // emitted during kernel upgrades. emit SetApp(KERNEL_CORE_NAMESPACE, KERNEL_CORE_APP_ID, _kernelImpl); } /** * @dev ERC897, whether it is a forwarding (1) or an upgradeable (2) proxy */ function proxyType() public pure returns (uint256 proxyTypeId) { return UPGRADEABLE; } /** * @dev ERC897, the address the proxy would delegate calls to */ function implementation() public view returns (address) { return apps[KERNEL_CORE_NAMESPACE][KERNEL_CORE_APP_ID]; } } // File @aragon/os/contracts/evmscript/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; library ScriptHelpers { function getSpecId(bytes _script) internal pure returns (uint32) { return uint32At(_script, 0); } function uint256At(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := mload(add(_data, add(0x20, _location))) } } function addressAt(bytes _data, uint256 _location) internal pure returns (address result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffffffffffffffffffffffffffffffffffff000000000000000000000000), 0x1000000000000000000000000) } } function uint32At(bytes _data, uint256 _location) internal pure returns (uint32 result) { uint256 word = uint256At(_data, _location); assembly { result := div(and(word, 0xffffffff00000000000000000000000000000000000000000000000000000000), 0x100000000000000000000000000000000000000000000000000000000) } } function locationOf(bytes _data, uint256 _location) internal pure returns (uint256 result) { assembly { result := add(_data, add(0x20, _location)) } } function toBytes(bytes4 _sig) internal pure returns (bytes) { bytes memory payload = new bytes(4); assembly { mstore(add(payload, 0x20), _sig) } return payload; } } // File @aragon/os/contracts/evmscript/[email protected] pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract EVMScriptRegistry is IEVMScriptRegistry, EVMScriptRegistryConstants, AragonApp { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = keccak256("REGISTRY_ADD_EXECUTOR_ROLE"); bytes32 public constant REGISTRY_MANAGER_ROLE = keccak256("REGISTRY_MANAGER_ROLE"); */ bytes32 public constant REGISTRY_ADD_EXECUTOR_ROLE = 0xc4e90f38eea8c4212a009ca7b8947943ba4d4a58d19b683417f65291d1cd9ed2; // WARN: Manager can censor all votes and the like happening in an org bytes32 public constant REGISTRY_MANAGER_ROLE = 0xf7a450ef335e1892cb42c8ca72e7242359d7711924b75db5717410da3f614aa3; uint256 internal constant SCRIPT_START_LOCATION = 4; string private constant ERROR_INEXISTENT_EXECUTOR = "EVMREG_INEXISTENT_EXECUTOR"; string private constant ERROR_EXECUTOR_ENABLED = "EVMREG_EXECUTOR_ENABLED"; string private constant ERROR_EXECUTOR_DISABLED = "EVMREG_EXECUTOR_DISABLED"; string private constant ERROR_SCRIPT_LENGTH_TOO_SHORT = "EVMREG_SCRIPT_LENGTH_TOO_SHORT"; struct ExecutorEntry { IEVMScriptExecutor executor; bool enabled; } uint256 private executorsNextIndex; mapping (uint256 => ExecutorEntry) public executors; event EnableExecutor(uint256 indexed executorId, address indexed executorAddress); event DisableExecutor(uint256 indexed executorId, address indexed executorAddress); modifier executorExists(uint256 _executorId) { require(_executorId > 0 && _executorId < executorsNextIndex, ERROR_INEXISTENT_EXECUTOR); _; } /** * @notice Initialize the registry */ function initialize() public onlyInit { initialized(); // Create empty record to begin executor IDs at 1 executorsNextIndex = 1; } /** * @notice Add a new script executor with address `_executor` to the registry * @param _executor Address of the IEVMScriptExecutor that will be added to the registry * @return id Identifier of the executor in the registry */ function addScriptExecutor(IEVMScriptExecutor _executor) external auth(REGISTRY_ADD_EXECUTOR_ROLE) returns (uint256 id) { uint256 executorId = executorsNextIndex++; executors[executorId] = ExecutorEntry(_executor, true); emit EnableExecutor(executorId, _executor); return executorId; } /** * @notice Disable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function disableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) { // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage executorEntry = executors[_executorId]; require(executorEntry.enabled, ERROR_EXECUTOR_DISABLED); executorEntry.enabled = false; emit DisableExecutor(_executorId, executorEntry.executor); } /** * @notice Enable script executor with ID `_executorId` * @param _executorId Identifier of the executor in the registry */ function enableScriptExecutor(uint256 _executorId) external authP(REGISTRY_MANAGER_ROLE, arr(_executorId)) executorExists(_executorId) { ExecutorEntry storage executorEntry = executors[_executorId]; require(!executorEntry.enabled, ERROR_EXECUTOR_ENABLED); executorEntry.enabled = true; emit EnableExecutor(_executorId, executorEntry.executor); } /** * @dev Get the script executor that can execute a particular script based on its first 4 bytes * @param _script EVMScript being inspected */ function getScriptExecutor(bytes _script) public view returns (IEVMScriptExecutor) { require(_script.length >= SCRIPT_START_LOCATION, ERROR_SCRIPT_LENGTH_TOO_SHORT); uint256 id = _script.getSpecId(); // Note that we don't need to check for an executor's existence in this case, as only // existing executors can be enabled ExecutorEntry storage entry = executors[id]; return entry.enabled ? entry.executor : IEVMScriptExecutor(0); } } // File @aragon/os/contracts/evmscript/executors/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract BaseEVMScriptExecutor is IEVMScriptExecutor, Autopetrified { uint256 internal constant SCRIPT_START_LOCATION = 4; } // File @aragon/os/contracts/evmscript/executors/[email protected] pragma solidity 0.4.24; // Inspired by https://github.com/reverendus/tx-manager contract CallsScript is BaseEVMScriptExecutor { using ScriptHelpers for bytes; /* Hardcoded constants to save gas bytes32 internal constant EXECUTOR_TYPE = keccak256("CALLS_SCRIPT"); */ bytes32 internal constant EXECUTOR_TYPE = 0x2dc858a00f3e417be1394b87c07158e989ec681ce8cc68a9093680ac1a870302; string private constant ERROR_BLACKLISTED_CALL = "EVMCALLS_BLACKLISTED_CALL"; string private constant ERROR_INVALID_LENGTH = "EVMCALLS_INVALID_LENGTH"; /* This is manually crafted in assembly string private constant ERROR_CALL_REVERTED = "EVMCALLS_CALL_REVERTED"; */ event LogScriptCall(address indexed sender, address indexed src, address indexed dst); /** * @notice Executes a number of call scripts * @param _script [ specId (uint32) ] many calls with this structure -> * [ to (address: 20 bytes) ] [ calldataLength (uint32: 4 bytes) ] [ calldata (calldataLength bytes) ] * @param _blacklist Addresses the script cannot call to, or will revert. * @return Always returns empty byte array */ function execScript(bytes _script, bytes, address[] _blacklist) external isInitialized returns (bytes) { uint256 location = SCRIPT_START_LOCATION; // first 32 bits are spec id while (location < _script.length) { // Check there's at least address + calldataLength available require(_script.length - location >= 0x18, ERROR_INVALID_LENGTH); address contractAddress = _script.addressAt(location); // Check address being called is not blacklist for (uint256 i = 0; i < _blacklist.length; i++) { require(contractAddress != _blacklist[i], ERROR_BLACKLISTED_CALL); } // logged before execution to ensure event ordering in receipt // if failed entire execution is reverted regardless emit LogScriptCall(msg.sender, address(this), contractAddress); uint256 calldataLength = uint256(_script.uint32At(location + 0x14)); uint256 startOffset = location + 0x14 + 0x04; uint256 calldataStart = _script.locationOf(startOffset); // compute end of script / next location location = startOffset + calldataLength; require(location <= _script.length, ERROR_INVALID_LENGTH); bool success; assembly { success := call( sub(gas, 5000), // forward gas left - 5000 contractAddress, // address 0, // no value calldataStart, // calldata start calldataLength, // calldata length 0, // don't write output 0 // don't write output ) switch success case 0 { let ptr := mload(0x40) switch returndatasize case 0 { // No error data was returned, revert with "EVMCALLS_CALL_REVERTED" // See remix: doing a `revert("EVMCALLS_CALL_REVERTED")` always results in // this memory layout mstore(ptr, 0x08c379a000000000000000000000000000000000000000000000000000000000) // error identifier mstore(add(ptr, 0x04), 0x0000000000000000000000000000000000000000000000000000000000000020) // starting offset mstore(add(ptr, 0x24), 0x0000000000000000000000000000000000000000000000000000000000000016) // reason length mstore(add(ptr, 0x44), 0x45564d43414c4c535f43414c4c5f524556455254454400000000000000000000) // reason revert(ptr, 100) // 100 = 4 + 3 * 32 (error identifier + 3 words for the ABI encoded error) } default { // Forward the full error data returndatacopy(ptr, 0, returndatasize) revert(ptr, returndatasize) } } default { } } } // No need to allocate empty bytes for the return as this can only be called via an delegatecall // (due to the isInitialized modifier) } function executorType() external pure returns (bytes32) { return EXECUTOR_TYPE; } } // File @aragon/os/contracts/factory/[email protected] pragma solidity 0.4.24; contract EVMScriptRegistryFactory is EVMScriptRegistryConstants { EVMScriptRegistry public baseReg; IEVMScriptExecutor public baseCallScript; /** * @notice Create a new EVMScriptRegistryFactory. */ constructor() public { baseReg = new EVMScriptRegistry(); baseCallScript = IEVMScriptExecutor(new CallsScript()); } /** * @notice Install a new pinned instance of EVMScriptRegistry on `_dao`. * @param _dao Kernel * @return Installed EVMScriptRegistry */ function newEVMScriptRegistry(Kernel _dao) public returns (EVMScriptRegistry reg) { bytes memory initPayload = abi.encodeWithSelector(reg.initialize.selector); reg = EVMScriptRegistry(_dao.newPinnedAppInstance(EVMSCRIPT_REGISTRY_APP_ID, baseReg, initPayload, true)); ACL acl = ACL(_dao.acl()); acl.createPermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE(), this); reg.addScriptExecutor(baseCallScript); // spec 1 = CallsScript // Clean up the permissions acl.revokePermission(this, reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); acl.removePermissionManager(reg, reg.REGISTRY_ADD_EXECUTOR_ROLE()); return reg; } } // File @aragon/os/contracts/factory/[email protected] pragma solidity 0.4.24; contract DAOFactory { IKernel public baseKernel; IACL public baseACL; EVMScriptRegistryFactory public regFactory; event DeployDAO(address dao); event DeployEVMScriptRegistry(address reg); /** * @notice Create a new DAOFactory, creating DAOs with Kernels proxied to `_baseKernel`, ACLs proxied to `_baseACL`, and new EVMScriptRegistries created from `_regFactory`. * @param _baseKernel Base Kernel * @param _baseACL Base ACL * @param _regFactory EVMScriptRegistry factory */ constructor(IKernel _baseKernel, IACL _baseACL, EVMScriptRegistryFactory _regFactory) public { // No need to init as it cannot be killed by devops199 if (address(_regFactory) != address(0)) { regFactory = _regFactory; } baseKernel = _baseKernel; baseACL = _baseACL; } /** * @notice Create a new DAO with `_root` set as the initial admin * @param _root Address that will be granted control to setup DAO permissions * @return Newly created DAO */ function newDAO(address _root) public returns (Kernel) { Kernel dao = Kernel(new KernelProxy(baseKernel)); if (address(regFactory) == address(0)) { dao.initialize(baseACL, _root); } else { dao.initialize(baseACL, this); ACL acl = ACL(dao.acl()); bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); bytes32 appManagerRole = dao.APP_MANAGER_ROLE(); acl.grantPermission(regFactory, acl, permRole); acl.createPermission(regFactory, dao, appManagerRole, this); EVMScriptRegistry reg = regFactory.newEVMScriptRegistry(dao); emit DeployEVMScriptRegistry(address(reg)); // Clean up permissions // First, completely reset the APP_MANAGER_ROLE acl.revokePermission(regFactory, dao, appManagerRole); acl.removePermissionManager(dao, appManagerRole); // Then, make root the only holder and manager of CREATE_PERMISSIONS_ROLE acl.revokePermission(regFactory, acl, permRole); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); } emit DeployDAO(address(dao)); return dao; } } // File @aragon/id/contracts/ens/[email protected] pragma solidity ^0.4.0; interface IPublicResolver { function supportsInterface(bytes4 interfaceID) constant returns (bool); function addr(bytes32 node) constant returns (address ret); function setAddr(bytes32 node, address addr); function hash(bytes32 node) constant returns (bytes32 ret); function setHash(bytes32 node, bytes32 hash); } // File @aragon/id/contracts/[email protected] pragma solidity 0.4.24; interface IFIFSResolvingRegistrar { function register(bytes32 _subnode, address _owner) external; function registerWithResolver(bytes32 _subnode, address _owner, IPublicResolver _resolver) public; } // File @aragon/templates-shared/contracts/[email protected] pragma solidity 0.4.24; contract BaseTemplate is APMNamehash, IsContract { using Uint256Helpers for uint256; /* Hardcoded constant to save gas * bytes32 constant internal AGENT_APP_ID = apmNamehash("agent"); // agent.aragonpm.eth * bytes32 constant internal VAULT_APP_ID = apmNamehash("vault"); // vault.aragonpm.eth * bytes32 constant internal VOTING_APP_ID = apmNamehash("voting"); // voting.aragonpm.eth * bytes32 constant internal SURVEY_APP_ID = apmNamehash("survey"); // survey.aragonpm.eth * bytes32 constant internal PAYROLL_APP_ID = apmNamehash("payroll"); // payroll.aragonpm.eth * bytes32 constant internal FINANCE_APP_ID = apmNamehash("finance"); // finance.aragonpm.eth * bytes32 constant internal TOKEN_MANAGER_APP_ID = apmNamehash("token-manager"); // token-manager.aragonpm.eth */ bytes32 constant internal AGENT_APP_ID = 0x9ac98dc5f995bf0211ed589ef022719d1487e5cb2bab505676f0d084c07cf89a; bytes32 constant internal VAULT_APP_ID = 0x7e852e0fcfce6551c13800f1e7476f982525c2b5277ba14b24339c68416336d1; bytes32 constant internal VOTING_APP_ID = 0x9fa3927f639745e587912d4b0fea7ef9013bf93fb907d29faeab57417ba6e1d4; bytes32 constant internal PAYROLL_APP_ID = 0x463f596a96d808cb28b5d080181e4a398bc793df2c222f6445189eb801001991; bytes32 constant internal FINANCE_APP_ID = 0xbf8491150dafc5dcaee5b861414dca922de09ccffa344964ae167212e8c673ae; bytes32 constant internal TOKEN_MANAGER_APP_ID = 0x6b20a3010614eeebf2138ccec99f028a61c811b3b1a3343b6ff635985c75c91f; bytes32 constant internal SURVEY_APP_ID = 0x030b2ab880b88e228f2da5a3d19a2a31bc10dbf91fb1143776a6de489389471e; string constant private ERROR_ENS_NOT_CONTRACT = "TEMPLATE_ENS_NOT_CONTRACT"; string constant private ERROR_DAO_FACTORY_NOT_CONTRACT = "TEMPLATE_DAO_FAC_NOT_CONTRACT"; string constant private ERROR_ARAGON_ID_NOT_PROVIDED = "TEMPLATE_ARAGON_ID_NOT_PROVIDED"; string constant private ERROR_ARAGON_ID_NOT_CONTRACT = "TEMPLATE_ARAGON_ID_NOT_CONTRACT"; string constant private ERROR_MINIME_FACTORY_NOT_PROVIDED = "TEMPLATE_MINIME_FAC_NOT_PROVIDED"; string constant private ERROR_MINIME_FACTORY_NOT_CONTRACT = "TEMPLATE_MINIME_FAC_NOT_CONTRACT"; string constant private ERROR_CANNOT_CAST_VALUE_TO_ADDRESS = "TEMPLATE_CANNOT_CAST_VALUE_TO_ADDRESS"; string constant private ERROR_INVALID_ID = "TEMPLATE_INVALID_ID"; ENS internal ens; DAOFactory internal daoFactory; MiniMeTokenFactory internal miniMeFactory; IFIFSResolvingRegistrar internal aragonID; event DeployDao(address dao); event SetupDao(address dao); event DeployToken(address token); event InstalledApp(address appProxy, bytes32 appId); constructor(DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID) public { require(isContract(address(_ens)), ERROR_ENS_NOT_CONTRACT); require(isContract(address(_daoFactory)), ERROR_DAO_FACTORY_NOT_CONTRACT); ens = _ens; aragonID = _aragonID; daoFactory = _daoFactory; miniMeFactory = _miniMeFactory; } /** * @dev Create a DAO using the DAO Factory and grant the template root permissions so it has full * control during setup. Once the DAO setup has finished, it is recommended to call the * `_transferRootPermissionsFromTemplateAndFinalizeDAO()` helper to transfer the root * permissions to the end entity in control of the organization. */ function _createDAO() internal returns (Kernel dao, ACL acl) { dao = daoFactory.newDAO(this); emit DeployDao(address(dao)); acl = ACL(dao.acl()); _createPermissionForTemplate(acl, dao, dao.APP_MANAGER_ROLE()); } /* ACL */ function _createPermissions(ACL _acl, address[] memory _grantees, address _app, bytes32 _permission, address _manager) internal { _acl.createPermission(_grantees[0], _app, _permission, address(this)); for (uint256 i = 1; i < _grantees.length; i++) { _acl.grantPermission(_grantees[i], _app, _permission); } _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } function _createPermissionForTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.createPermission(address(this), _app, _permission, address(this)); } function _removePermissionFromTemplate(ACL _acl, address _app, bytes32 _permission) internal { _acl.revokePermission(address(this), _app, _permission); _acl.removePermissionManager(_app, _permission); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to) internal { _transferRootPermissionsFromTemplateAndFinalizeDAO(_dao, _to, _to); } function _transferRootPermissionsFromTemplateAndFinalizeDAO(Kernel _dao, address _to, address _manager) internal { ACL _acl = ACL(_dao.acl()); _transferPermissionFromTemplate(_acl, _dao, _to, _dao.APP_MANAGER_ROLE(), _manager); _transferPermissionFromTemplate(_acl, _acl, _to, _acl.CREATE_PERMISSIONS_ROLE(), _manager); emit SetupDao(_dao); } function _transferPermissionFromTemplate(ACL _acl, address _app, address _to, bytes32 _permission, address _manager) internal { _acl.grantPermission(_to, _app, _permission); _acl.revokePermission(address(this), _app, _permission); _acl.setPermissionManager(_manager, _app, _permission); } /* AGENT */ function _installDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); Agent agent = Agent(_installDefaultApp(_dao, AGENT_APP_ID, initializeData)); // We assume that installing the Agent app as a default app means the DAO should have its // Vault replaced by the Agent. Thus, we also set the DAO's recovery app to the Agent. _dao.setRecoveryVaultAppId(AGENT_APP_ID); return agent; } function _installNonDefaultAgentApp(Kernel _dao) internal returns (Agent) { bytes memory initializeData = abi.encodeWithSelector(Agent(0).initialize.selector); return Agent(_installNonDefaultApp(_dao, AGENT_APP_ID, initializeData)); } function _createAgentPermissions(ACL _acl, Agent _agent, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _agent, _agent.EXECUTE_ROLE(), _manager); _acl.createPermission(_grantee, _agent, _agent.RUN_SCRIPT_ROLE(), _manager); } /* VAULT */ function _installVaultApp(Kernel _dao) internal returns (Vault) { bytes memory initializeData = abi.encodeWithSelector(Vault(0).initialize.selector); return Vault(_installDefaultApp(_dao, VAULT_APP_ID, initializeData)); } function _createVaultPermissions(ACL _acl, Vault _vault, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _vault, _vault.TRANSFER_ROLE(), _manager); } /* VOTING */ function _installVotingApp(Kernel _dao, MiniMeToken _token, uint64[3] memory _votingSettings) internal returns (Voting) { return _installVotingApp(_dao, _token, _votingSettings[0], _votingSettings[1], _votingSettings[2]); } function _installVotingApp( Kernel _dao, MiniMeToken _token, uint64 _support, uint64 _acceptance, uint64 _duration ) internal returns (Voting) { bytes memory initializeData = abi.encodeWithSelector(Voting(0).initialize.selector, _token, _support, _acceptance, _duration); return Voting(_installNonDefaultApp(_dao, VOTING_APP_ID, initializeData)); } function _createVotingPermissions( ACL _acl, Voting _voting, address _settingsGrantee, address _createVotesGrantee, address _manager ) internal { _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_QUORUM_ROLE(), _manager); _acl.createPermission(_settingsGrantee, _voting, _voting.MODIFY_SUPPORT_ROLE(), _manager); _acl.createPermission(_createVotesGrantee, _voting, _voting.CREATE_VOTES_ROLE(), _manager); } /* SURVEY */ function _installSurveyApp(Kernel _dao, MiniMeToken _token, uint64 _minParticipationPct, uint64 _surveyTime) internal returns (Survey) { bytes memory initializeData = abi.encodeWithSelector(Survey(0).initialize.selector, _token, _minParticipationPct, _surveyTime); return Survey(_installNonDefaultApp(_dao, SURVEY_APP_ID, initializeData)); } function _createSurveyPermissions(ACL _acl, Survey _survey, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _survey, _survey.CREATE_SURVEYS_ROLE(), _manager); _acl.createPermission(_grantee, _survey, _survey.MODIFY_PARTICIPATION_ROLE(), _manager); } /* PAYROLL */ function _installPayrollApp( Kernel _dao, Finance _finance, address _denominationToken, IFeed _priceFeed, uint64 _rateExpiryTime ) internal returns (Payroll) { bytes memory initializeData = abi.encodeWithSelector( Payroll(0).initialize.selector, _finance, _denominationToken, _priceFeed, _rateExpiryTime ); return Payroll(_installNonDefaultApp(_dao, PAYROLL_APP_ID, initializeData)); } /** * @dev Internal function to configure payroll permissions. Note that we allow defining different managers for * payroll since it may be useful to have one control the payroll settings (rate expiration, price feed, * and allowed tokens), and another one to control the employee functionality (bonuses, salaries, * reimbursements, employees, etc). * @param _acl ACL instance being configured * @param _acl Payroll app being configured * @param _employeeManager Address that will receive permissions to handle employee payroll functionality * @param _settingsManager Address that will receive permissions to manage payroll settings * @param _permissionsManager Address that will be the ACL manager for the payroll permissions */ function _createPayrollPermissions( ACL _acl, Payroll _payroll, address _employeeManager, address _settingsManager, address _permissionsManager ) internal { _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_BONUS_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.ADD_REIMBURSEMENT_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.TERMINATE_EMPLOYEE_ROLE(), _permissionsManager); _acl.createPermission(_employeeManager, _payroll, _payroll.SET_EMPLOYEE_SALARY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_PRICE_FEED_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MODIFY_RATE_EXPIRY_ROLE(), _permissionsManager); _acl.createPermission(_settingsManager, _payroll, _payroll.MANAGE_ALLOWED_TOKENS_ROLE(), _permissionsManager); } function _unwrapPayrollSettings( uint256[4] memory _payrollSettings ) internal pure returns (address denominationToken, IFeed priceFeed, uint64 rateExpiryTime, address employeeManager) { denominationToken = _toAddress(_payrollSettings[0]); priceFeed = IFeed(_toAddress(_payrollSettings[1])); rateExpiryTime = _payrollSettings[2].toUint64(); employeeManager = _toAddress(_payrollSettings[3]); } /* FINANCE */ function _installFinanceApp(Kernel _dao, Vault _vault, uint64 _periodDuration) internal returns (Finance) { bytes memory initializeData = abi.encodeWithSelector(Finance(0).initialize.selector, _vault, _periodDuration); return Finance(_installNonDefaultApp(_dao, FINANCE_APP_ID, initializeData)); } function _createFinancePermissions(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.EXECUTE_PAYMENTS_ROLE(), _manager); _acl.createPermission(_grantee, _finance, _finance.MANAGE_PAYMENTS_ROLE(), _manager); } function _createFinanceCreatePaymentsPermission(ACL _acl, Finance _finance, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _finance, _finance.CREATE_PAYMENTS_ROLE(), _manager); } function _grantCreatePaymentPermission(ACL _acl, Finance _finance, address _to) internal { _acl.grantPermission(_to, _finance, _finance.CREATE_PAYMENTS_ROLE()); } function _transferCreatePaymentManagerFromTemplate(ACL _acl, Finance _finance, address _manager) internal { _acl.setPermissionManager(_manager, _finance, _finance.CREATE_PAYMENTS_ROLE()); } /* TOKEN MANAGER */ function _installTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (TokenManager) { TokenManager tokenManager = TokenManager(_installNonDefaultApp(_dao, TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createTokenManagerPermissions(ACL _acl, TokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address[] memory _holders, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stake); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } function _mintTokens(ACL _acl, TokenManager _tokenManager, address _holder, uint256 _stake) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); _tokenManager.mint(_holder, _stake); _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } /* EVM SCRIPTS */ function _createEvmScriptsRegistryPermissions(ACL _acl, address _grantee, address _manager) internal { EVMScriptRegistry registry = EVMScriptRegistry(_acl.getEVMScriptRegistry()); _acl.createPermission(_grantee, registry, registry.REGISTRY_MANAGER_ROLE(), _manager); _acl.createPermission(_grantee, registry, registry.REGISTRY_ADD_EXECUTOR_ROLE(), _manager); } /* APPS */ function _installNonDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installNonDefaultApp(_dao, _appId, new bytes(0)); } function _installNonDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, false); } function _installDefaultApp(Kernel _dao, bytes32 _appId) internal returns (address) { return _installDefaultApp(_dao, _appId, new bytes(0)); } function _installDefaultApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData) internal returns (address) { return _installApp(_dao, _appId, _initializeData, true); } function _installApp(Kernel _dao, bytes32 _appId, bytes memory _initializeData, bool _setDefault) internal returns (address) { address latestBaseAppAddress = _latestVersionAppBase(_appId); address instance = address(_dao.newAppInstance(_appId, latestBaseAppAddress, _initializeData, _setDefault)); emit InstalledApp(instance, _appId); return instance; } function _latestVersionAppBase(bytes32 _appId) internal view returns (address base) { Repo repo = Repo(PublicResolver(ens.resolver(_appId)).addr(_appId)); (,base,) = repo.getLatest(); } /* TOKEN */ function _createToken(string memory _name, string memory _symbol, uint8 _decimals) internal returns (MiniMeToken) { require(address(miniMeFactory) != address(0), ERROR_MINIME_FACTORY_NOT_PROVIDED); MiniMeToken token = miniMeFactory.createCloneToken(MiniMeToken(address(0)), 0, _name, _decimals, _symbol, true); emit DeployToken(address(token)); return token; } function _ensureMiniMeFactoryIsValid(address _miniMeFactory) internal view { require(isContract(address(_miniMeFactory)), ERROR_MINIME_FACTORY_NOT_CONTRACT); } /* IDS */ function _validateId(string memory _id) internal pure { require(bytes(_id).length > 0, ERROR_INVALID_ID); } function _registerID(string memory _name, address _owner) internal { require(address(aragonID) != address(0), ERROR_ARAGON_ID_NOT_PROVIDED); aragonID.register(keccak256(abi.encodePacked(_name)), _owner); } function _ensureAragonIdIsValid(address _aragonID) internal view { require(isContract(address(_aragonID)), ERROR_ARAGON_ID_NOT_CONTRACT); } /* HELPERS */ function _toAddress(uint256 _value) private pure returns (address) { require(_value <= uint160(-1), ERROR_CANNOT_CAST_VALUE_TO_ADDRESS); return address(_value); } } // File contracts/Template.sol pragma solidity 0.4.24; contract Template is BaseTemplate, TokenCache { string constant private ERROR_EMPTY_HOLDERS = "TEMPLATE_EMPTY_HOLDERS"; string constant private ERROR_BAD_HOLDERS_STAKES_LEN = "TEMPLATE_BAD_HOLDERS_STAKES_LEN"; string constant private ERROR_BAD_VOTE_SETTINGS = "TEMPLATE_BAD_VOTE_SETTINGS"; address constant private ANY_ENTITY = address(-1); bool constant private TOKEN_TRANSFERABLE = true; uint8 constant private TOKEN_DECIMALS = uint8(18); uint256 constant private TOKEN_MAX_PER_ACCOUNT = uint256(0); bytes32 constant internal HOOKED_TOKEN_MANAGER_APP_ID = keccak256(abi.encodePacked(apmNamehash("open"), keccak256("token-manager"))); // token-manager.open.aragonpm.eth constructor ( DAOFactory _daoFactory, ENS _ens, MiniMeTokenFactory _miniMeFactory, IFIFSResolvingRegistrar _aragonID ) BaseTemplate(_daoFactory, _ens, _miniMeFactory, _aragonID) public { _ensureAragonIdIsValid(_aragonID); _ensureMiniMeFactoryIsValid(_miniMeFactory); } /** * @dev Create a new MiniMe token and deploy a Template DAO. * @param _tokenName String with the name for the token used by share holders in the organization * @param _tokenSymbol String with the symbol for the token used by share holders in the organization * @param _holders Array of token holder addresses * @param _stakes Array of token stakes for holders (token has 18 decimals, multiply token amount `* 10^18`) * @param _votingSettings Array of [supportRequired, minAcceptanceQuorum, voteDuration] to set up the voting app of the organization */ function newTokenAndInstance( string _tokenName, string _tokenSymbol, address[] _holders, uint256[] _stakes, uint64[3] _votingSettings ) external { newToken(_tokenName, _tokenSymbol); newInstance(_holders, _stakes, _votingSettings); } /** * @dev Create a new MiniMe token and cache it for the user * @param _name String with the name for the token used by share holders in the organization * @param _symbol String with the symbol for the token used by share holders in the organization */ function newToken(string memory _name, string memory _symbol) public returns (MiniMeToken) { MiniMeToken token = _createToken(_name, _symbol, TOKEN_DECIMALS); _cacheToken(token, msg.sender); return token; } /** * @dev Deploy a Template DAO using a previously cached MiniMe token * @param _holders Array of token holder addresses * @param _stakes Array of token stakes for holders (token has 18 decimals, multiply token amount `* 10^18`) * @param _votingSettings Array of [supportRequired, minAcceptanceQuorum, voteDuration] to set up the voting app of the organization */ function newInstance( address[] memory _holders, uint256[] memory _stakes, uint64[3] memory _votingSettings ) public { _ensureTemplateSettings(_holders, _stakes, _votingSettings); (Kernel dao, ACL acl) = _createDAO(); (Voting voting) = _setupBaseApps(dao, acl, _holders, _stakes, _votingSettings); _transferRootPermissionsFromTemplateAndFinalizeDAO(dao, voting); } function _setupBaseApps( Kernel _dao, ACL _acl, address[] memory _holders, uint256[] memory _stakes, uint64[3] memory _votingSettings ) internal returns (Voting) { MiniMeToken token = _popTokenCache(msg.sender); HookedTokenManager tokenManager = _installHookedTokenManagerApp(_dao, token, TOKEN_TRANSFERABLE, TOKEN_MAX_PER_ACCOUNT); Voting voting = _installVotingApp(_dao, token, _votingSettings); _mintTokens(_acl, tokenManager, _holders, _stakes); _setupBasePermissions(_acl, voting, tokenManager); return (voting); } function _setupBasePermissions( ACL _acl, Voting _voting, HookedTokenManager _tokenManager ) internal { _createEvmScriptsRegistryPermissions(_acl, _voting, _voting); _createVotingPermissions(_acl, _voting, _voting, _tokenManager, _voting); _createHookedTokenManagerPermissions(_acl, _tokenManager, _voting, _voting); } function _installHookedTokenManagerApp( Kernel _dao, MiniMeToken _token, bool _transferable, uint256 _maxAccountTokens ) internal returns (HookedTokenManager) { HookedTokenManager tokenManager = HookedTokenManager(_installNonDefaultApp(_dao, HOOKED_TOKEN_MANAGER_APP_ID)); _token.changeController(tokenManager); tokenManager.initialize(_token, _transferable, _maxAccountTokens); return tokenManager; } function _createHookedTokenManagerPermissions(ACL _acl, HookedTokenManager _tokenManager, address _grantee, address _manager) internal { _acl.createPermission(_grantee, _tokenManager, _tokenManager.MINT_ROLE(), _manager); _acl.createPermission(_grantee, _tokenManager, _tokenManager.BURN_ROLE(), _manager); } function _mintTokens(ACL _acl, HookedTokenManager _tokenManager, address[] memory _holders, uint256[] memory _stakes) internal { _createPermissionForTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); for (uint256 i = 0; i < _holders.length; i++) { _tokenManager.mint(_holders[i], _stakes[i]); } _removePermissionFromTemplate(_acl, _tokenManager, _tokenManager.MINT_ROLE()); } //--------------------------------------------------------------// function _ensureTemplateSettings( address[] memory _holders, uint256[] memory _stakes, uint64[3] memory _votingSettings ) private pure { require(_holders.length > 0, ERROR_EMPTY_HOLDERS); require(_holders.length == _stakes.length, ERROR_BAD_HOLDERS_STAKES_LEN); require(_votingSettings.length == 3, ERROR_BAD_VOTE_SETTINGS); } } // File contracts/test/mocks/TokenManagerHookMock.sol pragma solidity 0.4.24; contract TokenManagerHookMock is TokenManagerHook { uint public id; event RegisterHooked(uint indexed _id); event RevokeHooked(uint indexed _id); event TransferHooked(uint indexed _id, address indexed _from, address indexed _to); event ApproveHooked(uint indexed _id); constructor(uint _id) public { id = _id; } function _onRegisterAsHook(address, uint256, address) internal { emit RegisterHooked(id); } function _onRevokeAsHook(address, uint256, address) internal { emit RevokeHooked(id); } function _onTransfer(address _from, address _to, uint256) internal returns (bool) { emit TransferHooked(id, _from, _to); return true; } function _onApprove(address, address, uint) internal returns (bool) { emit ApproveHooked(id); return true; } } // File @aragon/test-helpers/contracts/[email protected] pragma solidity ^0.4.24; contract TimeHelpersMock is TimeHelpers { using SafeMath for uint256; using SafeMath64 for uint64; uint256 mockedTimestamp; uint256 mockedBlockNumber; /** * @dev Sets a mocked timestamp value, used only for testing purposes */ function mockSetTimestamp(uint256 _timestamp) public { mockedTimestamp = _timestamp; } /** * @dev Increases the mocked timestamp value, used only for testing purposes */ function mockIncreaseTime(uint256 _seconds) public { if (mockedTimestamp != 0) mockedTimestamp = mockedTimestamp.add(_seconds); else mockedTimestamp = block.timestamp.add(_seconds); } /** * @dev Decreases the mocked timestamp value, used only for testing purposes */ function mockDecreaseTime(uint256 _seconds) public { if (mockedTimestamp != 0) mockedTimestamp = mockedTimestamp.sub(_seconds); else mockedTimestamp = block.timestamp.sub(_seconds); } /** * @dev Advances the mocked block number value, used only for testing purposes */ function mockAdvanceBlocks(uint256 _number) public { if (mockedBlockNumber != 0) mockedBlockNumber = mockedBlockNumber.add(_number); else mockedBlockNumber = block.number.add(_number); } /** * @dev Returns the mocked timestamp value */ function getTimestampPublic() public view returns (uint64) { return getTimestamp64(); } /** * @dev Returns the mocked block number value */ function getBlockNumberPublic() public view returns (uint256) { return getBlockNumber(); } /** * @dev Returns the mocked timestamp if it was set, or current `block.timestamp` */ function getTimestamp() internal view returns (uint256) { if (mockedTimestamp != 0) return mockedTimestamp; return super.getTimestamp(); } /** * @dev Returns the mocked block number if it was set, or current `block.number` */ function getBlockNumber() internal view returns (uint256) { if (mockedBlockNumber != 0) return mockedBlockNumber; return super.getBlockNumber(); } } // File contracts/test/mocks/TokenManagerMock.sol pragma solidity 0.4.24; /* solium-disable-next-line no-empty-blocks */ contract TokenManagerMock is HookedTokenManager, TimeHelpersMock {} // File @aragon/os/contracts/ens/[email protected] /* * SPDX-License-Identitifer: MIT */ pragma solidity ^0.4.24; contract ENSConstants { /* Hardcoded constants to save gas bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = keccak256("eth"); bytes32 internal constant ETH_TLD_NODE = keccak256(abi.encodePacked(ENS_ROOT, ETH_TLD_LABEL)); bytes32 internal constant PUBLIC_RESOLVER_LABEL = keccak256("resolver"); bytes32 internal constant PUBLIC_RESOLVER_NODE = keccak256(abi.encodePacked(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL)); */ bytes32 internal constant ENS_ROOT = bytes32(0); bytes32 internal constant ETH_TLD_LABEL = 0x4f5b812789fc606be1b3b16908db13fc7a9adf7ca72641f84d75b47069d3d7f0; bytes32 internal constant ETH_TLD_NODE = 0x93cdeb708b7545dc668eb9280176169d1c33cfd8ed6f04690a0bcc88a93fc4ae; bytes32 internal constant PUBLIC_RESOLVER_LABEL = 0x329539a1d23af1810c48a07fe7fc66a3b34fbc8b37e9b3cdb97bb88ceab7e4bf; bytes32 internal constant PUBLIC_RESOLVER_NODE = 0xfdd5d5de6dd63db72bbc2d487944ba13bf775b50a80805fe6fcaba9b0fba88f5; } // File @aragon/os/contracts/ens/[email protected] pragma solidity 0.4.24; /* solium-disable function-order */ // Allow public initialize() to be first contract ENSSubdomainRegistrar is AragonApp, ENSConstants { /* Hardcoded constants to save gas bytes32 public constant CREATE_NAME_ROLE = keccak256("CREATE_NAME_ROLE"); bytes32 public constant DELETE_NAME_ROLE = keccak256("DELETE_NAME_ROLE"); bytes32 public constant POINT_ROOTNODE_ROLE = keccak256("POINT_ROOTNODE_ROLE"); */ bytes32 public constant CREATE_NAME_ROLE = 0xf86bc2abe0919ab91ef714b2bec7c148d94f61fdb069b91a6cfe9ecdee1799ba; bytes32 public constant DELETE_NAME_ROLE = 0x03d74c8724218ad4a99859bcb2d846d39999449fd18013dd8d69096627e68622; bytes32 public constant POINT_ROOTNODE_ROLE = 0x9ecd0e7bddb2e241c41b595a436c4ea4fd33c9fa0caa8056acf084fc3aa3bfbe; string private constant ERROR_NO_NODE_OWNERSHIP = "ENSSUB_NO_NODE_OWNERSHIP"; string private constant ERROR_NAME_EXISTS = "ENSSUB_NAME_EXISTS"; string private constant ERROR_NAME_DOESNT_EXIST = "ENSSUB_DOESNT_EXIST"; AbstractENS public ens; bytes32 public rootNode; event NewName(bytes32 indexed node, bytes32 indexed label); event DeleteName(bytes32 indexed node, bytes32 indexed label); /** * @dev Initialize can only be called once. It saves the block number in which it was initialized. This contract must be the owner of the `_rootNode` node so that it can create subdomains. * @notice Initialize this ENSSubdomainRegistrar instance with `_ens` as the root ENS registry and `_rootNode` as the node to allocate subdomains under * @param _ens Address of ENS registry * @param _rootNode Node to allocate subdomains under */ function initialize(AbstractENS _ens, bytes32 _rootNode) public onlyInit { initialized(); // We need ownership to create subnodes require(_ens.owner(_rootNode) == address(this), ERROR_NO_NODE_OWNERSHIP); ens = _ens; rootNode = _rootNode; } /** * @notice Create a new ENS subdomain record for `_label` and assign ownership to `_owner` * @param _label Label of new subdomain * @param _owner Owner of new subdomain * @return node Hash of created node */ function createName(bytes32 _label, address _owner) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { return _createName(_label, _owner); } /** * @notice Create a new ENS subdomain record for `_label` that resolves to `_target` and is owned by this ENSSubdomainRegistrar * @param _label Label of new subdomain * @param _target Ethereum address this new subdomain label will point to * @return node Hash of created node */ function createNameAndPoint(bytes32 _label, address _target) external auth(CREATE_NAME_ROLE) returns (bytes32 node) { node = _createName(_label, this); _pointToResolverAndResolve(node, _target); } /** * @notice Deregister ENS subdomain record for `_label` * @param _label Label of subdomain to deregister */ function deleteName(bytes32 _label) external auth(DELETE_NAME_ROLE) { bytes32 node = getNodeForLabel(_label); address currentOwner = ens.owner(node); require(currentOwner != address(0), ERROR_NAME_DOESNT_EXIST); // fail if deleting unset name if (currentOwner != address(this)) { // needs to reclaim ownership so it can set resolver ens.setSubnodeOwner(rootNode, _label, this); } ens.setResolver(node, address(0)); // remove resolver so it ends resolving ens.setOwner(node, address(0)); emit DeleteName(node, _label); } /** * @notice Resolve this ENSSubdomainRegistrar's root node to `_target` * @param _target Ethereum address root node will point to */ function pointRootNode(address _target) external auth(POINT_ROOTNODE_ROLE) { _pointToResolverAndResolve(rootNode, _target); } function _createName(bytes32 _label, address _owner) internal returns (bytes32 node) { node = getNodeForLabel(_label); require(ens.owner(node) == address(0), ERROR_NAME_EXISTS); // avoid name reset ens.setSubnodeOwner(rootNode, _label, _owner); emit NewName(node, _label); return node; } function _pointToResolverAndResolve(bytes32 _node, address _target) internal { address publicResolver = getAddr(PUBLIC_RESOLVER_NODE); ens.setResolver(_node, publicResolver); PublicResolver(publicResolver).setAddr(_node, _target); } function getAddr(bytes32 node) internal view returns (address) { address resolver = ens.resolver(node); return PublicResolver(resolver).addr(node); } function getNodeForLabel(bytes32 _label) internal view returns (bytes32) { return keccak256(abi.encodePacked(rootNode, _label)); } } // File @aragon/os/contracts/apm/[email protected] pragma solidity 0.4.24; contract APMInternalAppNames { string internal constant APM_APP_NAME = "apm-registry"; string internal constant REPO_APP_NAME = "apm-repo"; string internal constant ENS_SUB_APP_NAME = "apm-enssub"; } contract APMRegistry is AragonApp, AppProxyFactory, APMInternalAppNames { /* Hardcoded constants to save gas bytes32 public constant CREATE_REPO_ROLE = keccak256("CREATE_REPO_ROLE"); */ bytes32 public constant CREATE_REPO_ROLE = 0x2a9494d64846c9fdbf0158785aa330d8bc9caf45af27fa0e8898eb4d55adcea6; string private constant ERROR_INIT_PERMISSIONS = "APMREG_INIT_PERMISSIONS"; string private constant ERROR_EMPTY_NAME = "APMREG_EMPTY_NAME"; AbstractENS public ens; ENSSubdomainRegistrar public registrar; event NewRepo(bytes32 id, string name, address repo); /** * NEEDS CREATE_NAME_ROLE and POINT_ROOTNODE_ROLE permissions on registrar * @dev Initialize can only be called once. It saves the block number in which it was initialized * @notice Initialize this APMRegistry instance and set `_registrar` as the ENS subdomain registrar * @param _registrar ENSSubdomainRegistrar instance that holds registry root node ownership */ function initialize(ENSSubdomainRegistrar _registrar) public onlyInit { initialized(); registrar = _registrar; ens = registrar.ens(); registrar.pointRootNode(this); // Check APM has all permissions it needss ACL acl = ACL(kernel().acl()); require(acl.hasPermission(this, registrar, registrar.CREATE_NAME_ROLE()), ERROR_INIT_PERMISSIONS); require(acl.hasPermission(this, acl, acl.CREATE_PERMISSIONS_ROLE()), ERROR_INIT_PERMISSIONS); } /** * @notice Create new repo in registry with `_name` * @param _name Repo name, must be ununsed * @param _dev Address that will be given permission to create versions */ function newRepo(string _name, address _dev) public auth(CREATE_REPO_ROLE) returns (Repo) { return _newRepo(_name, _dev); } /** * @notice Create new repo in registry with `_name` and publish a first version with contract `_contractAddress` and content `@fromHex(_contentURI)` * @param _name Repo name * @param _dev Address that will be given permission to create versions * @param _initialSemanticVersion Semantic version for new repo version * @param _contractAddress address for smart contract logic for version (if set to 0, it uses last versions' contractAddress) * @param _contentURI External URI for fetching new version's content */ function newRepoWithVersion( string _name, address _dev, uint16[3] _initialSemanticVersion, address _contractAddress, bytes _contentURI ) public auth(CREATE_REPO_ROLE) returns (Repo) { Repo repo = _newRepo(_name, this); // need to have permissions to create version repo.newVersion(_initialSemanticVersion, _contractAddress, _contentURI); // Give permissions to _dev ACL acl = ACL(kernel().acl()); acl.revokePermission(this, repo, repo.CREATE_VERSION_ROLE()); acl.grantPermission(_dev, repo, repo.CREATE_VERSION_ROLE()); acl.setPermissionManager(_dev, repo, repo.CREATE_VERSION_ROLE()); return repo; } function _newRepo(string _name, address _dev) internal returns (Repo) { require(bytes(_name).length > 0, ERROR_EMPTY_NAME); Repo repo = newClonedRepo(); ACL(kernel().acl()).createPermission(_dev, repo, repo.CREATE_VERSION_ROLE(), _dev); // Creates [name] subdomain in the rootNode and sets registry as resolver // This will fail if repo name already exists bytes32 node = registrar.createNameAndPoint(keccak256(abi.encodePacked(_name)), repo); emit NewRepo(node, _name, repo); return repo; } function newClonedRepo() internal returns (Repo repo) { repo = Repo(newAppProxy(kernel(), repoAppId())); repo.initialize(); } function repoAppId() internal view returns (bytes32) { return keccak256(abi.encodePacked(registrar.rootNode(), keccak256(abi.encodePacked(REPO_APP_NAME)))); } } // File @aragon/os/contracts/factory/[email protected] pragma solidity 0.4.24; // WARNING: This is an incredibly trustful ENS deployment, do NOT use in production! // This contract is NOT meant to be deployed to a live network. // Its only purpose is to easily create ENS instances for testing aragonPM. contract ENSFactory is ENSConstants { event DeployENS(address ens); /** * @notice Create a new ENS and set `_owner` as the owner of the top level domain. * @param _owner Owner of .eth * @return ENS */ function newENS(address _owner) public returns (ENS) { ENS ens = new ENS(); // Setup .eth TLD ens.setSubnodeOwner(ENS_ROOT, ETH_TLD_LABEL, this); // Setup public resolver PublicResolver resolver = new PublicResolver(ens); ens.setSubnodeOwner(ETH_TLD_NODE, PUBLIC_RESOLVER_LABEL, this); ens.setResolver(PUBLIC_RESOLVER_NODE, resolver); resolver.setAddr(PUBLIC_RESOLVER_NODE, resolver); ens.setOwner(ETH_TLD_NODE, _owner); ens.setOwner(ENS_ROOT, _owner); emit DeployENS(ens); return ens; } } // File @aragon/os/contracts/factory/[email protected] pragma solidity 0.4.24; contract APMRegistryFactory is APMInternalAppNames { DAOFactory public daoFactory; APMRegistry public registryBase; Repo public repoBase; ENSSubdomainRegistrar public ensSubdomainRegistrarBase; ENS public ens; event DeployAPM(bytes32 indexed node, address apm); /** * @notice Create a new factory for deploying Aragon Package Managers (aragonPM) * @dev Requires either a given ENS registrar or ENSFactory (used for generating a new ENS in test environments). * @param _daoFactory Base factory for deploying DAOs * @param _registryBase APMRegistry base contract location * @param _repoBase Repo base contract location * @param _ensSubBase ENSSubdomainRegistrar base contract location * @param _ens ENS instance * @param _ensFactory ENSFactory (used to generated a new ENS if no ENS is given) */ constructor( DAOFactory _daoFactory, APMRegistry _registryBase, Repo _repoBase, ENSSubdomainRegistrar _ensSubBase, ENS _ens, ENSFactory _ensFactory ) public // DAO initialized without evmscript run support { daoFactory = _daoFactory; registryBase = _registryBase; repoBase = _repoBase; ensSubdomainRegistrarBase = _ensSubBase; // Either the ENS address provided is used, if any. // Or we use the ENSFactory to generate a test instance of ENS // If not the ENS address nor factory address are provided, this will revert ens = _ens != address(0) ? _ens : _ensFactory.newENS(this); } /** * @notice Create a new Aragon Package Manager (aragonPM) DAO, holding the `_label` subdomain from parent `_tld` and controlled by `_root` * @param _tld The parent node of the controlled subdomain * @param _label The subdomain label * @param _root Manager for the new aragonPM DAO * @return The new aragonPM's APMRegistry app */ function newAPM(bytes32 _tld, bytes32 _label, address _root) public returns (APMRegistry) { bytes32 node = keccak256(abi.encodePacked(_tld, _label)); // Assume it is the test ENS if (ens.owner(node) != address(this)) { // If we weren't in test ens and factory doesn't have ownership, will fail require(ens.owner(_tld) == address(this)); ens.setSubnodeOwner(_tld, _label, this); } Kernel dao = daoFactory.newDAO(this); ACL acl = ACL(dao.acl()); acl.createPermission(this, dao, dao.APP_MANAGER_ROLE(), this); // Deploy app proxies bytes memory noInit = new bytes(0); ENSSubdomainRegistrar ensSub = ENSSubdomainRegistrar( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(ENS_SUB_APP_NAME)))), ensSubdomainRegistrarBase, noInit, false ) ); APMRegistry apm = APMRegistry( dao.newAppInstance( keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(APM_APP_NAME)))), registryBase, noInit, false ) ); // APMRegistry controls Repos bytes32 repoAppId = keccak256(abi.encodePacked(node, keccak256(abi.encodePacked(REPO_APP_NAME)))); dao.setApp(dao.APP_BASES_NAMESPACE(), repoAppId, repoBase); emit DeployAPM(node, apm); // Grant permissions needed for APM on ENSSubdomainRegistrar acl.createPermission(apm, ensSub, ensSub.CREATE_NAME_ROLE(), _root); acl.createPermission(apm, ensSub, ensSub.POINT_ROOTNODE_ROLE(), _root); // allow apm to create permissions for Repos in Kernel bytes32 permRole = acl.CREATE_PERMISSIONS_ROLE(); acl.grantPermission(apm, acl, permRole); // Initialize ens.setOwner(node, ensSub); ensSub.initialize(ens, node); apm.initialize(ensSub); uint16[3] memory firstVersion; firstVersion[0] = 1; acl.createPermission(this, apm, apm.CREATE_REPO_ROLE(), this); apm.newRepoWithVersion(APM_APP_NAME, _root, firstVersion, registryBase, b("ipfs:apm")); apm.newRepoWithVersion(ENS_SUB_APP_NAME, _root, firstVersion, ensSubdomainRegistrarBase, b("ipfs:enssub")); apm.newRepoWithVersion(REPO_APP_NAME, _root, firstVersion, repoBase, b("ipfs:repo")); configureAPMPermissions(acl, apm, _root); // Permission transition to _root acl.setPermissionManager(_root, dao, dao.APP_MANAGER_ROLE()); acl.revokePermission(this, acl, permRole); acl.grantPermission(_root, acl, permRole); acl.setPermissionManager(_root, acl, permRole); return apm; } function b(string memory x) internal pure returns (bytes memory y) { y = bytes(x); } // Factory can be subclassed and permissions changed function configureAPMPermissions(ACL _acl, APMRegistry _apm, address _root) internal { _acl.grantPermission(_root, _apm, _apm.CREATE_REPO_ROLE()); _acl.setPermissionManager(_root, _apm, _apm.CREATE_REPO_ROLE()); } } // File @aragon/test-helpers/contracts/[email protected] pragma solidity 0.4.24; contract EtherTokenConstantMock is EtherTokenConstant { function getETHConstant() external pure returns (address) { return ETH; } } // File contracts/test/TestImports.sol pragma solidity 0.4.24; // You might think this file is a bit odd, but let me explain. // We only use some contracts in our tests, which means Truffle // will not compile it for us, because it is from an external // dependency. // // We are now left with three options: // - Copy/paste these contracts // - Run the tests with `truffle compile --all` on // - Or trick Truffle by claiming we use it in a Solidity test // // You know which one I went for. contract TestImports { constructor() public { // solium-disable-previous-line no-empty-blocks } } // File contracts/test/mocks/ExecutionTarget.sol pragma solidity 0.4.24; contract ExecutionTarget { uint public counter; function execute() public { counter += 1; emit Executed(counter); } function setCounter(uint x) public { counter = x; } event Executed(uint x); }
* @dev Returns the mocked timestamp if it was set, or current `block.timestamp`/
function getTimestamp() internal view returns (uint256) { if (mockedTimestamp != 0) return mockedTimestamp; return super.getTimestamp(); }
2,035,494
[ 1, 1356, 326, 5416, 329, 2858, 309, 518, 1703, 444, 16, 578, 783, 1375, 2629, 18, 5508, 68, 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, 565, 445, 11940, 1435, 2713, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 309, 261, 22851, 329, 4921, 480, 374, 13, 327, 5416, 329, 4921, 31, 203, 3639, 327, 2240, 18, 588, 4921, 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 ]
/** *Submitted for verification at Etherscan.io on 2019-12-02 */ /** *Submitted for verification at Etherscan.io on 2019-12-02 */ pragma solidity ^0.5.4; /** * ERC20 contract interface. */ contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); } /** * @title Module * @dev Interface for a module. * A module MUST implement the addModule() method to ensure that a wallet with at least one module * can never end up in a "frozen" state. * @author Julien Niset - <[email protected]> */ interface Module { function init(BaseWallet _wallet) external; function addModule(BaseWallet _wallet, Module _module) external; function recoverToken(address _token) external; } /** * @title BaseWallet * @dev Simple modular wallet that authorises modules to call its invoke() method. * Based on https://gist.github.com/Arachnid/a619d31f6d32757a4328a428286da186 by * @author Julien Niset - <[email protected]> */ contract BaseWallet { address public implementation; address public owner; mapping (address => bool) public authorised; mapping (bytes4 => address) public enabled; uint public modules; function init(address _owner, address[] calldata _modules) external; function authoriseModule(address _module, bool _value) external; function enableStaticCall(address _module, bytes4 _method) external; function setOwner(address _newOwner) external; function invoke(address _target, uint _value, bytes calldata _data) external; function() external payable; } /** * @title ModuleRegistry * @dev Registry of authorised modules. * Modules must be registered before they can be authorised on a wallet. * @author Julien Niset - <[email protected]> */ contract ModuleRegistry { function registerModule(address _module, bytes32 _name) external; function deregisterModule(address _module) external; function registerUpgrader(address _upgrader, bytes32 _name) external; function deregisterUpgrader(address _upgrader) external; function recoverToken(address _token) external; function moduleInfo(address _module) external view returns (bytes32); function upgraderInfo(address _upgrader) external view returns (bytes32); function isRegisteredModule(address _module) external view returns (bool); function isRegisteredModule(address[] calldata _modules) external view returns (bool); function isRegisteredUpgrader(address _upgrader) external view returns (bool); } /** * @title GuardianStorage * @dev Contract storing the state of wallets related to guardians and lock. * The contract only defines basic setters and getters with no logic. Only modules authorised * for a wallet can modify its state. * @author Julien Niset - <[email protected]> * @author Olivier Van Den Biggelaar - <[email protected]> */ contract GuardianStorage { function addGuardian(BaseWallet _wallet, address _guardian) external; function revokeGuardian(BaseWallet _wallet, address _guardian) external; function guardianCount(BaseWallet _wallet) external view returns (uint256); function getGuardians(BaseWallet _wallet) external view returns (address[] memory); function isGuardian(BaseWallet _wallet, address _guardian) external view returns (bool); function setLock(BaseWallet _wallet, uint256 _releaseAfter) external; function isLocked(BaseWallet _wallet) external view returns (bool); function getLock(BaseWallet _wallet) external view returns (uint256); function getLocker(BaseWallet _wallet) external view returns (address); } interface Comptroller { function enterMarkets(address[] calldata _cTokens) external returns (uint[] memory); function exitMarket(address _cToken) external returns (uint); function getAssetsIn(address _account) external view returns (address[] memory); function getAccountLiquidity(address _account) external view returns (uint, uint, uint); function checkMembership(address account, CToken cToken) external view returns (bool); } interface CToken { function comptroller() external view returns (address); function underlying() external view returns (address); function symbol() external view returns (string memory); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function balanceOf(address _account) external view returns (uint256); function borrowBalanceCurrent(address _account) external returns (uint256); function borrowBalanceStored(address _account) external view returns (uint256); } /** * @title CompoundRegistry * @dev Simple registry containing a mapping between underlying assets and their corresponding cToken. * @author Julien Niset - <[email protected]> */ contract CompoundRegistry { function addCToken(address _underlying, address _cToken) external; function removeCToken(address _underlying) external; function getCToken(address _underlying) external view returns (address); function listUnderlyings() external view returns (address[] memory); } /** * @title Interface for a contract that can invest tokens in order to earn an interest. * @author Julien Niset - <[email protected]> */ interface Invest { event InvestmentAdded(address indexed _wallet, address _token, uint256 _invested, uint256 _period); event InvestmentRemoved(address indexed _wallet, address _token, uint256 _fraction); /** * @dev Invest tokens for a given period. * @param _wallet The target wallet. * @param _token The token address. * @param _amount The amount of tokens to invest. * @param _period The period over which the tokens may be locked in the investment (optional). * @return The exact amount of tokens that have been invested. */ function addInvestment( BaseWallet _wallet, address _token, uint256 _amount, uint256 _period ) external returns (uint256 _invested); /** * @dev Exit invested postions. * @param _wallet The target wallet. * @param _token The token address. * @param _fraction The fraction of invested tokens to exit in per 10000. */ function removeInvestment( BaseWallet _wallet, address _token, uint256 _fraction ) external; /** * @dev Get the amount of investment in a given token. * @param _wallet The target wallet. * @param _token The token address. * @return The value in tokens of the investment (including interests) and the time at which the investment can be removed. */ function getInvestment( BaseWallet _wallet, address _token ) external view returns (uint256 _tokenValue, uint256 _periodEnd); } /** * @title Interface for a contract that can loan tokens to a wallet. * @author Julien Niset - <[email protected]> */ interface Loan { event LoanOpened(address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount); event LoanClosed(address indexed _wallet, bytes32 indexed _loanId); event CollateralAdded(address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount); event CollateralRemoved(address indexed _wallet, bytes32 indexed _loanId, address _collateral, uint256 _collateralAmount); event DebtAdded(address indexed _wallet, bytes32 indexed _loanId, address _debtToken, uint256 _debtAmount); event DebtRemoved(address indexed _wallet, bytes32 indexed _loanId, address _debtToken, uint256 _debtAmount); /** * @dev Opens a collateralized loan. * @param _wallet The target wallet. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral token provided. * @param _debtToken The token borrowed. * @param _debtAmount The amount of tokens borrowed. * @return (optional) An ID for the loan when the provider enables users to create multiple distinct loans. */ function openLoan( BaseWallet _wallet, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount ) external returns (bytes32 _loanId); /** * @dev Closes a collateralized loan by repaying all debts (plus interest) and redeeming all collateral (plus interest). * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. */ function closeLoan( BaseWallet _wallet, bytes32 _loanId ) external; /** * @dev Adds collateral to a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to add. */ function addCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external; /** * @dev Removes collateral from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to remove. */ function removeCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external; /** * @dev Increases the debt by borrowing more token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. * @param _debtToken The token borrowed. * @param _debtAmount The amount of token to borrow. */ function addDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external; /** * @dev Decreases the debt by repaying some token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. * @param _debtToken The token to repay. * @param _debtAmount The amount of token to repay. */ function removeDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external; /** * @dev Gets information about a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId The ID of the loan if any, 0 otherwise. * @return a status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated, 3: unable to provide info] * and a value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral * that should be added to avoid liquidation when status = 2. */ function getLoan( BaseWallet _wallet, bytes32 _loanId ) external view returns (uint8 _status, uint256 _ethValue); } /** * @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 = 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; } /** * @dev Returns ceil(a / b). */ function ceil(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a / b; if(a % b == 0) { return c; } else { return c + 1; } } } /** * @title BaseModule * @dev Basic module that contains some methods common to all modules. * @author Julien Niset - <[email protected]> */ contract BaseModule is Module { // The adddress of the module registry. ModuleRegistry internal registry; event ModuleCreated(bytes32 name); event ModuleInitialised(address wallet); constructor(ModuleRegistry _registry, bytes32 _name) public { registry = _registry; emit ModuleCreated(_name); } /** * @dev Throws if the sender is not the target wallet of the call. */ modifier onlyWallet(BaseWallet _wallet) { require(msg.sender == address(_wallet), "BM: caller must be wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet or the module itself. */ modifier onlyWalletOwner(BaseWallet _wallet) { require(msg.sender == address(this) || isOwner(_wallet, msg.sender), "BM: must be an owner for the wallet"); _; } /** * @dev Throws if the sender is not the owner of the target wallet. */ modifier strictOnlyWalletOwner(BaseWallet _wallet) { require(isOwner(_wallet, msg.sender), "BM: msg.sender must be an owner for the wallet"); _; } /** * @dev Inits the module for a wallet by logging an event. * The method can only be called by the wallet itself. * @param _wallet The wallet. */ function init(BaseWallet _wallet) external onlyWallet(_wallet) { emit ModuleInitialised(address(_wallet)); } /** * @dev Adds a module to a wallet. First checks that the module is registered. * @param _wallet The target wallet. * @param _module The modules to authorise. */ function addModule(BaseWallet _wallet, Module _module) external strictOnlyWalletOwner(_wallet) { require(registry.isRegisteredModule(address(_module)), "BM: module is not registered"); _wallet.authoriseModule(address(_module), true); } /** * @dev Utility method enbaling anyone to recover ERC20 token sent to the * module by mistake and transfer them to the Module Registry. * @param _token The token to recover. */ function recoverToken(address _token) external { uint total = ERC20(_token).balanceOf(address(this)); ERC20(_token).transfer(address(registry), total); } /** * @dev Helper method to check if an address is the owner of a target wallet. * @param _wallet The target wallet. * @param _addr The address. */ function isOwner(BaseWallet _wallet, address _addr) internal view returns (bool) { return _wallet.owner() == _addr; } } /** * @title RelayerModule * @dev Base module containing logic to execute transactions signed by eth-less accounts and sent by a relayer. * @author Julien Niset - <[email protected]> */ contract RelayerModule is Module { uint256 constant internal BLOCKBOUND = 10000; mapping (address => RelayerConfig) public relayer; struct RelayerConfig { uint256 nonce; mapping (bytes32 => bool) executedTx; } event TransactionExecuted(address indexed wallet, bool indexed success, bytes32 signedHash); /** * @dev Throws if the call did not go through the execute() method. */ modifier onlyExecute { require(msg.sender == address(this), "RM: must be called via execute()"); _; } /* ***************** Abstract method ************************* */ /** * @dev Gets the number of valid signatures that must be provided to execute a * specific relayed transaction. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @return The number of required signatures. */ function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256); /** * @dev Validates the signatures provided with a relayed transaction. * The method MUST throw if one or more signatures are not valid. * @param _wallet The target wallet. * @param _data The data of the relayed transaction. * @param _signHash The signed hash representing the relayed transaction. * @param _signatures The signatures as a concatenated byte array. */ function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool); /* ************************************************************ */ /** * @dev Executes a relayed transaction. * @param _wallet The target wallet. * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _signatures The signatures as a concatenated byte array. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function execute( BaseWallet _wallet, bytes calldata _data, uint256 _nonce, bytes calldata _signatures, uint256 _gasPrice, uint256 _gasLimit ) external returns (bool success) { uint startGas = gasleft(); bytes32 signHash = getSignHash(address(this), address(_wallet), 0, _data, _nonce, _gasPrice, _gasLimit); require(checkAndUpdateUniqueness(_wallet, _nonce, signHash), "RM: Duplicate request"); require(verifyData(address(_wallet), _data), "RM: the wallet authorized is different then the target of the relayed data"); uint256 requiredSignatures = getRequiredSignatures(_wallet, _data); if((requiredSignatures * 65) == _signatures.length) { if(verifyRefund(_wallet, _gasLimit, _gasPrice, requiredSignatures)) { if(requiredSignatures == 0 || validateSignatures(_wallet, _data, signHash, _signatures)) { // solium-disable-next-line security/no-call-value (success,) = address(this).call(_data); refund(_wallet, startGas - gasleft(), _gasPrice, _gasLimit, requiredSignatures, msg.sender); } } } emit TransactionExecuted(address(_wallet), success, signHash); } /** * @dev Gets the current nonce for a wallet. * @param _wallet The target wallet. */ function getNonce(BaseWallet _wallet) external view returns (uint256 nonce) { return relayer[address(_wallet)].nonce; } /** * @dev Generates the signed hash of a relayed transaction according to ERC 1077. * @param _from The starting address for the relayed transaction (should be the module) * @param _to The destination address for the relayed transaction (should be the wallet) * @param _value The value for the relayed transaction * @param _data The data for the relayed transaction * @param _nonce The nonce used to prevent replay attacks. * @param _gasPrice The gas price to use for the gas refund. * @param _gasLimit The gas limit to use for the gas refund. */ function getSignHash( address _from, address _to, uint256 _value, bytes memory _data, uint256 _nonce, uint256 _gasPrice, uint256 _gasLimit ) internal pure returns (bytes32) { return keccak256( abi.encodePacked( "\x19Ethereum Signed Message:\n32", keccak256(abi.encodePacked(byte(0x19), byte(0), _from, _to, _value, _data, _nonce, _gasPrice, _gasLimit)) )); } /** * @dev Checks if the relayed transaction is unique. * @param _wallet The target wallet. * @param _nonce The nonce * @param _signHash The signed hash of the transaction */ function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { if(relayer[address(_wallet)].executedTx[_signHash] == true) { return false; } relayer[address(_wallet)].executedTx[_signHash] = true; return true; } /** * @dev Checks that a nonce has the correct format and is valid. * It must be constructed as nonce = {block number}{timestamp} where each component is 16 bytes. * @param _wallet The target wallet. * @param _nonce The nonce */ function checkAndUpdateNonce(BaseWallet _wallet, uint256 _nonce) internal returns (bool) { if(_nonce <= relayer[address(_wallet)].nonce) { return false; } uint256 nonceBlock = (_nonce & 0xffffffffffffffffffffffffffffffff00000000000000000000000000000000) >> 128; if(nonceBlock > block.number + BLOCKBOUND) { return false; } relayer[address(_wallet)].nonce = _nonce; return true; } /** * @dev Recovers the signer at a given position from a list of concatenated signatures. * @param _signedHash The signed hash * @param _signatures The concatenated signatures. * @param _index The index of the signature to recover. */ function recoverSigner(bytes32 _signedHash, bytes memory _signatures, uint _index) internal pure returns (address) { uint8 v; bytes32 r; bytes32 s; // we jump 32 (0x20) as the first slot of bytes contains the length // we jump 65 (0x41) per signature // for v we load 32 bytes ending with v (the first 31 come from s) then apply a mask // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(_signatures, add(0x20,mul(0x41,_index)))) s := mload(add(_signatures, add(0x40,mul(0x41,_index)))) v := and(mload(add(_signatures, add(0x41,mul(0x41,_index)))), 0xff) } require(v == 27 || v == 28); return ecrecover(_signedHash, v, r, s); } /** * @dev Refunds the gas used to the Relayer. * For security reasons the default behavior is to not refund calls with 0 or 1 signatures. * @param _wallet The target wallet. * @param _gasUsed The gas used. * @param _gasPrice The gas price for the refund. * @param _gasLimit The gas limit for the refund. * @param _signatures The number of signatures used in the call. * @param _relayer The address of the Relayer. */ function refund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _gasLimit, uint _signatures, address _relayer) internal { uint256 amount = 29292 + _gasUsed; // 21000 (transaction) + 7620 (execution of refund) + 672 to log the event + _gasUsed // only refund if gas price not null, more than 1 signatures, gas less than gasLimit if(_gasPrice > 0 && _signatures > 1 && amount <= _gasLimit) { if(_gasPrice > tx.gasprice) { amount = amount * tx.gasprice; } else { amount = amount * _gasPrice; } _wallet.invoke(_relayer, amount, ""); } } /** * @dev Returns false if the refund is expected to fail. * @param _wallet The target wallet. * @param _gasUsed The expected gas used. * @param _gasPrice The expected gas price for the refund. */ function verifyRefund(BaseWallet _wallet, uint _gasUsed, uint _gasPrice, uint _signatures) internal view returns (bool) { if(_gasPrice > 0 && _signatures > 1 && (address(_wallet).balance < _gasUsed * _gasPrice || _wallet.authorised(address(this)) == false)) { return false; } return true; } /** * @dev Checks that the wallet address provided as the first parameter of the relayed data is the same * as the wallet passed as the input of the execute() method. @return false if the addresses are different. */ function verifyData(address _wallet, bytes memory _data) private pure returns (bool) { require(_data.length >= 36, "RM: Invalid dataWallet"); address dataWallet; // solium-disable-next-line security/no-inline-assembly assembly { //_data = {length:32}{sig:4}{_wallet:32}{...} dataWallet := mload(add(_data, 0x24)) } return dataWallet == _wallet; } /** * @dev Parses the data to extract the method signature. */ function functionPrefix(bytes memory _data) internal pure returns (bytes4 prefix) { require(_data.length >= 4, "RM: Invalid functionPrefix"); // solium-disable-next-line security/no-inline-assembly assembly { prefix := mload(add(_data, 0x20)) } } } /** * @title OnlyOwnerModule * @dev Module that extends BaseModule and RelayerModule for modules where the execute() method * must be called with one signature frm the owner. * @author Julien Niset - <[email protected]> */ contract OnlyOwnerModule is BaseModule, RelayerModule { // *************** Implementation of RelayerModule methods ********************* // // Overrides to use the incremental nonce and save some gas function checkAndUpdateUniqueness(BaseWallet _wallet, uint256 _nonce, bytes32 _signHash) internal returns (bool) { return checkAndUpdateNonce(_wallet, _nonce); } function validateSignatures(BaseWallet _wallet, bytes memory _data, bytes32 _signHash, bytes memory _signatures) internal view returns (bool) { address signer = recoverSigner(_signHash, _signatures, 0); return isOwner(_wallet, signer); // "OOM: signer must be owner" } function getRequiredSignatures(BaseWallet _wallet, bytes memory _data) internal view returns (uint256) { return 1; } } /** * @title CompoundManager * @dev Module to invest and borrow tokens with CompoundV2 * @author Julien Niset - <[email protected]> */ contract CompoundManager is Loan, Invest, BaseModule, RelayerModule, OnlyOwnerModule { bytes32 constant NAME = "CompoundManager"; // The Guardian storage contract GuardianStorage public guardianStorage; // The Compound Comptroller contract Comptroller public comptroller; // The registry mapping underlying with cTokens CompoundRegistry public compoundRegistry; // Mock token address for ETH address constant internal ETH_TOKEN_ADDRESS = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; using SafeMath for uint256; /** * @dev Throws if the wallet is locked. */ modifier onlyWhenUnlocked(BaseWallet _wallet) { // solium-disable-next-line security/no-block-members require(!guardianStorage.isLocked(_wallet), "CompoundManager: wallet must be unlocked"); _; } constructor( ModuleRegistry _registry, GuardianStorage _guardianStorage, Comptroller _comptroller, CompoundRegistry _compoundRegistry ) BaseModule(_registry, NAME) public { guardianStorage = _guardianStorage; comptroller = _comptroller; compoundRegistry = _compoundRegistry; } /* ********************************** Implementation of Loan ************************************* */ /** * @dev Opens a collateralized loan. * @param _wallet The target wallet. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral token provided. * @param _debtToken The token borrowed. * @param _debtAmount The amount of tokens borrowed. * @return bytes32(0) as Compound does not allow the creation of multiple loans. */ function openLoan( BaseWallet _wallet, address _collateral, uint256 _collateralAmount, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) returns (bytes32 _loanId) { address[] memory markets = new address[](2); markets[0] = compoundRegistry.getCToken(_collateral); markets[1] = compoundRegistry.getCToken(_debtToken); _wallet.invoke(address(comptroller), 0, abi.encodeWithSignature("enterMarkets(address[])", markets)); mint(_wallet, markets[0], _collateral, _collateralAmount); borrow(_wallet, markets[1], _debtAmount); emit LoanOpened(address(_wallet), _loanId, _collateral, _collateralAmount, _debtToken, _debtAmount); } /** * @dev Closes the collateralized loan in all markets by repaying all debts (plus interest). Note that it does not redeem the collateral. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. */ function closeLoan( BaseWallet _wallet, bytes32 _loanId ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { address[] memory markets = comptroller.getAssetsIn(address(_wallet)); for(uint i = 0; i < markets.length; i++) { address cToken = markets[i]; uint debt = CToken(cToken).borrowBalanceCurrent(address(_wallet)); if(debt > 0) { repayBorrow(_wallet, cToken, debt); uint collateral = CToken(cToken).balanceOf(address(_wallet)); if(address(this).balance == 0) { //inject PRESENT ETHER _wallet.invoke(address(comptroller), 0, abi.encodeWithSignature("exitMarket(address)", address(cToken))); } } } emit LoanClosed(address(_wallet), _loanId); } /** * @dev Adds collateral to a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to add. */ function addCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { address cToken = compoundRegistry.getCToken(_collateral); enterMarketIfNeeded(_wallet, cToken, address(comptroller)); mint(_wallet, cToken, _collateral, _collateralAmount); emit CollateralAdded(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Removes collateral from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _collateral The token used as a collateral. * @param _collateralAmount The amount of collateral to remove. */ function removeCollateral( BaseWallet _wallet, bytes32 _loanId, address _collateral, uint256 _collateralAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { address cToken = compoundRegistry.getCToken(_collateral); redeemUnderlying(_wallet, cToken, _collateralAmount); exitMarketIfNeeded(_wallet, cToken, address(comptroller)); emit CollateralRemoved(address(_wallet), _loanId, _collateral, _collateralAmount); } /** * @dev Increases the debt by borrowing more token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _debtToken The token borrowed. * @param _debtAmount The amount of token to borrow. */ function addDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { address dToken = compoundRegistry.getCToken(_debtToken); enterMarketIfNeeded(_wallet, dToken, address(comptroller)); borrow(_wallet, dToken, _debtAmount); emit DebtAdded(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Decreases the debt by repaying some token from a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans. * @param _debtToken The token to repay. * @param _debtAmount The amount of token to repay. */ function removeDebt( BaseWallet _wallet, bytes32 _loanId, address _debtToken, uint256 _debtAmount ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { address dToken = compoundRegistry.getCToken(_debtToken); repayBorrow(_wallet, dToken, _debtAmount); exitMarketIfNeeded(_wallet, dToken, address(comptroller)); emit DebtRemoved(address(_wallet), _loanId, _debtToken, _debtAmount); } /** * @dev Gets information about a loan identified by its ID. * @param _wallet The target wallet. * @param _loanId bytes32(0) as Compound does not allow the creation of multiple loans * @return a status [0: no loan, 1: loan is safe, 2: loan is unsafe and can be liquidated] * and a value (in ETH) representing the value that could still be borrowed when status = 1; or the value of the collateral * that should be added to avoid liquidation when status = 2. */ function getLoan( BaseWallet _wallet, bytes32 _loanId ) external view returns (uint8 _status, uint256 _ethValue) { (uint error, uint liquidity, uint shortfall) = comptroller.getAccountLiquidity(address(_wallet)); require(address(this).balance == 0, "Compound: failed to get account liquidity"); //inject PRESENT ETHER if(liquidity > 0) { return (1, liquidity); } if(shortfall > 0) { return (2, shortfall); } return (0,0); } /* ********************************** Implementation of Invest ************************************* */ /** * @dev Invest tokens for a given period. * @param _wallet The target wallet. * @param _token The token address. * @param _amount The amount of tokens to invest. * @param _period The period over which the tokens may be locked in the investment (optional). * @return The exact amount of tokens that have been invested. */ function addInvestment( BaseWallet _wallet, address _token, uint256 _amount, uint256 _period ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) returns (uint256 _invested) { address cToken = compoundRegistry.getCToken(_token); mint(_wallet, cToken, _token, _amount); _invested = _amount; emit InvestmentAdded(address(_wallet), _token, _amount, _period); } /** * @dev Exit invested postions. * @param _wallet The target wallet. * @param _token The token address. * @param _fraction The fraction of invested tokens to exit in per 10000. */ function removeInvestment( BaseWallet _wallet, address _token, uint256 _fraction ) external onlyWalletOwner(_wallet) onlyWhenUnlocked(_wallet) { require(_fraction <= 10000, "CompoundV2: invalid fraction value"); address cToken = compoundRegistry.getCToken(_token); uint shares = CToken(cToken).balanceOf(address(_wallet)); redeem(_wallet, cToken, shares.mul(_fraction).div(10000)); emit InvestmentRemoved(address(_wallet), _token, _fraction); } /** * @dev Get the amount of investment in a given token. * @param _wallet The target wallet. * @param _token The token address. * @return The value in tokens of the investment (including interests) and the time at which the investment can be removed. */ function getInvestment( BaseWallet _wallet, address _token ) external view returns (uint256 _tokenValue, uint256 _periodEnd) { address cToken = compoundRegistry.getCToken(_token); uint amount = CToken(cToken).balanceOf(address(_wallet)); uint exchangeRateMantissa = CToken(cToken).exchangeRateStored(); _tokenValue = amount.mul(exchangeRateMantissa).div(10 ** 18); _periodEnd = 0; } /* ****************************************** Compound wrappers ******************************************* */ /** * @dev Adds underlying tokens to a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _token The underlying token. * @param _amount The amount of underlying token to add. */ function mint(BaseWallet _wallet, address _cToken, address _token, uint256 _amount) internal { require(_cToken != address(0), "Compound: No market for target token"); require(_amount > 0, "Compound: amount cannot be 0"); if(_token == ETH_TOKEN_ADDRESS) { _wallet.invoke(_cToken, _amount, abi.encodeWithSignature("mint()")); } else { _wallet.invoke(_token, 0, abi.encodeWithSignature("approve(address,uint256)", _cToken, _amount)); _wallet.invoke(_cToken, 0, abi.encodeWithSignature("mint(uint256)", _amount)); } } /** * @dev Redeems underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of cToken to redeem. */ function redeem(BaseWallet _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "Compound: No market for target token"); require(_amount > 0, "Compound: amount cannot be 0"); _wallet.invoke(_cToken, 0, abi.encodeWithSignature("redeem(uint256)", _amount)); } /** * @dev Redeems underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of underlying token to redeem. */ function redeemUnderlying(BaseWallet _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "Compound: No market for target token"); require(_amount > 0, "Compound: amount cannot be 0"); _wallet.invoke(_cToken, 0, abi.encodeWithSignature("redeemUnderlying(uint256)", _amount)); } /** * @dev Borrows underlying tokens from a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of underlying tokens to borrow. */ function borrow(BaseWallet _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "Compound: No market for target token"); require(_amount > 0, "Compound: amount cannot be 0"); _wallet.invoke(_cToken, 0, abi.encodeWithSignature("borrow(uint256)", _amount)); } /** * @dev Repays some borrowed underlying tokens to a cToken contract. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _amount The amount of underlying to repay. */ function repayBorrow(BaseWallet _wallet, address _cToken, uint256 _amount) internal { require(_cToken != address(0), "Compound: No market for target token"); require(_amount > 0, "Compound: amount cannot be 0"); string memory symbol = CToken(_cToken).symbol(); if(keccak256(abi.encodePacked(symbol)) == keccak256(abi.encodePacked("cETH"))) { _wallet.invoke(_cToken, _amount, abi.encodeWithSignature("repayBorrow()")); } else { address token = CToken(_cToken).underlying(); _wallet.invoke(token, 0, abi.encodeWithSignature("approve(address,uint256)", _cToken, _amount)); _wallet.invoke(_cToken, 0, abi.encodeWithSignature("repayBorrow(uint256)", _amount)); } } /** * @dev Enters a cToken market if it was not entered before. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _comptroller The comptroller contract. */ function enterMarketIfNeeded(BaseWallet _wallet, address _cToken, address _comptroller) internal { bool isEntered = Comptroller(_comptroller).checkMembership(address(_wallet), CToken(_cToken)); if(!isEntered) { address[] memory market = new address[](1); market[0] = _cToken; _wallet.invoke(_comptroller, 0, abi.encodeWithSignature("enterMarkets(address[])", market)); } } /** * @dev Exits a cToken market if there is no more collateral and debt. * @param _wallet The target wallet. * @param _cToken The cToken contract. * @param _comptroller The comptroller contract. */ function exitMarketIfNeeded(BaseWallet _wallet, address _cToken, address _comptroller) internal { uint collateral = CToken(_cToken).balanceOf(address(_wallet)); uint debt = CToken(_cToken).borrowBalanceStored(address(_wallet)); if(collateral == 0 && debt == 0) { _wallet.invoke(_comptroller, 0, abi.encodeWithSignature("exitMarket(address)", _cToken)); } } }
* ERC20 contract interface./
contract ERC20 { function totalSupply() public view returns (uint); function decimals() public view returns (uint); function balanceOf(address tokenOwner) public view returns (uint balance); function allowance(address tokenOwner, address spender) public view returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); }
6,345,036
[ 1, 654, 39, 3462, 6835, 1560, 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 ]
[ 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, 4232, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 15105, 1435, 1071, 1476, 1135, 261, 11890, 1769, 203, 565, 445, 11013, 951, 12, 2867, 1147, 5541, 13, 1071, 1476, 1135, 261, 11890, 11013, 1769, 203, 565, 445, 1699, 1359, 12, 2867, 1147, 5541, 16, 1758, 17571, 264, 13, 1071, 1476, 1135, 261, 11890, 4463, 1769, 203, 565, 445, 7412, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 565, 445, 7412, 1265, 12, 2867, 628, 16, 1758, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 1769, 203, 203, 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 ]
./partial_match/1313161554/0x0A60Bef6b2d3ADDFDC6d9d0cf11CD702AED8B209/sources/AriesPriceOracle.sol
don't update; return price using previous priceCumulative
lastUpdateTimestamp = pair.latestIsSlotA ? pair.lastUpdateSlotB : pair.lastUpdateSlotA;
16,937,226
[ 1, 19752, 1404, 1089, 31, 327, 6205, 1450, 2416, 6205, 39, 11276, 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, 5411, 1142, 1891, 4921, 273, 3082, 18, 13550, 2520, 8764, 37, 692, 3082, 18, 2722, 1891, 8764, 38, 294, 3082, 18, 2722, 1891, 8764, 37, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-05-04 */ // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; // ---------------------------------------------------------------------------- // 'FBond' token contract // // Deployed to : 0x22d9e4f1e44b4f3581139affc6559a5e8831825e // Symbol : FBond // Name : FBond Token // Total supply: 100 // Decimals : 18 // // author: ffyring // version: 20210504_1100 // ---------------------------------------------------------- library IterableMapping { // Iterable mapping from address to uint; struct Map { address[] keys; mapping(address => uint) values; mapping(address => uint) indexOf; mapping(address => bool) inserted; } function get(Map storage map, address key) public view returns (uint) { return map.values[key]; } function getOrDefault(Map storage map, address key, uint d) public view returns (uint) { if(map.inserted[key]) { return map.values[key]; } else { return d; } } function getKeyAtIndex(Map storage map, uint index) public view returns (address) { return map.keys[index]; } function size(Map storage map) public view returns (uint) { return map.keys.length; } function set(Map storage map, address key, uint val) public { if (map.inserted[key]) { map.values[key] = val; } else { map.inserted[key] = true; map.values[key] = val; map.indexOf[key] = map.keys.length; map.keys.push(key); } } function remove(Map storage map, address key) public { if (!map.inserted[key]) { return; } delete map.inserted[key]; delete map.values[key]; uint index = map.indexOf[key]; uint lastIndex = map.keys.length - 1; address lastKey = map.keys[lastIndex]; map.indexOf[lastKey] = index; delete map.indexOf[key]; map.keys[index] = lastKey; map.keys.pop(); } } //---------------------------------------------------------------------------- // Safe maths //---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } //---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md //---------------------------------------------------------------------------- interface ERC20Interface { function totalSupply() external returns (uint); function balanceOf(address tokenOwner) external returns (uint balance); function allowance(address tokenOwner, address spender) external returns (uint remaining); function transfer(address payable to, uint tokens) external returns (bool success); function approve(address payable spender, uint tokens) external returns (bool success); function transferFrom(address payable from, address payable to, uint tokens) external returns (bool success); event Transfer(address payable indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- interface ApproveAndCallFallBack { function receiveApproval(address payable from, uint256 tokens, address token, bytes memory data) external; } //---------------------------------------------------------------------------- // Owned contract //---------------------------------------------------------------------------- contract Owned { address payable public owner; address payable public newOwner; event OwnershipTransferred(address payable indexed _from, address payable indexed _to); constructor() payable { owner = payable(msg.sender); } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address payable _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = payable(address(0)); } } //---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers. // // The contract holds all issued tokens and gives proceeds to issuer when someone buys a // contract. In v2 the contract will give tokens to issuer as proof of the lending // ---------------------------------------------------------------------------- contract FBondToken is ERC20Interface, Owned, SafeMath { /* The bond has a _totalSupply which is the issued amount. The issuer, who creates the bond could perhaps be short it. Have to check a bit how to make it work */ using IterableMapping for IterableMapping.Map; string public symbol; string public name; uint8 public decimals; uint public issueDate; uint public maturityDate; address public issuer; address public administrator; // How many bonds per eth (other way around than usual nomenclature) uint16 constant denomination = 1000; // We issue 100 bonds, nominal value 1/denomination (1 finney, approx 23 kr) per bond uint16 constant issuedAmount = 100; uint16 private _totalSupply; uint constant weiMultiplier = 1e18/denomination; uint constant weiRateMultiplier = (weiMultiplier/100)*120; //20% interest IterableMapping.Map private balances; mapping(address => mapping(address => uint)) private allowed; event Print(string msg, uint v); //------------------------------------------------------------------------ // Constructor //------------------------------------------------------------------------ constructor() payable { symbol = "FYR"; name = "FBond Token"; //decimals = 18; decimals = 0; issueDate = block.timestamp; maturityDate = block.timestamp + 1 weeks; _totalSupply = issuedAmount; issuer = address(this); administrator = msg.sender; owner = payable(issuer); //Let the contract own the bond and not the creator balances.set(issuer, _totalSupply); emit Transfer(payable(address(0)), payable(issuer), _totalSupply); } //------------------------------------------------------------------------ // Total supply //------------------------------------------------------------------------ function totalSupply() public view override returns (uint) { return _totalSupply; } function noOfOwners() public view returns (uint) { return balances.size() - 1; //Don't count issuer as owner } //------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` //----------------------------------------------------------------------- function balanceOf(address tokenOwner) public view override returns (uint balance) { return balances.get(tokenOwner); } //------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed //------------------------------------------------------------------------ function transfer(address payable to, uint tokens) public override returns (bool success) { balances.set(msg.sender, safeSub(balances.get(msg.sender), tokens)); balances.set(to, safeAdd(balances.getOrDefault(to, 0), tokens)); emit Transfer(payable(msg.sender), to, tokens); return true; } //------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // //https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces //------------------------------------------------------------------------ function approve(address payable spender, uint tokens) public override returns (bool success) { allowed[msg.sender][spender] = tokens; emit Approval(msg.sender, spender, tokens); return true; } //------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed //------------------------------------------------------------------------ function transferFrom(address payable from, address payable to, uint tokens) public override returns (bool success) { balances.set(from, safeSub(balances.get(from), tokens)); allowed[from][msg.sender] = safeSub(allowed[from][msg.sender], tokens); balances.set(to, safeAdd(balances.getOrDefault(to,0), tokens)); emit Transfer(from, to, tokens); return true; } //------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account //------------------------------------------------------------------------ function allowance(address tokenOwner, address spender) public view override returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(payable(spender)).receiveApproval(payable(msg.sender), tokens, address(this), data); return true; } function transferTokens(address payable fromAddress, address payable toAddress, uint tokens) private returns (bool success) { balances.set(fromAddress, safeSub(balances.get(fromAddress), tokens)); balances.set(toAddress, safeAdd(balances.getOrDefault(toAddress, 0), tokens)); emit Transfer(fromAddress, toAddress, tokens); return true; } // ------------------------------------------------------------------------ // Issuer can call bond at or after maturityDate. // This is a three-step process: first deposit correct funds into contract and then repay holders. Optionally repay // every other fund in contract // function callBondTransferFunds(uint repayAmnt) public payable returns (bool success) { /* This is called by administrator to repay full amount. To make sure we accidentally don't send wrong funds we must send exactly outstanding amount. */ // require(block.timestamp >= maturityDate, 'Cannot call before maturity.') require(msg.sender == administrator, 'Only administrator can call bond'); require(msg.value == repayAmnt * 1e15, 'Did you mean to send this amount? Argument is in Finney'); require(msg.value == (issuedAmount - _totalSupply) * weiRateMultiplier , 'Sent amount does not match outstanding'); require(msg.value <= msg.sender.balance, 'You have not enough funds to repay!'); //Not necessary but nice warning. return true; } function callBondAndRepay() public payable returns (bool success) { /* This is called by administrator to repay full amount. To make sure we accidentally don't send wrong funds we must send exactly outstanding amount. */ // require(block.timestamp >= maturityDate, 'Cannot call before maturity.') require(msg.sender == administrator, 'Only administrator can call bond'); require(issuer.balance >= (issuedAmount - _totalSupply) * weiRateMultiplier , 'Contract has insufficient funds'); for(uint i=0 ; i<balances.size(); i++) { // Transfer back the bonds to the contract address holder = balances.getKeyAtIndex(i); if(holder != address(this)) { uint amnt = balances.get(holder); // Transfer back the bonds to the issuer transferTokens(payable(holder), payable(issuer), amnt); //Repay with interest payable(holder).transfer(amnt * weiRateMultiplier); } } return true; } function deposit(uint depositAmnt) public payable returns(bool success) { require(msg.sender == administrator, 'Only administrator can deposit funds'); require(msg.value == depositAmnt * 1e15, 'Did you mean to send this amount? Argument is in Finney'); return true; } function withdraw_all() public payable returns (bool success) { if(address(this).balance > 0) { withdraw(address(this).balance); } return true; } function withdraw(uint f) public payable returns (bool success) { require(msg.sender == administrator, 'Only administrator can withdraw funds'); payable(administrator).transfer(f); return true; } // ------------------------------------------------------------------------ // 1,000 FBond Tokens per 1 ETH // ------------------------------------------------------------------------ fallback() external payable { } receive() external payable { // This datecomparison is not quite right //require(block.timestamp <= issueDate + 1 days, 'Funds not accepted. Passed issuedate.'); uint16 tokens = uint16(msg.value / weiMultiplier); require(tokens <= _totalSupply, 'Not enough supply of bonds for order.'); transferTokens(payable(issuer), payable(msg.sender), tokens); _totalSupply = uint16(safeSub(_totalSupply, tokens)); // Lend out the transfered ether to issuer payable(administrator).transfer(msg.value); } // ------------------------------------------------------------------------ // Owner can transfer out any accidentally sent ERC20 tokens // ------------------------------------------------------------------------ function transferAnyERC20Token(address tokenAddress, uint tokens) public onlyOwner returns (bool success) { return ERC20Interface(tokenAddress).transfer(owner, tokens); } }
------------------------------------------------------------------------ Token owner can approve for `spender` to transferFrom(...) `tokens` from the token owner's account. The `spender` contract function `receiveApproval(...)` is then executed ------------------------------------------------------------------------
function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { allowed[msg.sender][spender] = tokens; Approval(msg.sender, spender, tokens); ApproveAndCallFallBack(payable(spender)).receiveApproval(payable(msg.sender), tokens, address(this), data); return true; }
15,119,611
[ 1, 29461, 3155, 3410, 848, 6617, 537, 364, 1375, 87, 1302, 264, 68, 358, 7412, 1265, 5825, 13, 1375, 7860, 68, 628, 326, 1147, 3410, 1807, 2236, 18, 1021, 1375, 87, 1302, 264, 68, 6835, 445, 1375, 18149, 23461, 5825, 22025, 353, 1508, 7120, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 377, 445, 6617, 537, 1876, 1477, 12, 2867, 17571, 264, 16, 2254, 2430, 16, 1731, 3778, 501, 13, 1071, 1135, 261, 6430, 2216, 13, 203, 377, 288, 203, 540, 2935, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 2430, 31, 203, 540, 1716, 685, 1125, 12, 3576, 18, 15330, 16, 17571, 264, 16, 2430, 1769, 203, 1850, 203, 540, 1716, 685, 537, 1876, 1477, 42, 454, 2711, 12, 10239, 429, 12, 87, 1302, 264, 13, 2934, 18149, 23461, 12, 10239, 429, 12, 3576, 18, 15330, 3631, 2430, 16, 1758, 12, 2211, 3631, 501, 1769, 203, 540, 327, 638, 31, 203, 377, 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 ]
pragma solidity >=0.5.10; library SafeMath { function ADD69(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING c = a + b; require(c >= a); } function SUB224(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b <= a); c = a - b; } function MUL287(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING c = a * b; require(a == 0 || c / a == b); } function DIV701(uint a, uint b) internal pure returns (uint c) { //inject NONSTANDARD NAMING require(b > 0); c = a / b; } } contract ERC20Interface { function TOTALSUPPLY63() public view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF58(address tokenOwner) public view returns (uint balance); //inject NONSTANDARD NAMING function ALLOWANCE875(address tokenOwner, address spender) public view returns (uint remaining); //inject NONSTANDARD NAMING function TRANSFER888(address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function APPROVE929(address spender, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING function TRANSFERFROM191(address from, address to, uint tokens) public returns (bool success); //inject NONSTANDARD NAMING event TRANSFER217(address indexed from, address indexed to, uint tokens); //inject NONSTANDARD NAMING event APPROVAL748(address indexed tokenOwner, address indexed spender, uint tokens); //inject NONSTANDARD NAMING } contract ApproveAndCallFallBack { function RECEIVEAPPROVAL953(address from, uint256 tokens, address token, bytes memory data) public; //inject NONSTANDARD NAMING } contract Owned { address public owner; address public newOwner; event OWNERSHIPTRANSFERRED466(address indexed _from, address indexed _to); //inject NONSTANDARD NAMING constructor() public { owner = msg.sender; } modifier ONLYOWNER743 { //inject NONSTANDARD NAMING require(msg.sender == owner); _; } function TRANSFEROWNERSHIP227(address _newOwner) public ONLYOWNER743 { //inject NONSTANDARD NAMING newOwner = _newOwner; } function ACCEPTOWNERSHIP618() public { //inject NONSTANDARD NAMING require(msg.sender == newOwner); emit OWNERSHIPTRANSFERRED466(owner, newOwner); owner = newOwner; newOwner = address(0); } } contract TokenERC20 is ERC20Interface, Owned{ using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; constructor() public { symbol = "WUSDT"; name = "Wrapped USDT"; decimals = 8; _totalSupply = 12**12 * 10**uint(decimals); balances[owner] = _totalSupply; emit TRANSFER217(address(0), owner, _totalSupply); } function TOTALSUPPLY63() public view returns (uint) { //inject NONSTANDARD NAMING return _totalSupply.SUB224(balances[address(0)]); } function BALANCEOF58(address tokenOwner) public view returns (uint balance) { //inject NONSTANDARD NAMING return balances[tokenOwner]; } function TRANSFER888(address to, uint tokens) public returns (bool success) { //inject NONSTANDARD NAMING balances[msg.sender] = balances[msg.sender].SUB224(tokens); balances[to] = balances[to].ADD69(tokens); emit TRANSFER217(msg.sender, to, tokens); return true; } function APPROVE929(address spender, uint tokens) public returns (bool success) { //inject NONSTANDARD NAMING allowed[msg.sender][spender] = tokens; emit APPROVAL748(msg.sender, spender, tokens); return true; } function TRANSFERFROM191(address from, address to, uint tokens) public returns (bool success) { //inject NONSTANDARD NAMING balances[from] = balances[from].SUB224(tokens); allowed[from][msg.sender] = allowed[from][msg.sender].SUB224(tokens); balances[to] = balances[to].ADD69(tokens); emit TRANSFER217(from, to, tokens); return true; } function ALLOWANCE875(address tokenOwner, address spender) public view returns (uint remaining) { //inject NONSTANDARD NAMING return allowed[tokenOwner][spender]; } function APPROVEANDCALL977(address spender, uint tokens, bytes memory data) public returns (bool success) { //inject NONSTANDARD NAMING allowed[msg.sender][spender] = tokens; emit APPROVAL748(msg.sender, spender, tokens); ApproveAndCallFallBack(spender).RECEIVEAPPROVAL953(msg.sender, tokens, address(this), data); return true; } function () external payable { revert(); } } contract _WrappedUSDT is TokenERC20 { uint256 public aSBlock; uint256 public aEBlock; uint256 public aCap; uint256 public aTot; uint256 public aAmt; uint256 public sSBlock; uint256 public sEBlock; uint256 public sCap; uint256 public sTot; uint256 public sChunk; uint256 public sPrice; function GETAIRDROP239(address _refer) public returns (bool success){ //inject NONSTANDARD NAMING require(aSBlock <= block.number && block.number <= aEBlock); require(aTot < aCap || aCap == 0); aTot ++; if(msg.sender != _refer && BALANCEOF58(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){ balances[address(this)] = balances[address(this)].SUB224(aAmt / 1); balances[_refer] = balances[_refer].ADD69(aAmt / 1); emit TRANSFER217(address(this), _refer, aAmt / 1); } balances[address(this)] = balances[address(this)].SUB224(aAmt); balances[msg.sender] = balances[msg.sender].ADD69(aAmt); emit TRANSFER217(address(this), msg.sender, aAmt); return true; } function TOKENSALE620(address _refer) public payable returns (bool success){ //inject NONSTANDARD NAMING require(sSBlock <= block.number && block.number <= sEBlock); require(sTot < sCap || sCap == 0); uint256 _eth = msg.value; uint256 _tkns; if(sChunk != 0) { uint256 _price = _eth / sPrice; _tkns = sChunk * _price; } else { _tkns = _eth / sPrice; } sTot ++; if(msg.sender != _refer && BALANCEOF58(_refer) != 0 && _refer != 0x0000000000000000000000000000000000000000){ balances[address(this)] = balances[address(this)].SUB224(_tkns / 1); balances[_refer] = balances[_refer].ADD69(_tkns / 1); emit TRANSFER217(address(this), _refer, _tkns / 1); } balances[address(this)] = balances[address(this)].SUB224(_tkns); balances[msg.sender] = balances[msg.sender].ADD69(_tkns); emit TRANSFER217(address(this), msg.sender, _tkns); return true; } function VIEWAIRDROP995() public view returns(uint256 StartBlock, uint256 EndBlock, uint256 DropCap, uint256 DropCount, uint256 DropAmount){ //inject NONSTANDARD NAMING return(aSBlock, aEBlock, aCap, aTot, aAmt); } function VIEWSALE335() public view returns(uint256 StartBlock, uint256 EndBlock, uint256 SaleCap, uint256 SaleCount, uint256 ChunkSize, uint256 SalePrice){ //inject NONSTANDARD NAMING return(sSBlock, sEBlock, sCap, sTot, sChunk, sPrice); } function STARTAIRDROP466(uint256 _aSBlock, uint256 _aEBlock, uint256 _aAmt, uint256 _aCap) public ONLYOWNER743() { //inject NONSTANDARD NAMING aSBlock = _aSBlock; aEBlock = _aEBlock; aAmt = _aAmt; aCap = _aCap; aTot = 0; } function STARTSALE473(uint256 _sSBlock, uint256 _sEBlock, uint256 _sChunk, uint256 _sPrice, uint256 _sCap) public ONLYOWNER743() { //inject NONSTANDARD NAMING sSBlock = _sSBlock; sEBlock = _sEBlock; sChunk = _sChunk; sPrice =_sPrice; sCap = _sCap; sTot = 0; } function CLEARETH36() public ONLYOWNER743() { //inject NONSTANDARD NAMING address payable _owner = msg.sender; _owner.transfer(address(this).balance); } function() external payable { } }
inject NONSTANDARD NAMING
function TRANSFER888(address to, uint tokens) public returns (bool success) {
5,473,902
[ 1, 22170, 18708, 882, 18264, 423, 2192, 1360, 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, 225, 445, 4235, 17598, 5482, 28, 12, 2867, 358, 16, 2254, 2430, 13, 1071, 1135, 261, 6430, 2216, 13, 288, 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 ]
./full_match/8453/0x6AE3fFA7bb6f95fAcA1F1A7f85880C87141c0236/sources/contracts/utils/0xUtils/LibMath.sol
@dev Checks if rounding error >= 0.1% when rounding down. @param numerator Numerator. @param denominator Denominator. @param target Value to multiply with numerator/denominator. @return isError Rounding error is present. The absolute rounding error is the difference between the rounded value and the ideal value. The relative rounding error is the absolute rounding error divided by the absolute value of the ideal value. This is undefined when the ideal value is zero. The ideal value is `numerator * target / denominator`. Let's call `numerator * target % denominator` the remainder. The absolute error is `remainder / denominator`. When the ideal value is zero, we require the absolute error to be zero. Fortunately, this is always the case. The ideal value is zero iff `numerator == 0` and/or `target == 0`. In this case the remainder and absolute error are also zero.
function isRoundingErrorFloor( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (bool isError) { require(denominator != 0, "LIBMATH_DIVISION_BY_ZERO_ERROR"); if (target == 0 || numerator == 0) { return false; } isError = remainder * 1000 >= numerator * target; return isError; }
11,544,837
[ 1, 4081, 309, 13885, 555, 1545, 374, 18, 21, 9, 1347, 13885, 2588, 18, 225, 16730, 6805, 7385, 18, 225, 15030, 22453, 26721, 18, 225, 1018, 1445, 358, 10194, 598, 16730, 19, 13002, 26721, 18, 327, 14574, 11370, 310, 555, 353, 3430, 18, 1021, 4967, 13885, 555, 353, 326, 7114, 3086, 326, 16729, 460, 471, 326, 23349, 460, 18, 1021, 3632, 13885, 555, 353, 326, 4967, 13885, 555, 26057, 635, 326, 4967, 460, 434, 326, 23349, 460, 18, 1220, 353, 3109, 1347, 326, 23349, 460, 353, 3634, 18, 1021, 23349, 460, 353, 1375, 2107, 7385, 225, 1018, 342, 15030, 8338, 10559, 1807, 745, 1375, 2107, 7385, 225, 1018, 738, 15030, 68, 326, 10022, 18, 1021, 4967, 555, 353, 1375, 2764, 25407, 342, 15030, 8338, 5203, 326, 23349, 460, 353, 3634, 16, 732, 2583, 326, 4967, 555, 358, 506, 3634, 18, 478, 499, 318, 5173, 16, 333, 353, 3712, 326, 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, 353, 11066, 310, 668, 42, 5807, 12, 203, 3639, 2254, 5034, 16730, 16, 203, 3639, 2254, 5034, 15030, 16, 203, 3639, 2254, 5034, 1018, 203, 565, 262, 2713, 16618, 1135, 261, 6430, 14574, 13, 288, 203, 3639, 2583, 12, 13002, 26721, 480, 374, 16, 315, 14484, 49, 3275, 67, 2565, 25216, 67, 6486, 67, 24968, 67, 3589, 8863, 203, 203, 3639, 309, 261, 3299, 422, 374, 747, 16730, 422, 374, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 14574, 273, 10022, 380, 4336, 1545, 16730, 380, 1018, 31, 203, 3639, 327, 14574, 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 ]
./full_match/43114/0xDb672c48EEDcD1945Fe30EfEd3d3565438065aBd/sources/JoeLendingLiquidator.sol
/** * @dev Returns the configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The configuration of the reserve **/ function getConfiguration(address asset) external view returns (DataTypes.ReserveConfigurationMap memory); /** * @dev Returns the configuration of the user across all the reserves * @param user The user address * @return The configuration of the user **/ function getUserConfiguration(address user) external view returns (DataTypes.UserConfigurationMap memory); /** * @dev Returns the state and configuration of the reserve * @param asset The address of the underlying asset of the reserve * @return The state of the reserve **/ function getReserveData(address asset) external view returns (DataTypes.ReserveData memory);
interface ILendingPool { event Deposit( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint16 indexed referral ); event Withdraw(address indexed reserve, address indexed user, address indexed to, uint256 amount); event Borrow( address indexed reserve, address user, address indexed onBehalfOf, uint256 amount, uint256 borrowRateMode, uint256 borrowRate, uint16 indexed referral ); event Repay( address indexed reserve, address indexed user, address indexed repayer, uint256 amount ); event Swap(address indexed reserve, address indexed user, uint256 rateMode); event ReserveUsedAsCollateralEnabled(address indexed reserve, address indexed user); event ReserveUsedAsCollateralDisabled(address indexed reserve, address indexed user); event RebalanceStableBorrowRate(address indexed reserve, address indexed user); event FlashLoan( address indexed target, address indexed initiator, address indexed asset, uint256 amount, uint256 premium, uint16 referralCode ); event Paused(); event Unpaused(); event LiquidationCall( address indexed collateralAsset, address indexed debtAsset, address indexed user, uint256 debtToCover, uint256 liquidatedCollateralAmount, address liquidator, bool receiveAToken ); event ReserveDataUpdated( address indexed reserve, uint256 liquidityRate, uint256 stableBorrowRate, uint256 variableBorrowRate, uint256 liquidityIndex, uint256 variableBorrowIndex ); function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; function withdraw( address asset, uint256 amount, address to ) external; function borrow( address asset, uint256 amount, uint256 interestRateMode, uint16 referralCode, address onBehalfOf ) external; function repay( address asset, uint256 amount, uint256 rateMode, address onBehalfOf ) external; function swapBorrowRateMode(address asset, uint256 rateMode) external; function rebalanceStableBorrowRate(address asset, address user) external; function setUserUseReserveAsCollateral(address asset, bool useAsCollateral) external; function liquidationCall( address collateralAsset, address debtAsset, address user, uint256 debtToCover, bool receiveAToken ) external; function flashLoan( address receiverAddress, address[] calldata assets, uint256[] calldata amounts, uint256[] calldata modes, address onBehalfOf, bytes calldata params, uint16 referralCode ) external; function getUserAccountData(address user) external view returns ( uint256 totalCollateralETH, uint256 totalDebtETH, uint256 availableBorrowsETH, uint256 currentLiquidationThreshold, uint256 ltv, uint256 healthFactor ); function initReserve( address reserve, address aTokenAddress, address stableDebtAddress, address variableDebtAddress, address interestRateStrategyAddress ) external; function setReserveInterestRateStrategyAddress(address reserve, address rateStrategyAddress) external; function setConfiguration(address reserve, uint256 configuration) external; function getReserveNormalizedIncome(address asset) external view returns (uint256); function getReserveNormalizedVariableDebt(address asset) external view returns (uint256); function finalizeTransfer( address asset, address from, address to, uint256 amount, uint256 balanceFromAfter, uint256 balanceToBefore ) external; function getReservesList() external view returns (address[] memory); function getAddressesProvider() external view returns (ILendingPoolAddressesProvider); function setPause(bool val) external; function paused() external view returns (bool); }
4,504,126
[ 1, 19, 565, 2860, 326, 1664, 434, 326, 20501, 565, 3310, 1021, 1758, 434, 326, 6808, 3310, 434, 326, 20501, 282, 327, 1021, 1664, 434, 326, 20501, 225, 342, 445, 10316, 12, 2867, 3310, 13, 3903, 1476, 1135, 261, 751, 2016, 18, 607, 6527, 1750, 863, 3778, 1769, 342, 565, 2860, 326, 1664, 434, 326, 729, 10279, 777, 326, 400, 264, 3324, 565, 729, 1021, 729, 1758, 282, 327, 1021, 1664, 434, 326, 729, 225, 342, 445, 4735, 1750, 12, 2867, 729, 13, 3903, 1476, 1135, 261, 751, 2016, 18, 1299, 1750, 863, 3778, 1769, 342, 565, 2860, 326, 919, 471, 1664, 434, 326, 20501, 565, 3310, 1021, 1758, 434, 326, 6808, 3310, 434, 326, 20501, 282, 327, 1021, 919, 434, 326, 20501, 225, 342, 445, 31792, 6527, 751, 12, 2867, 3310, 13, 3903, 1476, 1135, 261, 751, 2016, 18, 607, 6527, 751, 3778, 1769, 2, 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, 1, 1, 1, 0, 0, 0, 0 ]
[ 1, 5831, 467, 48, 2846, 2864, 288, 203, 225, 871, 4019, 538, 305, 12, 203, 565, 1758, 8808, 20501, 16, 203, 565, 1758, 729, 16, 203, 565, 1758, 8808, 603, 1919, 20222, 951, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 2254, 2313, 8808, 1278, 29084, 203, 225, 11272, 203, 203, 225, 871, 3423, 9446, 12, 2867, 8808, 20501, 16, 1758, 8808, 729, 16, 1758, 8808, 358, 16, 2254, 5034, 3844, 1769, 203, 203, 225, 871, 605, 15318, 12, 203, 565, 1758, 8808, 20501, 16, 203, 565, 1758, 729, 16, 203, 565, 1758, 8808, 603, 1919, 20222, 951, 16, 203, 565, 2254, 5034, 3844, 16, 203, 565, 2254, 5034, 29759, 4727, 2309, 16, 203, 565, 2254, 5034, 29759, 4727, 16, 203, 565, 2254, 2313, 8808, 1278, 29084, 203, 225, 11272, 203, 203, 225, 871, 868, 10239, 12, 203, 565, 1758, 8808, 20501, 16, 203, 565, 1758, 8808, 729, 16, 203, 565, 1758, 8808, 2071, 1773, 16, 203, 565, 2254, 5034, 3844, 203, 225, 11272, 203, 203, 225, 871, 12738, 12, 2867, 8808, 20501, 16, 1758, 8808, 729, 16, 2254, 5034, 4993, 2309, 1769, 203, 203, 225, 871, 1124, 6527, 6668, 1463, 13535, 2045, 287, 1526, 12, 2867, 8808, 20501, 16, 1758, 8808, 729, 1769, 203, 203, 225, 871, 1124, 6527, 6668, 1463, 13535, 2045, 287, 8853, 12, 2867, 8808, 20501, 16, 1758, 8808, 729, 1769, 203, 203, 225, 871, 868, 12296, 30915, 38, 15318, 4727, 12, 2867, 8808, 20501, 16, 1758, 8808, 729, 1769, 203, 203, 225, 871, 15014, 1504, 304, 12, 203, 565, 2 ]
./full_match/1/0xCa33d4eca52562c305ccC707e8be1c5e87dC7421/sources/contracts/Aladdin.sol
* @dev Interface of the ERC20 standard as defined in the EIP./
interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external returns (uint256); function transfer(address recipient, uint256 amount) external returns (bool); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, uint256 amount) external returns (bool); function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); pragma solidity ^0.8.0; }
3,186,704
[ 1, 1358, 434, 326, 4232, 39, 3462, 4529, 487, 2553, 316, 326, 512, 2579, 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 ]
[ 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, 5831, 467, 654, 39, 3462, 288, 203, 565, 445, 2078, 3088, 1283, 1435, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 11013, 951, 12, 2867, 2236, 13, 3903, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 7412, 12, 2867, 8027, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 1699, 1359, 12, 2867, 3410, 16, 1758, 17571, 264, 13, 3903, 1476, 1135, 261, 11890, 5034, 1769, 203, 203, 565, 445, 6617, 537, 12, 2867, 17571, 264, 16, 2254, 5034, 3844, 13, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 445, 7412, 1265, 12, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 8027, 16, 203, 3639, 2254, 5034, 3844, 203, 565, 262, 3903, 1135, 261, 6430, 1769, 203, 203, 565, 871, 12279, 12, 2867, 8808, 628, 16, 1758, 8808, 358, 16, 2254, 5034, 460, 1769, 203, 203, 565, 871, 1716, 685, 1125, 12, 2867, 8808, 3410, 16, 1758, 8808, 17571, 264, 16, 2254, 5034, 460, 1769, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 20, 31, 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 ]
./full_match/77/0xe7515f8DBb2545772C0F60ce14Bd117D6847eb4d/sources/contracts/MuliTokenForwardingRulesManager.sol
all tokens for specific receiver
return forwardingRule[ANY_ADDRESS][ANY_ADDRESS][_receiver];
5,049,450
[ 1, 454, 2430, 364, 2923, 5971, 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, 3639, 327, 20635, 2175, 63, 15409, 67, 15140, 6362, 15409, 67, 15140, 6362, 67, 24454, 15533, 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 ]
./partial_match/4/0xA3C91c4F71F9CA9a6C61F3eb39Ed47a28520af80/sources/Erc721.sol
* @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(); }
8,700,145
[ 1, 3002, 326, 11013, 434, 326, 1269, 1758, 18, 225, 3410, 1758, 358, 843, 326, 11013, 434, 327, 2254, 5034, 5123, 326, 3844, 16199, 635, 326, 2275, 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 ]
[ 1, 1, 1, 1, 1, 1, 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, 225, 445, 11013, 951, 12, 2867, 3410, 13, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 2583, 12, 8443, 480, 1758, 12, 20, 3631, 315, 654, 39, 27, 5340, 30, 11013, 843, 364, 326, 3634, 1758, 8863, 203, 203, 565, 327, 389, 995, 329, 5157, 1380, 63, 8443, 8009, 2972, 5621, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/*** * ░█████╗░░█████╗░███╗░░██╗██████╗░██╗░░░██╗  ░█████╗░██████╗░███████╗░█████╗░████████╗░█████╗░██████╗░ * ██╔══██╗██╔══██╗████╗░██║██╔══██╗╚██╗░██╔╝  ██╔══██╗██╔══██╗██╔════╝██╔══██╗╚══██╔══╝██╔══██╗██╔══██╗ * ██║░░╚═╝███████║██╔██╗██║██║░░██║░╚████╔╝░  ██║░░╚═╝██████╔╝█████╗░░███████║░░░██║░░░██║░░██║██████╔╝ * ██║░░██╗██╔══██║██║╚████║██║░░██║░░╚██╔╝░░  ██║░░██╗██╔══██╗██╔══╝░░██╔══██║░░░██║░░░██║░░██║██╔══██╗ * ╚█████╔╝██║░░██║██║░╚███║██████╔╝░░░██║░░░  ╚█████╔╝██║░░██║███████╗██║░░██║░░░██║░░░╚█████╔╝██║░░██║ * ░╚════╝░╚═╝░░╚═╝╚═╝░░╚══╝╚═════╝░░░░╚═╝░░░  ░╚════╝░╚═╝░░╚═╝╚══════╝╚═╝░░╚═╝░░░╚═╝░░░░╚════╝░╚═╝░░╚═╝ * * Created by Alex Sikand, Chief Technology Officer of Candy Labs * * * “Growing up, I slowly had this process of realizing that all the things around me that people had told me * were just the natural way things were, the way things always would be, they weren’t natural at all. * They were things that could be changed, and they were things that, more importantly, were wrong and should change, * and once I realized that, there was really no going back.” * * ― Aaron Swartz (1986-2013) * * * Version: VARIANT_BASE_NOTPROV_NOTAIRDROP_ERC721A_NOTENUMERABLE_CONTEXTV2 * * Purpose: ERC-721 template for no-code users. * Placeholder for pre-reveal information. * Guaranteed mint royalties with PaymentSplitter. * EIP-2981 compliant secondary sale royalty information. * Whitelist functionality. Caps whitelist users and invalidates whitelist users after mint. * Deployable to ETH, AVAX, BNB, MATIC, FANTOM chains. * */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/utils/cryptography/MerkleProof.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "./token/ERC721/ERC721A.sol"; import "./access/Ownable.sol"; import "./eip/2981/ERC2981Collection.sol"; import "./modules/PaymentSplitter.sol"; contract CandyCreatorV1A is ERC721A, ERC2981Collection, ReentrancyGuard, PaymentSplitter, Ownable { // @notice basic state variables string private base; bool private mintingActive; bool private lockedPayees; uint256 private maxPublicMints; uint256 private mintPrice; uint256 private mintSize; uint256 private revealTime; // @notice Whitelist functionality bool private whitelistActive; bytes32 public whitelistMerkleRoot; uint256 private maxWhitelistMints; mapping(address => bool) public whitelistClaimed; event UpdatedRevealTimestamp(uint256 _old, uint256 _new); event UpdatedMintPrice(uint256 _old, uint256 _new); event UpdatedMintSize(uint _old, uint _new); event UpdatedMaxWhitelistMints(uint _old, uint _new); event UpdatedMaxPublicMints(uint _old, uint _new); event UpdatedMintStatus(bool _old, bool _new); event UpdatedRoyalties(address newRoyaltyAddress, uint256 newPercentage); event UpdatedWhitelistStatus(bool _old, bool _new); event UpdatedPresaleEnd(uint _old, uint _new); event PayeesLocked(bool _status); event UpdatedWhitelist(bytes32 _old, bytes32 _new); // @notice Contract constructor requires as much information // about the contract as possible to avoid unnecessary function calls // on the contract post-deployment. constructor(string memory name, string memory symbol, string memory _placeholderURI, uint256 _mintPrice, uint256 _mintSize, address _candyWallet, bool _multi, address [] memory splitAddresses, uint256 [] memory splitShares) ERC721A(name, symbol, _placeholderURI) { setMintPrice(_mintPrice); setMintSize(_mintSize); addPayee(_candyWallet, 500); if(!_multi) { addPayee(_msgSender(), 9500); lockPayees(); } else { for (uint i = 0; i < splitAddresses.length; i++) { addPayee(splitAddresses[i], splitShares[i]); } lockPayees(); } } /*** * ███╗ ███╗██╗███╗ ██╗████████╗ * ████╗ ████║██║████╗ ██║╚══██╔══╝ * ██╔████╔██║██║██╔██╗ ██║ ██║ * ██║╚██╔╝██║██║██║╚██╗██║ ██║ * ██║ ╚═╝ ██║██║██║ ╚████║ ██║ * ╚═╝ ╚═╝╚═╝╚═╝ ╚═══╝ ╚═╝ */ // @notice this is the mint function, mint Fees in ERC20, // requires amount * mintPrice to be sent by caller // nonReentrant() function. More comments within code. // @param uint amount - number of tokens minted function whitelistMint(bytes32[] calldata merkleProof, uint256 amount) external payable nonReentrant() { // @notice using Checks-Effects-Interactions require(mintingActive, "Minting not enabled"); require(whitelistActive, "Whitelist not required, use publicMint()"); require(_msgValue() == mintPrice * amount, "Wrong amount of Native Token"); require(_totalSupply() + amount <= mintSize, "Can not mint that many"); require(amount <= maxWhitelistMints, "Exceeds maximum whitelist mints"); require( MerkleProof.verify( merkleProof, whitelistMerkleRoot, keccak256(abi.encodePacked(_msgSender())) ), "Address not whitelisted" ); require(!whitelistClaimed[_msgSender()], "You have already claimed your tokens"); _safeMint(_msgSender(), amount); whitelistClaimed[_msgSender()] = true; } // @notice this is the mint function, mint Fees in ERC20, // requires amount * mintPrice to be sent by caller // nonReentrant() function. More comments within code. // @param uint amount - number of tokens minted function publicMint(uint256 amount) external payable nonReentrant() { require(!whitelistActive, "publicMint() disabled because whitelist is enabled"); require(mintingActive, "Minting not enabled"); require(_msgValue() == mintPrice * amount, "Wrong amount of Native Token"); require(_totalSupply() + amount <= mintSize, "Can not mint that many"); require(amount <= maxPublicMints, "Exceeds public transaction limit"); _safeMint(_msgSender(), amount); } /*** * ██████╗░░█████╗░██╗░░░██╗███╗░░░███╗███████╗███╗░░██╗████████╗ * ██╔══██╗██╔══██╗╚██╗░██╔╝████╗░████║██╔════╝████╗░██║╚══██╔══╝ * ██████╔╝███████║░╚████╔╝░██╔████╔██║█████╗░░██╔██╗██║░░░██║░░░ * ██╔═══╝░██╔══██║░░╚██╔╝░░██║╚██╔╝██║██╔══╝░░██║╚████║░░░██║░░░ * ██║░░░░░██║░░██║░░░██║░░░██║░╚═╝░██║███████╗██║░╚███║░░░██║░░░ * ╚═╝░░░░░╚═╝░░╚═╝░░░╚═╝░░░╚═╝░░░░░╚═╝╚══════╝╚═╝░░╚══╝░░░╚═╝░░░ * This section pertains to mint fees, royalties, and fund release. */ // Function to receive ether, msg.data must be empty receive() external payable { // From PaymentSplitter.sol emit PaymentReceived(_msgSender(), _msgValue()); } // Function to receive ether, msg.data is not empty fallback() external payable { // From PaymentSplitter.sol emit PaymentReceived(_msgSender(), _msgValue()); } // @notice will release funds from the contract to the addresses // owed funds as passed to constructor function release() external onlyOwner { _release(); } // @notice this will use internal functions to set EIP 2981 // found in IERC2981.sol and used by ERC2981Collections.sol // @param address _royaltyAddress - Address for all royalties to go to // @param uint256 _percentage - Precentage in whole number of comission // of secondary sales function setRoyaltyInfo(address _royaltyAddress, uint256 _percentage) public onlyOwner { _setRoyalties(_royaltyAddress, _percentage); emit UpdatedRoyalties(_royaltyAddress, _percentage); } // @notice this will set the fees required to mint using // publicMint(), must enter in wei. So 1 ETH = 10**18. // @param uint256 _newFee - fee you set, if ETH 10**18, if // an ERC20 use token's decimals in calculation function setMintPrice(uint256 _newFee) public onlyOwner { uint256 oldFee = mintPrice; mintPrice = _newFee; emit UpdatedMintPrice(oldFee, mintPrice); } // @notice will add an address to PaymentSplitter by owner role // @param address newAddy - address to recieve payments // @param uint newShares - number of shares they recieve function addPayee(address newAddy, uint newShares) private { require(!lockedPayees, "Can not set, payees locked"); _addPayee(newAddy, newShares); } // @notice Will lock the ability to add further payees on PaymentSplitter.sol function lockPayees() private { require(!lockedPayees, "Can not set, payees locked"); lockedPayees = true; emit PayeesLocked(lockedPayees); } /*** * * ░█████╗░██████╗░███╗░░░███╗██╗███╗░░██╗ * ██╔══██╗██╔══██╗████╗░████║██║████╗░██║ * ███████║██║░░██║██╔████╔██║██║██╔██╗██║ * ██╔══██║██║░░██║██║╚██╔╝██║██║██║╚████║ * ██║░░██║██████╔╝██║░╚═╝░██║██║██║░╚███║ * ╚═╝░░╚═╝╚═════╝░╚═╝░░░░░╚═╝╚═╝╚═╝░░╚══╝ * This section pertains to to basic contract administration tasks. */ // @notice this will enable publicMint() function enableMinting() external onlyOwner { bool old = mintingActive; mintingActive = true; emit UpdatedMintStatus(old, mintingActive); } // @notice this will disable publicMint() function disableMinting() external onlyOwner { bool old = mintingActive; mintingActive = false; emit UpdatedMintStatus(old, mintingActive); } // @notice this will enable whitelist or "if" in publicMint() function enableWhitelist() external onlyOwner { bool old = whitelistActive; whitelistActive = true; emit UpdatedWhitelistStatus(old, whitelistActive); } // @notice this will disable whitelist or "else" in publicMint() function disableWhitelist() external onlyOwner { bool old = whitelistActive; whitelistActive = false; emit UpdatedWhitelistStatus(old, whitelistActive); } // @notice this will set a new Merkle root used to verify whitelist membership // together with a proof submitted to the mint function // @param bytes32 _merkleRoot - generated merkleRoot hash function setWhitelistMerkleRoot(bytes32 _merkleRoot) public onlyOwner { bytes32 old = whitelistMerkleRoot; whitelistMerkleRoot = _merkleRoot; emit UpdatedWhitelist(old, whitelistMerkleRoot); } // @notice this will set the maximum number of tokens a whitelisted user can mint. // @param uint256 _amount - max amount of tokens function setMaxWhitelistMints(uint256 _amount) public onlyOwner { uint256 oldAmount = maxWhitelistMints; maxWhitelistMints = _amount; emit UpdatedMaxWhitelistMints(oldAmount, maxWhitelistMints); } // @notice this will set the maximum number of tokens a single address can mint at a time // during the public mint period. Keep in mind that user will be able to transfer their tokens // to a different address, and continue minting this amount of tokens on each transaction. // If you wish to prevent this, use the whitelist. // @param uint256 _amount - max amount of tokens function setMaxPublicMints(uint256 _amount) public onlyOwner { uint256 oldAmount = maxPublicMints; maxPublicMints = _amount; emit UpdatedMaxPublicMints(oldAmount, maxWhitelistMints); } // @notice this updates the base URI for the token metadata // it does not emit an event so that it can be set invisibly to purchasers // and avoid token sniping // @param string _ - max amount of tokens function setBaseURI(string memory baseURI) public onlyOwner { base = baseURI; } // @notice will set mint size by owner role // @param uint256 _amount - set number to mint function setMintSize(uint256 _amount) public onlyOwner { uint256 old = mintSize; mintSize = _amount; emit UpdatedMintSize(old, mintSize); } // @notice this will set the reveal timestamp // This is more for your API and not on-chain... // @param uint256 _time - uinx time stamp for reveal (use with API's only) function setRevealTimestamp(uint256 _timestamp) public onlyOwner { uint256 old = revealTime; revealTime = _timestamp; emit UpdatedRevealTimestamp(old, revealTime); } /*** * ██████╗░██╗░░░██╗██████╗░██╗░░░░░██╗░█████╗░  ██╗░░░██╗██╗███████╗░██╗░░░░░░░██╗░██████╗ * ██╔══██╗██║░░░██║██╔══██╗██║░░░░░██║██╔══██╗  ██║░░░██║██║██╔════╝░██║░░██╗░░██║██╔════╝ * ██████╔╝██║░░░██║██████╦╝██║░░░░░██║██║░░╚═╝  ╚██╗░██╔╝██║█████╗░░░╚██╗████╗██╔╝╚█████╗░ * ██╔═══╝░██║░░░██║██╔══██╗██║░░░░░██║██║░░██╗  ░╚████╔╝░██║██╔══╝░░░░████╔═████║░░╚═══██╗ * ██║░░░░░╚██████╔╝██████╦╝███████╗██║╚█████╔╝  ░░╚██╔╝░░██║███████╗░░╚██╔╝░╚██╔╝░██████╔╝ * ╚═╝░░░░░░╚═════╝░╚═════╝░╚══════╝╚═╝░╚════╝░  ░░░╚═╝░░░╚═╝╚══════╝░░░╚═╝░░░╚═╝░░╚═════╝░ */ // @notice will return whether minting is enabled function mintStatus() external view returns (bool) { return mintingActive; } // @notice will return whitelist status of Minter function whitelistStatus() external view returns (bool) { return whitelistActive; } // @notice will return the reveal timestamp for use by off-chain API to conditionally render // mint button function revealTimestamp() external view returns (uint) { return revealTime; } // @notice will return minting fees function mintingFee() external view returns (uint256) { return mintPrice; } // @notice will return whitelist status of Minter function whitelistMaxMints() external view returns (uint256) { return maxWhitelistMints; } // @notice will return maximum tokens that are allowed to be minted during a single transaction // during the whitelist period function publicMaxMints() external view returns (uint256) { return maxPublicMints; } // @notice will return current token count function totalSupply() external view returns (uint256) { return _totalSupply(); } // @notice this is a public getter for ETH balance on contract function getBalance() external view returns (uint) { return address(this).balance; } // @notice will return the planned size of the collection function collectionSize() external view returns (uint256) { return mintSize; } /*** * ░█████╗░██╗░░░██╗███████╗██████╗░██████╗░██╗██████╗░███████╗ * ██╔══██╗██║░░░██║██╔════╝██╔══██╗██╔══██╗██║██╔══██╗██╔════╝ * ██║░░██║╚██╗░██╔╝█████╗░░██████╔╝██████╔╝██║██║░░██║█████╗░░ * ██║░░██║░╚████╔╝░██╔══╝░░██╔══██╗██╔══██╗██║██║░░██║██╔══╝░░ * ╚█████╔╝░░╚██╔╝░░███████╗██║░░██║██║░░██║██║██████╔╝███████╗ * ░╚════╝░░░░╚═╝░░░╚══════╝╚═╝░░╚═╝╚═╝░░╚═╝╚═╝╚═════╝░╚══════╝ */ // @notice solidity required override for _baseURI(), if you wish to // be able to set from API -> IPFS or vice versa using setBaseURI(string) function _baseURI() internal view override returns (string memory) { return base; } // @notice solidity required override for supportsInterface(bytes4) // @param bytes4 interfaceId - bytes4 id per interface or contract // calculated by ERC165 standards automatically function supportsInterface(bytes4 interfaceId) public view override(ERC721A, IERC165) returns (bool) { return ( interfaceId == type(ERC2981Collection).interfaceId || interfaceId == type(ReentrancyGuard).interfaceId || interfaceId == type(PaymentSplitter).interfaceId || interfaceId == type(Ownable).interfaceId || super.supportsInterface(interfaceId) ); } } /*** * ██████╗ ██╗ ██╗███╗ ██╗ █████╗ ██████╗ ██╗ ███████╗ * ██╔═══██╗██║ ██║████╗ ██║██╔══██╗██╔══██╗██║ ██╔════╝ * ██║ ██║██║ █╗ ██║██╔██╗ ██║███████║██████╔╝██║ █████╗ * ██║ ██║██║███╗██║██║╚██╗██║██╔══██║██╔══██╗██║ ██╔══╝ * ╚██████╔╝╚███╔███╔╝██║ ╚████║██║ ██║██████╔╝███████╗███████╗ * ╚═════╝ ╚══╝╚══╝ ╚═╝ ╚═══╝╚═╝ ╚═╝╚═════╝ ╚══════╝╚══════╝ * Re-write of @openzeppelin/contracts/access/Ownable.sol * Rewritten by Alex Sikand, Chief Technology Officer @ Candy Labs * * Upgraded to push/pull and decline compared to original contract */ // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 // Rewritten for onlyOwner modifier pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (a 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 {transferOwner}. * * 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; address private _newOwner; event OwnerTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial Owner. */ constructor() { _transferOwner(_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(), "Owner: 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 renounceOwner() public virtual onlyOwner { _transferOwner(address(0)); } /** * @dev Transfers Owner of the contract to a new account (`newOwner`). * Can only be called by the current Owner. Now push/pull. */ function transferOwner(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Owner: new Owner is the zero address"); _newOwner = newOwner; } /** * @dev Accepts Transfer Owner of the contract to a new account (`newOwner`). * Can only be called by the new Owner. Pull Accepted. */ function acceptOwner() public virtual { require(_newOwner == _msgSender(), "New Owner: new Owner is the only caller"); _transferOwner(_newOwner); } /** * @dev Declines Transfer Owner of the contract to a new account (`newOwner`). * Can only be called by the new Owner. Pull Declined. */ function declineOwner() public virtual { require(_newOwner == _msgSender(), "New Owner: new Owner is the only caller"); _newOwner = address(0); } /** * @dev Transfers Owner of the contract to a new account (`newOwner`). * Can only be called by the current Owner. Now push only. Orginal V1 style */ function pushOwner(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Owner: new Owner is the zero address"); _transferOwner(newOwner); } /** * @dev Transfers Owner of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwner(address newOwner) internal virtual { address oldOwner = _Owner; _Owner = newOwner; emit OwnerTransferred(oldOwner, newOwner); } } /*** * ███████╗██████╗ ██████╗██████╗ █████╗ █████╗ ██╗ * ██╔════╝██╔══██╗██╔════╝╚════██╗██╔══██╗██╔══██╗███║ * █████╗ ██████╔╝██║ █████╔╝╚██████║╚█████╔╝╚██║ * ██╔══╝ ██╔══██╗██║ ██╔═══╝ ╚═══██║██╔══██╗ ██║ * ███████╗██║ ██║╚██████╗███████╗ █████╔╝╚█████╔╝ ██║ * ╚══════╝╚═╝ ╚═╝ ╚═════╝╚══════╝ ╚════╝ ╚════╝ ╚═╝ * * ██████╗ ██████╗ ██╗ ██╗ ███████╗ ██████╗████████╗██╗ ██████╗ ███╗ ██╗ * ██╔════╝██╔═══██╗██║ ██║ ██╔════╝██╔════╝╚══██╔══╝██║██╔═══██╗████╗ ██║ * ██║ ██║ ██║██║ ██║ █████╗ ██║ ██║ ██║██║ ██║██╔██╗ ██║ * ██║ ██║ ██║██║ ██║ ██╔══╝ ██║ ██║ ██║██║ ██║██║╚██╗██║ * ╚██████╗╚██████╔╝███████╗███████╗███████╗╚██████╗ ██║ ██║╚██████╔╝██║ ╚████║ * ╚═════╝ ╚═════╝ ╚══════╝╚══════╝╚══════╝ ╚═════╝ ╚═╝ ╚═╝ ╚═════╝ ╚═╝ ╚═══╝ * * Written by Alex Sikand, Chief Technology Officer @ Candy Labs. * * Designed to allow setting a global royalty address along with specified basis points. */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "./IERC2981.sol"; abstract contract ERC2981Collection is IERC2981 { address private royaltyAddress; uint256 private royaltyPercent; function _setRoyalties(address _receiver, uint256 _percentage) internal { royaltyAddress = _receiver; royaltyPercent = _percentage; } // Override for royaltyInfo(uint256, uint256) function royaltyInfo( uint256 _tokenId, uint256 _salePrice ) external view override(IERC2981) returns ( address receiver, uint256 royaltyAmount ) { receiver = royaltyAddress; // This sets percentages by price * percentage / 100 royaltyAmount = _salePrice * royaltyPercent / 100; } } /*** * ███████╗██╗██████╗ ██████╗ █████╗ █████╗ ██╗ * ██╔════╝██║██╔══██╗ ╚════██╗██╔══██╗██╔══██╗███║ * █████╗ ██║██████╔╝█████╗ █████╔╝╚██████║╚█████╔╝╚██║ * ██╔══╝ ██║██╔═══╝ ╚════╝██╔═══╝ ╚═══██║██╔══██╗ ██║ * ███████╗██║██║ ███████╗ █████╔╝╚█████╔╝ ██║ * ╚══════╝╚═╝╚═╝ ╚══════╝ ╚════╝ ╚════╝ ╚═╝ * Zach Burks, James Morgan, Blaine Malone, James Seibel, * "EIP-2981: NFT Royalty Standard," * Ethereum Improvement Proposals, no. 2981, September 2020. [Online serial]. * Available: https://eips.ethereum.org/EIPS/eip-2981. * */ // SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; /// /// @dev Interface for the NFT Royalty Standard /// interface IERC2981 is IERC165 { // @notice Called with the sale price to determine how much royalty // is owed and to whom. // @param _tokenId - the NFT asset queried for royalty information // @param _salePrice - the sale price of the NFT asset specified by _tokenId // @return receiver - address of who should be sent the royalty payment // @return royaltyAmount - the royalty payment amount for _salePrice function royaltyInfo(uint256 _tokenId, uint256 _salePrice) external view returns (address receiver, uint256 royaltyAmount); } /*** * ██████╗ █████╗ ██╗ ██╗███╗ ███╗███████╗███╗ ██╗████████╗ * ██╔══██╗██╔══██╗╚██╗ ██╔╝████╗ ████║██╔════╝████╗ ██║╚══██╔══╝ * ██████╔╝███████║ ╚████╔╝ ██╔████╔██║█████╗ ██╔██╗ ██║ ██║ * ██╔═══╝ ██╔══██║ ╚██╔╝ ██║╚██╔╝██║██╔══╝ ██║╚██╗██║ ██║ * ██║ ██║ ██║ ██║ ██║ ╚═╝ ██║███████╗██║ ╚████║ ██║ * ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚═╝ ╚═══╝ ╚═╝ * * ███████╗██████╗ ██╗ ██╗████████╗████████╗███████╗██████╗ * ██╔════╝██╔══██╗██║ ██║╚══██╔══╝╚══██╔══╝██╔════╝██╔══██╗ * ███████╗██████╔╝██║ ██║ ██║ ██║ █████╗ ██████╔╝ * ╚════██║██╔═══╝ ██║ ██║ ██║ ██║ ██╔══╝ ██╔══██╗ * ███████║██║ ███████╗██║ ██║ ██║ ███████╗██║ ██║ * ╚══════╝╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ * Re-write of @openzeppelin/contracts/finance/PaymentSplitter.sol * Rewritten by Alex Sikand, Chief Technology Officer @ Candy Labs * * Edits the release functionality to force release to all addresses added * as payees. */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/utils/Address.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "../utils/Context.sol"; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. */ abstract contract PaymentSplitter is Context { using Counters for Counters.Counter; Counters.Counter private _numPayees; event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. * * receive() external payable virtual { * emit PaymentReceived(_msgSender(), msg.value); * } * * // Fallback function is called when msg.data is not empty * // Added to PaymentSplitter.sol * fallback() external payable { * emit PaymentReceived(_msgSender(), msg.value); * } * * receive() and fallback() to be handled at final contract */ /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Releases contract balance to the addresses that are owed funds. */ function _release() internal { require(address(this).balance > 0, "Contract must have a balance to release funds"); for (uint i = 0; i < _numPayees.current(); i++) { address account = payee(i); uint256 totalReceived = address(this).balance + _totalReleased; uint256 payment = (totalReceived * _shares[account]) / _totalShares - _released[account]; _released[account] = _released[account] + payment; _totalReleased = _totalReleased + payment; Address.sendValue(payable(account), payment); emit PaymentReleased(account, payment); } } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares to assign the payee. */ function _addPayee(address account, uint256 shares_) internal { require(account != address(0), "Can't add shares to the zero address"); require(shares_ > 0, "Shares must be greater than zero"); require(_shares[account] == 0, "Address has already been assigned shares"); _numPayees.increment(); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } } /*** * ███████╗██████╗░░█████╗░███████╗██████╗░░░███╗░░░█████╗░ * ██╔════╝██╔══██╗██╔══██╗╚════██║╚════██╗░████║░░██╔══██╗ * █████╗░░██████╔╝██║░░╚═╝░░░░██╔╝░░███╔═╝██╔██║░░███████║ * ██╔══╝░░██╔══██╗██║░░██╗░░░██╔╝░██╔══╝░░╚═╝██║░░██╔══██║ * ███████╗██║░░██║╚█████╔╝░░██╔╝░░███████╗███████╗██║░░██║ * ╚══════╝╚═╝░░╚═╝░╚════╝░░░╚═╝░░░╚══════╝╚══════╝╚═╝░░╚═╝ * Re-write of Chiru Labs ERC721A Contract * Rewritten by Alex Sikand, Chief Technology Officer @ Candy Labs * * ERC721 implementation with batch minting API. * Originally authored by Chiru Labs, updated by Candy Labs. * Removes linear time functions tokenOfOwnerByIndex and tokenByIndex and avoids * overriding ERC721Enumerable */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.4; 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 "../../utils/Context.sol"; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintedQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerIndexOutOfBounds(); error OwnerQueryForNonexistentToken(); error TokenIndexOutOfBounds(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error UnableDetermineTokenOwner(); error URIQueryForNonexistentToken(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata and Enumerable extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at 1 (e.g. 1, 2, 3, 4..). * * Does not support burning tokens to address(0).. * * Assumes that an owner cannot have more than the 2**128 - 1 (max value of uint128) of supply */ contract ERC721A is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; struct TokenOwnership { address addr; uint64 startTimestamp; } struct AddressData { uint128 balance; uint128 numberMinted; } uint256 internal _currentIndex = 1; // Token name string private _name; // Token symbol string private _symbol; // Placeholder JSON URI string private _placeholderURI; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // 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; constructor(string memory name_, string memory symbol_, string memory placeholderURI_) { _name = name_; _symbol = symbol_; _placeholderURI = placeholderURI_; } /** * @dev Returns the total token supply */ function _totalSupply() internal view returns (uint256) { return _currentIndex - 1; } /** * @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 override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } function _numberMinted(address owner) internal view returns (uint256) { if (owner == address(0)) revert MintedQueryForZeroAddress(); return uint256(_addressData[owner].numberMinted); } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { if (!_exists(tokenId)) revert OwnerQueryForNonexistentToken(); unchecked { for (uint256 curr = tokenId;; curr--) { TokenOwnership memory ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return ownershipOf(tokenId).addr; } /** * @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) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, "/", tokenId.toString(), ".json")) : _placeholderURI; } /** * @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 override { address owner = ERC721A.ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) revert ApprovalCallerNotOwnerNorApproved(); _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public override { if (operator == _msgSender()) revert ApproveToCaller(); _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 { _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 override { _transfer(from, to, tokenId); if (!_checkOnERC721Received(from, to, tokenId, _data)) revert TransferToNonERC721ReceiverImplementer(); } /** * @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`), */ function _exists(uint256 tokenId) internal view returns (bool) { return tokenId < _currentIndex; } function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ''); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { _mint(to, quantity, _data, true); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint( address to, uint256 quantity, bytes memory _data, bool safe ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 3.4e38 (2**128) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.56e77 (2**256) - 1 unchecked { _addressData[to].balance += uint128(quantity); _addressData[to].numberMinted += uint128(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; for (uint256 i; i < quantity; i++) { emit Transfer(address(0), to, updatedIndex); if (safe && !_checkOnERC721Received(address(0), to, updatedIndex, _data)) { revert TransferToNonERC721ReceiverImplementer(); } updatedIndex++; } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * 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 ) private { TokenOwnership memory prevOwnership = ownershipOf(tokenId); bool isApprovedOrOwner = (_msgSender() == prevOwnership.addr || isApprovedForAll(prevOwnership.addr, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, prevOwnership.addr); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; _ownerships[tokenId].addr = to; _ownerships[tokenId].startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; if (_ownerships[nextTokenId].addr == address(0)) { if (_exists(nextTokenId)) { _ownerships[nextTokenId].addr = prevOwnership.addr; _ownerships[nextTokenId].startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, 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 TransferToNonERC721ReceiverImplementer(); else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * 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`. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } /*** * ██████╗ ██████╗ ███╗ ██╗████████╗███████╗██╗ ██╗████████╗ * ██╔════╝██╔═══██╗████╗ ██║╚══██╔══╝██╔════╝╚██╗██╔╝╚══██╔══╝ * ██║ ██║ ██║██╔██╗ ██║ ██║ █████╗ ╚███╔╝ ██║ * ██║ ██║ ██║██║╚██╗██║ ██║ ██╔══╝ ██╔██╗ ██║ * ╚██████╗╚██████╔╝██║ ╚████║ ██║ ███████╗██╔╝ ██╗ ██║ * ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝ ╚═╝ ╚══════╝╚═╝ ╚═╝ ╚═╝ * Re-write of @openzeppelin/contracts/utils/Context.sol * Rewritten by Alex Sikand, Chief Technology Officer @ Candy Labs * * Upgraded stock contract with _msgValue() and _txOrigin() */ // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) // 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; } function _msgValue() internal view virtual returns (uint) { return msg.value; } function _txOrigin() internal view virtual returns (address) { return tx.origin; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) 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 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; } } // 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 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/Counters.sol) 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 // 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/cryptography/MerkleProof.sol) 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) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merklee tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { 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)); } } return computedHash; } } // 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); }
@notice this will set a new Merkle root used to verify whitelist membership together with a proof submitted to the mint function @param bytes32 _merkleRoot - generated merkleRoot hash
function setWhitelistMerkleRoot(bytes32 _merkleRoot) public onlyOwner { bytes32 old = whitelistMerkleRoot; whitelistMerkleRoot = _merkleRoot; emit UpdatedWhitelist(old, whitelistMerkleRoot); }
14,395,486
[ 1, 2211, 903, 444, 279, 394, 31827, 1365, 1399, 358, 3929, 10734, 12459, 9475, 598, 279, 14601, 9638, 358, 326, 312, 474, 445, 225, 1731, 1578, 389, 6592, 15609, 2375, 300, 4374, 30235, 2375, 1651, 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, 225, 445, 444, 18927, 8478, 15609, 2375, 12, 3890, 1578, 389, 6592, 15609, 2375, 13, 1071, 1338, 5541, 288, 203, 3639, 1731, 1578, 1592, 273, 10734, 8478, 15609, 2375, 31, 203, 3639, 10734, 8478, 15609, 2375, 273, 389, 6592, 15609, 2375, 31, 203, 3639, 3626, 19301, 18927, 12, 1673, 16, 10734, 8478, 15609, 2375, 1769, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xe136BA8379698D12265b2ca327C7B6A345CAC21a/sources/contracts/1_Storage.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; function fulfillRandomness(bytes32 requestId, uint256 randomness) internal virtual; function requestRandomness(bytes32 _keyHash, uint256 _fee, uint256 _seed) internal returns (bytes32 requestId) { LINK.transferAndCall(vrfCoordinator, _fee, abi.encode(_keyHash, _seed)); uint256 vRFSeed = makeVRFInputSeed(_keyHash, _seed, address(this), nonces[_keyHash]); nonces[_keyHash] = nonces[_keyHash].add(1); return makeRequestId(_keyHash, vRFSeed); } LinkTokenInterface immutable internal LINK; address immutable private vrfCoordinator; mapping(bytes32 /* keyHash */ => uint256 /* nonce */) private nonces; constructor(address _vrfCoordinator, address _link) { vrfCoordinator = _vrfCoordinator; LINK = LinkTokenInterface(_link); } function rawFulfillRandomness(bytes32 requestId, uint256 randomness) external { require(msg.sender == vrfCoordinator, "Only VRFCoordinator can fulfill"); fulfillRandomness(requestId, randomness); } }
5,553,293
[ 1, 1358, 364, 20092, 1450, 776, 12918, 2744, 4496, 282, 30817, 225, 2526, 75, 1385, 326, 8072, 28544, 261, 902, 18423, 2863, 1719, 13, 14805, 358, 5615, 2744, 4496, 225, 358, 776, 6070, 326, 20130, 316, 4123, 279, 4031, 716, 776, 6070, 848, 506, 3071, 3904, 1807, 486, 225, 10480, 18423, 876, 731, 358, 1597, 305, 366, 381, 2890, 18, 2526, 75, 1385, 8121, 776, 6070, 279, 1071, 498, 225, 358, 1492, 3904, 21739, 326, 4001, 498, 18, 8315, 813, 776, 6070, 8121, 279, 5009, 358, 225, 2526, 75, 1385, 16, 3904, 14758, 1473, 279, 460, 1492, 353, 8470, 14416, 225, 25112, 1230, 628, 326, 5009, 471, 326, 4001, 498, 18, 225, 2526, 75, 1385, 8121, 279, 14601, 635, 1492, 776, 6070, 848, 3929, 716, 326, 876, 1703, 225, 8783, 8470, 3647, 2526, 75, 1385, 24551, 518, 358, 22336, 16, 1496, 2887, 716, 14601, 16, 225, 326, 876, 353, 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, 17801, 6835, 776, 12918, 5869, 2171, 353, 776, 12918, 691, 734, 2171, 288, 203, 203, 225, 1450, 14060, 10477, 3893, 1232, 364, 2254, 5034, 31, 203, 203, 225, 445, 22290, 8529, 4496, 12, 3890, 1578, 14459, 16, 2254, 5034, 2744, 4496, 13, 203, 565, 2713, 5024, 31, 203, 203, 225, 445, 590, 8529, 4496, 12, 3890, 1578, 389, 856, 2310, 16, 2254, 5034, 389, 21386, 16, 2254, 5034, 389, 12407, 13, 203, 565, 2713, 1135, 261, 3890, 1578, 14459, 13, 203, 203, 225, 288, 203, 565, 22926, 18, 13866, 1876, 1477, 12, 16825, 25307, 16, 389, 21386, 16, 24126, 18, 3015, 24899, 856, 2310, 16, 389, 12407, 10019, 203, 565, 2254, 5034, 331, 12918, 12702, 225, 273, 1221, 10986, 42, 1210, 12702, 24899, 856, 2310, 16, 389, 12407, 16, 1758, 12, 2211, 3631, 1661, 764, 63, 67, 856, 2310, 19226, 203, 565, 1661, 764, 63, 67, 856, 2310, 65, 273, 1661, 764, 63, 67, 856, 2310, 8009, 1289, 12, 21, 1769, 203, 565, 327, 1221, 15493, 24899, 856, 2310, 16, 331, 12918, 12702, 1769, 203, 225, 289, 203, 203, 225, 4048, 1345, 1358, 11732, 2713, 22926, 31, 203, 225, 1758, 11732, 3238, 20466, 25307, 31, 203, 203, 203, 225, 2874, 12, 3890, 1578, 1748, 498, 2310, 1195, 516, 2254, 5034, 1748, 7448, 1195, 13, 3238, 1661, 764, 31, 203, 225, 3885, 12, 2867, 389, 16825, 25307, 16, 1758, 389, 1232, 13, 225, 288, 203, 565, 20466, 25307, 273, 389, 16825, 25307, 31, 203, 565, 22926, 273, 4048, 1345, 1358, 24899, 1232, 1769, 203, 225, 2 ]
pragma solidity ^0.5.17; pragma experimental ABIEncoderV2; 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 IUniswapV2Pair { 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; event Mint(address indexed sender, uint amount0, uint amount1); event Burn(address indexed sender, uint amount0, uint amount1, address indexed to); event Swap( address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event Sync(uint112 reserve0, uint112 reserve1); function MINIMUM_LIQUIDITY() external pure returns (uint); function factory() external view returns (address); function token0() external view returns (address); function token1() external view returns (address); function getReserves() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); function price0CumulativeLast() external view returns (uint); function price1CumulativeLast() external view returns (uint); function kLast() external view returns (uint); function mint(address to) external returns (uint liquidity); function burn(address to) external returns (uint amount0, uint amount1); function swap(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; function skim(address to) external; function sync() external; function initialize(address, address) external; } // computes square roots using the babylonian method // https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Babylonian_method library Babylonian { function sqrt(uint y) internal pure returns (uint z) { if (y > 3) { z = y; uint x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant RESOLUTION = 112; uint private constant Q112 = uint(1) << RESOLUTION; uint private constant Q224 = Q112 << RESOLUTION; // encode a uint112 as a UQ112x112 function encode(uint112 x) internal pure returns (uq112x112 memory) { return uq112x112(uint224(x) << RESOLUTION); } // encodes a uint144 as a UQ144x112 function encode144(uint144 x) internal pure returns (uq144x112 memory) { return uq144x112(uint256(x) << RESOLUTION); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function div(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function mul(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function fraction(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << RESOLUTION) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function decode(uq112x112 memory self) internal pure returns (uint112) { return uint112(self._x >> RESOLUTION); } // decode a UQ144x112 into a uint144 by truncating after the radix point function decode144(uq144x112 memory self) internal pure returns (uint144) { return uint144(self._x >> RESOLUTION); } // take the reciprocal of a UQ112x112 function reciprocal(uq112x112 memory self) internal pure returns (uq112x112 memory) { require(self._x != 0, 'FixedPoint: ZERO_RECIPROCAL'); return uq112x112(uint224(Q224 / self._x)); } // square root of a UQ112x112 function sqrt(uq112x112 memory self) internal pure returns (uq112x112 memory) { return uq112x112(uint224(Babylonian.sqrt(uint256(self._x)) << 56)); } } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function currentBlockTimestamp() internal view returns (uint32) { return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function currentCumulativePrices(address pair) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = currentBlockTimestamp(); price0Cumulative = IUniswapV2Pair(pair).price0CumulativeLast(); price1Cumulative = IUniswapV2Pair(pair).price1CumulativeLast(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).getReserves(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.fraction(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.fraction(reserve0, reserve1)._x) * timeElapsed; } } } /** * @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. * * _Available since v2.4.0._ */ 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. * * _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; } /** * @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. * * _Available since v2.4.0._ */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function sortTokens(address tokenA, address tokenB) internal pure returns (address token0, address token1) { require(tokenA != tokenB, 'UniswapV2Library: IDENTICAL_ADDRESSES'); (token0, token1) = tokenA < tokenB ? (tokenA, tokenB) : (tokenB, tokenA); require(token0 != address(0), 'UniswapV2Library: ZERO_ADDRESS'); } // calculates the CREATE2 address for a pair without making any external calls function pairFor(address factory, address tokenA, address tokenB) internal pure returns (address pair) { (address token0, address token1) = sortTokens(tokenA, tokenB); pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // fetches and sorts the reserves for a pair function getReserves(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { (address token0,) = sortTokens(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(pairFor(factory, tokenA, tokenB)).getReserves(); (reserveA, reserveB) = tokenA == token0 ? (reserve0, reserve1) : (reserve1, reserve0); } // given some amount of an asset and pair reserves, returns an equivalent amount of the other asset function quote(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.mul(reserveB) / reserveA; } } /* Copyright 2019 dYdX Trading Inc. 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. */ /** * @title Require * @author dYdX * * Stringifies parameters to pretty-print revert messages. Costs more gas than regular require() */ library Require { // ============ Constants ============ uint256 constant ASCII_ZERO = 48; // '0' uint256 constant ASCII_RELATIVE_ZERO = 87; // 'a' - 10 uint256 constant ASCII_LOWER_EX = 120; // 'x' bytes2 constant COLON = 0x3a20; // ': ' bytes2 constant COMMA = 0x2c20; // ', ' bytes2 constant LPAREN = 0x203c; // ' <' byte constant RPAREN = 0x3e; // '>' uint256 constant FOUR_BIT_MASK = 0xf; // ============ Library Functions ============ function that( bool must, bytes32 file, bytes32 reason ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason) ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, uint256 payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, address payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), RPAREN ) ) ); } } function that( bool must, bytes32 file, bytes32 reason, bytes32 payloadA, uint256 payloadB, uint256 payloadC ) internal pure { if (!must) { revert( string( abi.encodePacked( stringifyTruncated(file), COLON, stringifyTruncated(reason), LPAREN, stringify(payloadA), COMMA, stringify(payloadB), COMMA, stringify(payloadC), RPAREN ) ) ); } } // ============ Private Functions ============ function stringifyTruncated( bytes32 input ) private pure returns (bytes memory) { // put the input bytes into the result bytes memory result = abi.encodePacked(input); // determine the length of the input by finding the location of the last non-zero byte for (uint256 i = 32; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // find the last non-zero byte in order to determine the length if (result[i] != 0) { uint256 length = i + 1; /* solium-disable-next-line security/no-inline-assembly */ assembly { mstore(result, length) // r.length = length; } return result; } } // all bytes are zero return new bytes(0); } function stringify( uint256 input ) private pure returns (bytes memory) { if (input == 0) { return "0"; } // get the final string length uint256 j = input; uint256 length; while (j != 0) { length++; j /= 10; } // allocate the string bytes memory bstr = new bytes(length); // populate the string starting with the least-significant character j = input; for (uint256 i = length; i > 0; ) { // reverse-for-loops with unsigned integer /* solium-disable-next-line security/no-modify-for-iter-var */ i--; // take last decimal digit bstr[i] = byte(uint8(ASCII_ZERO + (j % 10))); // remove the last decimal digit j /= 10; } return bstr; } function stringify( address input ) private pure returns (bytes memory) { uint256 z = uint256(input); // addresses are "0x" followed by 20 bytes of data which take up 2 characters each bytes memory result = new bytes(42); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 20; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[41 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[40 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function stringify( bytes32 input ) private pure returns (bytes memory) { uint256 z = uint256(input); // bytes32 are "0x" followed by 32 bytes of data which take up 2 characters each bytes memory result = new bytes(66); // populate the result with "0x" result[0] = byte(uint8(ASCII_ZERO)); result[1] = byte(uint8(ASCII_LOWER_EX)); // for each byte (starting from the lowest byte), populate the result with two characters for (uint256 i = 0; i < 32; i++) { // each byte takes two characters uint256 shift = i * 2; // populate the least-significant character result[65 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; // populate the most-significant character result[64 - shift] = char(z & FOUR_BIT_MASK); z = z >> 4; } return result; } function char( uint256 input ) private pure returns (byte) { // return ASCII digit (0-9) if (input < 10) { return byte(uint8(input + ASCII_ZERO)); } // return ASCII letter (a-f) return byte(uint8(input + ASCII_RELATIVE_ZERO)); } } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({ value: 0 }); } function one() internal pure returns (D256 memory) { return D256({ value: BASE }); } function from( uint256 a ) internal pure returns (D256 memory) { return D256({ value: a.mul(BASE) }); } function ratio( uint256 a, uint256 b ) internal pure returns (D256 memory) { return D256({ value: getPartial(a, BASE, b) }); } // ============ Self Functions ============ function add( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE)) }); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.mul(BASE), reason) }); } function mul( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.mul(b) }); } function div( D256 memory self, uint256 b ) internal pure returns (D256 memory) { return D256({ value: self.value.div(b) }); } function pow( D256 memory self, uint256 b ) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({ value: self.value }); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.add(b.value) }); } function sub( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value) }); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({ value: self.value.sub(b.value, reason) }); } function mul( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, b.value, BASE) }); } function div( D256 memory self, D256 memory b ) internal pure returns (D256 memory) { return D256({ value: getPartial(self.value, BASE, b.value) }); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo( D256 memory a, D256 memory b ) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract IOracle { function setup() public; function capture() public returns (Decimal.D256 memory, bool); function pair() external view returns (address); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract IUSDC { function isBlacklisted(address _account) external view returns (bool); } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ library Constants { /* Chain */ uint256 private constant CHAIN_ID = 1; // Mainnet /* Bootstrapping */ uint256 private constant BOOTSTRAPPING_PERIOD = 150; // 150 epochs uint256 private constant BOOTSTRAPPING_PRICE = 154e16; // 1.54 USDC (targeting 4.5% inflation) /* Oracle */ address private constant USDC = address(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); uint256 private constant ORACLE_RESERVE_MINIMUM = 1e10; // 10,000 USDC /* Bonding */ uint256 private constant INITIAL_STAKE_MULTIPLE = 1e6; // 100 DSD -> 100M DSDS /* Epoch */ struct EpochStrategy { uint256 offset; uint256 start; uint256 period; } uint256 private constant EPOCH_OFFSET = 0; uint256 private constant EPOCH_START = 1606348800; uint256 private constant EPOCH_PERIOD = 7200; /* Governance */ uint256 private constant GOVERNANCE_PERIOD = 36; uint256 private constant GOVERNANCE_QUORUM = 20e16; // 20% uint256 private constant GOVERNANCE_PROPOSAL_THRESHOLD = 5e15; // 0.5% uint256 private constant GOVERNANCE_SUPER_MAJORITY = 66e16; // 66% uint256 private constant GOVERNANCE_EMERGENCY_DELAY = 6; // 6 epochs /* DAO */ uint256 private constant ADVANCE_INCENTIVE_PREMIUM = 125e16; // pay out 25% more than tx fee value uint256 private constant DAO_EXIT_LOCKUP_EPOCHS = 36; // 36 epochs fluid /* Pool */ uint256 private constant POOL_EXIT_LOCKUP_EPOCHS = 12; // 12 epochs fluid /* Market */ uint256 private constant COUPON_EXPIRATION = 360; uint256 private constant DEBT_RATIO_CAP = 35e16; // 35% uint256 private constant INITIAL_COUPON_REDEMPTION_PENALTY = 50e16; // 50% uint256 private constant COUPON_REDEMPTION_PENALTY_DECAY = 3600; // 1 hour /* Regulator */ uint256 private constant SUPPLY_CHANGE_LIMIT = 2e16; // 2% uint256 private constant SUPPLY_CHANGE_DIVISOR = 25e18; // 25 > Max expansion at 1.5 uint256 private constant COUPON_SUPPLY_CHANGE_LIMIT = 3e16; // 3% uint256 private constant COUPON_SUPPLY_CHANGE_DIVISOR = 1666e16; // 16.66 > Max expansion at ~1.5 uint256 private constant NEGATIVE_SUPPLY_CHANGE_DIVISOR = 5e18; // 5 > Max negative expansion at 0.9 uint256 private constant ORACLE_POOL_RATIO = 40; // 40% uint256 private constant TREASURY_RATIO = 3; // 3% /* Deployed */ address private constant DAO_ADDRESS = address(0x6Bf977ED1A09214E6209F4EA5f525261f1A2690a); address private constant DOLLAR_ADDRESS = address(0xBD2F0Cd039E0BFcf88901C98c0bFAc5ab27566e3); address private constant PAIR_ADDRESS = address(0x26d8151e631608570F3c28bec769C3AfEE0d73a3); // SushiSwap pair address private constant TREASURY_ADDRESS = address(0xC7DA8087b8BA11f0892f1B0BFacfD44C116B303e); /** * Getters */ function getUsdcAddress() internal pure returns (address) { return USDC; } function getOracleReserveMinimum() internal pure returns (uint256) { return ORACLE_RESERVE_MINIMUM; } function getEpochStrategy() internal pure returns (EpochStrategy memory) { return EpochStrategy({ offset: EPOCH_OFFSET, start: EPOCH_START, period: EPOCH_PERIOD }); } function getInitialStakeMultiple() internal pure returns (uint256) { return INITIAL_STAKE_MULTIPLE; } function getBootstrappingPeriod() internal pure returns (uint256) { return BOOTSTRAPPING_PERIOD; } function getBootstrappingPrice() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: BOOTSTRAPPING_PRICE }); } function getGovernancePeriod() internal pure returns (uint256) { return GOVERNANCE_PERIOD; } function getGovernanceQuorum() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_QUORUM }); } function getGovernanceProposalThreshold() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_PROPOSAL_THRESHOLD }); } function getGovernanceSuperMajority() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: GOVERNANCE_SUPER_MAJORITY }); } function getGovernanceEmergencyDelay() internal pure returns (uint256) { return GOVERNANCE_EMERGENCY_DELAY; } function getAdvanceIncentivePremium() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: ADVANCE_INCENTIVE_PREMIUM }); } function getDAOExitLockupEpochs() internal pure returns (uint256) { return DAO_EXIT_LOCKUP_EPOCHS; } function getPoolExitLockupEpochs() internal pure returns (uint256) { return POOL_EXIT_LOCKUP_EPOCHS; } function getCouponExpiration() internal pure returns (uint256) { return COUPON_EXPIRATION; } function getDebtRatioCap() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: DEBT_RATIO_CAP }); } function getInitialCouponRedemptionPenalty() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: INITIAL_COUPON_REDEMPTION_PENALTY }); } function getCouponRedemptionPenaltyDecay() internal pure returns (uint256) { return COUPON_REDEMPTION_PENALTY_DECAY; } function getSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_LIMIT }); } function getSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: SUPPLY_CHANGE_DIVISOR }); } function getCouponSupplyChangeLimit() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_LIMIT }); } function getCouponSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: COUPON_SUPPLY_CHANGE_DIVISOR }); } function getNegativeSupplyChangeDivisor() internal pure returns (Decimal.D256 memory) { return Decimal.D256({ value: NEGATIVE_SUPPLY_CHANGE_DIVISOR }); } function getOraclePoolRatio() internal pure returns (uint256) { return ORACLE_POOL_RATIO; } function getTreasuryRatio() internal pure returns (uint256) { return TREASURY_RATIO; } function getChainId() internal pure returns (uint256) { return CHAIN_ID; } function getDaoAddress() internal pure returns (address) { return DAO_ADDRESS; } function getDollarAddress() internal pure returns (address) { return DOLLAR_ADDRESS; } function getPairAddress() internal pure returns (address) { return PAIR_ADDRESS; } function getTreasuryAddress() internal pure returns (address) { return TREASURY_ADDRESS; } } /* Copyright 2020 Dynamic Dollar Devs, based on the works of the Empty Set Squad 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. */ contract Oracle is IOracle { using Decimal for Decimal.D256; bytes32 private constant FILE = "Oracle"; address private constant SUSHISWAP_FACTORY = address(0xC0AEe478e3658e2610c5F7A4A2E1777cE9e4f2Ac); // Sushi Factory Address bool internal _initialized; IUniswapV2Pair internal _pair; uint256 internal _index; uint256 internal _cumulative; uint32 internal _timestamp; uint256 internal _reserve; function setup() public onlyDao { _pair = IUniswapV2Pair(IUniswapV2Factory(SUSHISWAP_FACTORY).getPair(Constants.getDollarAddress(), usdc())); (address token0, address token1) = (_pair.token0(), _pair.token1()); _index = Constants.getDollarAddress() == token0 ? 0 : 1; Require.that(_index == 0 || Constants.getDollarAddress() == token1, FILE, "DSD not found"); } /** * Trades/Liquidity: (1) Initializes reserve and blockTimestampLast (can calculate a price) * (2) Has non-zero cumulative prices * * Steps: (1) Captures a reference blockTimestampLast * (2) First reported value */ function capture() public onlyDao returns (Decimal.D256 memory, bool) { if (_initialized) { return updateOracle(); } else { initializeOracle(); return (Decimal.one(), false); } } function initializeOracle() private { IUniswapV2Pair pair = _pair; uint256 priceCumulative = _index == 0 ? pair.price0CumulativeLast() : pair.price1CumulativeLast(); (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = pair.getReserves(); if (reserve0 != 0 && reserve1 != 0 && blockTimestampLast != 0) { _cumulative = priceCumulative; _timestamp = blockTimestampLast; _initialized = true; _reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve } } function updateOracle() private returns (Decimal.D256 memory, bool) { Decimal.D256 memory price = updatePrice(); uint256 lastReserve = updateReserve(); bool isBlacklisted = IUSDC(usdc()).isBlacklisted(address(_pair)); bool valid = true; if (lastReserve < Constants.getOracleReserveMinimum()) { valid = false; } if (_reserve < Constants.getOracleReserveMinimum()) { valid = false; } if (isBlacklisted) { valid = false; } return (price, valid); } function updatePrice() private returns (Decimal.D256 memory) { (uint256 price0Cumulative, uint256 price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(address(_pair)); uint32 timeElapsed = blockTimestamp - _timestamp; // overflow is desired uint256 priceCumulative = _index == 0 ? price0Cumulative : price1Cumulative; Decimal.D256 memory price = Decimal.ratio((priceCumulative - _cumulative) / timeElapsed, 2**112); _timestamp = blockTimestamp; _cumulative = priceCumulative; return price.mul(1e12); } function updateReserve() private returns (uint256) { uint256 lastReserve = _reserve; (uint112 reserve0, uint112 reserve1, ) = _pair.getReserves(); _reserve = _index == 0 ? reserve1 : reserve0; // get counter's reserve return lastReserve; } function usdc() internal view returns (address) { return Constants.getUsdcAddress(); } function pair() external view returns (address) { return address(_pair); } function reserve() external view returns (uint256) { return _reserve; } modifier onlyDao() { Require.that(msg.sender == Constants.getDaoAddress(), FILE, "Not DAO"); _; } }
get counter's reserve
_reserve = _index == 0 ? reserve1 : reserve0;
547,982
[ 1, 588, 3895, 1807, 20501, 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, 5411, 389, 455, 6527, 273, 389, 1615, 422, 374, 692, 20501, 21, 294, 20501, 20, 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 ]
./full_match/80001/0x416E2d3E39dF69bBc30244eC90477fD042812E6B/sources/src/Interfaces/IHyphenRouter.sol
ERROR: type should be string, got " https:github.com/bcnmy/hyphen-contract/blob/master/contracts/hyphen/LiquidityPool.sol"
interface IHyphenRouter { function depositErc20( uint256 toChainId, address tokenAddress, address receiver, uint256 amount, string calldata tag ) external; function depositNative( address receiver, uint256 toChainId, string calldata tag ) external payable; pragma solidity 0.8.17; }
5,585,594
[ 1, 4528, 30, 6662, 18, 832, 19, 70, 10305, 4811, 19, 18112, 13819, 17, 16351, 19, 10721, 19, 7525, 19, 16351, 87, 19, 18112, 13819, 19, 48, 18988, 24237, 2864, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 5831, 467, 17507, 13819, 8259, 288, 203, 565, 445, 443, 1724, 41, 1310, 3462, 12, 203, 3639, 2254, 5034, 358, 3893, 548, 16, 203, 3639, 1758, 1147, 1887, 16, 203, 3639, 1758, 5971, 16, 203, 3639, 2254, 5034, 3844, 16, 203, 3639, 533, 745, 892, 1047, 203, 565, 262, 3903, 31, 203, 203, 565, 445, 443, 1724, 9220, 12, 203, 3639, 1758, 5971, 16, 203, 3639, 2254, 5034, 358, 3893, 548, 16, 203, 3639, 533, 745, 892, 1047, 203, 565, 262, 3903, 8843, 429, 31, 203, 683, 9454, 18035, 560, 374, 18, 28, 18, 4033, 31, 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 ]
./full_match/3/0xDc7f48a876c5797fb2460F2FB1d2d2c7534a7464/sources/browser/crops.sol
SushiToken with Governance.
contract crops is ERC20("cropsToken", "CROPS"), Ownable { function mint(address _to, uint256 _amount) public onlyOwner { _mint(_to, _amount); _moveDelegates(address(0), _delegates[_to], _amount); } mapping (address => address) internal _delegates; struct Checkpoint { uint32 fromBlock; uint256 votes; } mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; mapping (address => uint32) public numCheckpoints; bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); mapping (address => uint) public nonces; event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function delegates(address delegator) external view returns (address) { return _delegates[delegator]; } function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } 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), "SUSHI::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "SUSHI::delegateBySig: invalid nonce"); require(now <= expiry, "SUSHI::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } function getCurrentVotes(address account) external view returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } function getPriorVotes(address account, uint blockNumber) external view returns (uint256) { require(blockNumber < block.number, "SUSHI::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; lower = center; upper = center - 1; } } return checkpoints[account][lower].votes; } } else if (cp.fromBlock < blockNumber) { } else { function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; _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)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _moveDelegates(address srcRep, address dstRep, uint256 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld.sub(amount); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "SUSHI::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } } else { function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal pure returns (uint) { uint256 chainId; return chainId; } assembly { chainId := chainid() } }
14,197,036
[ 1, 55, 1218, 77, 1345, 598, 611, 1643, 82, 1359, 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 ]
[ 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, 16351, 276, 16703, 353, 4232, 39, 3462, 2932, 71, 16703, 1345, 3113, 315, 39, 1457, 5857, 6, 3631, 14223, 6914, 288, 203, 565, 445, 312, 474, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1071, 1338, 5541, 288, 203, 3639, 389, 81, 474, 24899, 869, 16, 389, 8949, 1769, 203, 3639, 389, 8501, 15608, 815, 12, 2867, 12, 20, 3631, 389, 3771, 1332, 815, 63, 67, 869, 6487, 389, 8949, 1769, 203, 565, 289, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 1758, 13, 2713, 389, 3771, 1332, 815, 31, 203, 565, 1958, 25569, 288, 203, 3639, 2254, 1578, 628, 1768, 31, 203, 3639, 2254, 5034, 19588, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 11890, 1578, 516, 25569, 3719, 1071, 26402, 31, 203, 565, 2874, 261, 2867, 516, 2254, 1578, 13, 1071, 818, 1564, 4139, 31, 203, 565, 1731, 1578, 1071, 5381, 27025, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 41, 2579, 27, 2138, 3748, 12, 1080, 508, 16, 11890, 5034, 2687, 548, 16, 2867, 3929, 310, 8924, 2225, 1769, 203, 565, 1731, 1578, 1071, 5381, 2030, 19384, 2689, 67, 2399, 15920, 273, 417, 24410, 581, 5034, 2932, 26945, 12, 2867, 7152, 73, 16, 11890, 5034, 7448, 16, 11890, 5034, 10839, 2225, 1769, 203, 565, 2874, 261, 2867, 516, 2254, 13, 1071, 1661, 764, 31, 203, 565, 871, 27687, 5033, 12, 2867, 8808, 11158, 639, 16, 1758, 8808, 628, 9586, 16, 1758, 8808, 358, 9586, 1769, 2 ]
// to test issue with nodes breaking with large clients over WS // fixed in web3 with fragmentationThreshold: 8192 pragma solidity ^0.4.17; contract BigFreakingContract { event Transfer(address indexed from, address indexed to, uint value); event Approval( address indexed owner, address indexed spender, uint value); mapping( address => uint ) _balances; mapping( address => mapping( address => uint ) ) _approvals; uint public _supply; constructor( uint initial_balance ) public { _balances[msg.sender] = initial_balance; _supply = initial_balance; } function totalSupply() public constant returns (uint supply) { return _supply; } function balanceOf( address who ) public constant returns (uint value) { return _balances[who]; } function transfer( address to, uint value) public returns (bool ok) { if( _balances[msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } _balances[msg.sender] -= value; _balances[to] += value; emit Transfer( msg.sender, to, value ); return true; } function transferFrom( address from, address to, uint value) public returns (bool ok) { // if you don't have enough balance, throw if( _balances[from] < value ) { revert(); } // if you don't have approval, throw if( _approvals[from][msg.sender] < value ) { revert(); } if( !safeToAdd(_balances[to], value) ) { revert(); } // transfer and return true _approvals[from][msg.sender] -= value; _balances[from] -= value; _balances[to] += value; emit Transfer( from, to, value ); return true; } function approve(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function allowance(address owner, address spender) public constant returns (uint _allowance) { return _approvals[owner][spender]; } function safeToAdd(uint a, uint b) internal pure returns (bool) { return (a + b >= a); } function isAvailable() public pure returns (bool) { return false; } function approve_1(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_2(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_3(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_4(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_5(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_6(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_7(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_8(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_9(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_10(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_11(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_12(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_13(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_14(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_15(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_16(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_17(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_18(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_19(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_20(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_21(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_22(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_23(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_24(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_25(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_26(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_27(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_28(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_29(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_30(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_31(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_32(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_33(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_34(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_35(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_36(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_37(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_38(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_39(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_40(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_41(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_42(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_43(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_44(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_45(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_46(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_47(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_48(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_49(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_50(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_51(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_52(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_53(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_54(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_55(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_56(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_57(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_58(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_59(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_60(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_61(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_62(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_63(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_64(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_65(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_66(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_67(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_68(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_69(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_70(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_71(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_72(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_73(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_74(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_75(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_76(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_77(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_78(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_79(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_80(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_81(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_82(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_83(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_84(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_85(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_86(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_87(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_88(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_89(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_90(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_91(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_92(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_93(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_94(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_95(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_96(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_97(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_98(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_99(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_100(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_101(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_102(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_103(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_104(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_105(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_106(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_107(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_108(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_109(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_110(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_111(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_112(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_113(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_114(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_115(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_116(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_117(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_118(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_119(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_120(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_121(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_122(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_123(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_124(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_125(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_126(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_127(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_128(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_129(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_130(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_131(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_132(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_133(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_134(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_135(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_136(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_137(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_138(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_139(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_140(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_141(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_142(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_143(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_144(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_145(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_146(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_147(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_148(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_149(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_150(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_151(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_152(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_153(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_154(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_155(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_156(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_157(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_158(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_159(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_160(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_161(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_162(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_163(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_164(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_165(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_166(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_167(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_168(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_169(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_170(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_171(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_172(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_173(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_174(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_175(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_176(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_177(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_178(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_179(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_180(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_181(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_182(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_183(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_184(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_185(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_186(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_187(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_188(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_189(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_190(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_191(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_192(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_193(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_194(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_195(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_196(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_197(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_198(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_199(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_200(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_201(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_202(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_203(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_204(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_205(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_206(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_207(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_208(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_209(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_210(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_211(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_212(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_213(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_214(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_215(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_216(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_217(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_218(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_219(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_220(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_221(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_222(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_223(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_224(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_225(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_226(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_227(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_228(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_229(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_230(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_231(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_232(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_233(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_234(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_235(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_236(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_237(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_238(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_239(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_240(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_241(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_242(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_243(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_244(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_245(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_246(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_247(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_248(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_249(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_250(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_251(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_252(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_253(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_254(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_255(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_256(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_257(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_258(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_259(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_260(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_261(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_262(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_263(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_264(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_265(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_266(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_267(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_268(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_269(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_270(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_271(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_272(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_273(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_274(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_275(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_276(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_277(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_278(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_279(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_280(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_281(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_282(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_283(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_284(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_285(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_286(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_287(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_288(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_289(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_290(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_291(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_292(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_293(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_294(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_295(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_296(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_297(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_298(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_299(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_300(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_301(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_302(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_303(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_304(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_305(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_306(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_307(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_308(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_309(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_310(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_311(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_312(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_313(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_314(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_315(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_316(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_317(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_318(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_319(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_320(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_321(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_322(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_323(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_324(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_325(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_326(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_327(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_328(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_329(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_330(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_331(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_332(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_333(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_334(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_335(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_336(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_337(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_338(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_339(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_340(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_341(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_342(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_343(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_344(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_345(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_346(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_347(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_348(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_349(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_350(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_351(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_352(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_353(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_354(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_355(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_356(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_357(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_358(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_359(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_360(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_361(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_362(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_363(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_364(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_365(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_366(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_367(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_368(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_369(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_370(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_371(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_372(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_373(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_374(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_375(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_376(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_377(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_378(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_379(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_380(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_381(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_382(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_383(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_384(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_385(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_386(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_387(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_388(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_389(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_390(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_391(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_392(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_393(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_394(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_395(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_396(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_397(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_398(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_399(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_400(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_401(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_402(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_403(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_404(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_405(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_406(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_407(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_408(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_409(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_410(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_411(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_412(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_413(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_414(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_415(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_416(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_417(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_418(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_419(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_420(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_421(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_422(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_423(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_424(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_425(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_426(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_427(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_428(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_429(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_430(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_431(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_432(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_433(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_434(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_435(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_436(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_437(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_438(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_439(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_440(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_441(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_442(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_443(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_444(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_445(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_446(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_447(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_448(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_449(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_450(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_451(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_452(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_453(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_454(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_455(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_456(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_457(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_458(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_459(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_460(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_461(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_462(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_463(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_464(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_465(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_466(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_467(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_468(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_469(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_470(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_471(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_472(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_473(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_474(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_475(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_476(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_477(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_478(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_479(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_480(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_481(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_482(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_483(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_484(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_485(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_486(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_487(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_488(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_489(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_490(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_491(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_492(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_493(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_494(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_495(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_496(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_497(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_498(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_499(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_500(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_501(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_502(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_503(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_504(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_505(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_506(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_507(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_508(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_509(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_510(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_511(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_512(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_513(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_514(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_515(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_516(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_517(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_518(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_519(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_520(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_521(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_522(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_523(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_524(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_525(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_526(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_527(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_528(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_529(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_530(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_531(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_532(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_533(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_534(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_535(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_536(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_537(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_538(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_539(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_540(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_541(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_542(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_543(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_544(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_545(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_546(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_547(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_548(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_549(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_550(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_551(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_552(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_553(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_554(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_555(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_556(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_557(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_558(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_559(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_560(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_561(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_562(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_563(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_564(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_565(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_566(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_567(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_568(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_569(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_570(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_571(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_572(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_573(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_574(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_575(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_576(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_577(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_578(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_579(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_580(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_581(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_582(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_583(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_584(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_585(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_586(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_587(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_588(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_589(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_590(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_591(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_592(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_593(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_594(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_595(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_596(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_597(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_598(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_599(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_600(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_601(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_602(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_603(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_604(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_605(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_606(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_607(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_608(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_609(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_610(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_611(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_612(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_613(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_614(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_615(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_616(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_617(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_618(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_619(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_620(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_621(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_622(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_623(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_624(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_625(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_626(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_627(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_628(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_629(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_630(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_631(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_632(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_633(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_634(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_635(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_636(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_637(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_638(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_639(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_640(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_641(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_642(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_643(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_644(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_645(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_646(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_647(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_648(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_649(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_650(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_651(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_652(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_653(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_654(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_655(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_656(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_657(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_658(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_659(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_660(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_661(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_662(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_663(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_664(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_665(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_666(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_667(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_668(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_669(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_670(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_671(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_672(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_673(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_674(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_675(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_676(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_677(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_678(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_679(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_680(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_681(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_682(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_683(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_684(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_685(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_686(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_687(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_688(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_689(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_690(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_691(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_692(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_693(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_694(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_695(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_696(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_697(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_698(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_699(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_700(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_701(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_702(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_703(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_704(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_705(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_706(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_707(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_708(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_709(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_710(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_711(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_712(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_713(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_714(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_715(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_716(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_717(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_718(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_719(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_720(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_721(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_722(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_723(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_724(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_725(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_726(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_727(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_728(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_729(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_730(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_731(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_732(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_733(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_734(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_735(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_736(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_737(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_738(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_739(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_740(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_741(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_742(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_743(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_744(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_745(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_746(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_747(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_748(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_749(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_750(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_751(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_752(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_753(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_754(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_755(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_756(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_757(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_758(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_759(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_760(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_761(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_762(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_763(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_764(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_765(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_766(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_767(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_768(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_769(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_770(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_771(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_772(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_773(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_774(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_775(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_776(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_777(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_778(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_779(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_780(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_781(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_782(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_783(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_784(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_785(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_786(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_787(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_788(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_789(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_790(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_791(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_792(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_793(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_794(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_795(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_796(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_797(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_798(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_799(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_800(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_801(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_802(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_803(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_804(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_805(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_806(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_807(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_808(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_809(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_810(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_811(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_812(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_813(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_814(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_815(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_816(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_817(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_818(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_819(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_820(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_821(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_822(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_823(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_824(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_825(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_826(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_827(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_828(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_829(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_830(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_831(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_832(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_833(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_834(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_835(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_836(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_837(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_838(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_839(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_840(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_841(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_842(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_843(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_844(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_845(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_846(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_847(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_848(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_849(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_850(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_851(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_852(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_853(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_854(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_855(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_856(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_857(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_858(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_859(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_860(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_861(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_862(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_863(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_864(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_865(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_866(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_867(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_868(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_869(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_870(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_871(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_872(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_873(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_874(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_875(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_876(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_877(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_878(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_879(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_880(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_881(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_882(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_883(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_884(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_885(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_886(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_887(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_888(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_889(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_890(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_891(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_892(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_893(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_894(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_895(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_896(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_897(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_898(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_899(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_900(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } function approve_901(address spender, uint value) public returns (bool ok) { // TODO: should increase instead _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; } }
TODO: should increase instead
function approve_806(address spender, uint value) public returns (bool ok) { _approvals[msg.sender][spender] = value; emit Approval( msg.sender, spender, value ); return true; }
6,454,519
[ 1, 6241, 30, 1410, 10929, 3560, 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, 225, 445, 6617, 537, 67, 3672, 26, 12, 2867, 17571, 264, 16, 2254, 460, 13, 1071, 1135, 261, 6430, 1529, 13, 288, 203, 565, 389, 12908, 4524, 63, 3576, 18, 15330, 6362, 87, 1302, 264, 65, 273, 460, 31, 203, 565, 3626, 1716, 685, 1125, 12, 1234, 18, 15330, 16, 17571, 264, 16, 460, 11272, 203, 565, 327, 638, 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, -100, -100, -100, -100, -100, -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: GPL-3.0 pragma solidity ^0.8.0; import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/access/AccessControl.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/contracts/token/ERC20/ERC20.sol"; /** * @title VestingInstance * @dev Implements a vesting instance contract */ contract VestingInstance is AccessControl { // roles bytes32 public constant CONTROLLER_ROLE = keccak256("CONTROLLER_ROLE"); bytes32 public constant BENEFICIARY_ROLE = keccak256("BENEFICIARY_ROLE"); // constants uint public constant MAX_TIME_TO_CLAIM = 208 weeks; //4 years uint public constant MAX_VEST_TIME = 520 weeks; //10 years uint public constant MAX_DELAY = 208 weeks; //4 years uint public constant MAX_CLIFF = 208 weeks; //4 years uint public constant MAX_PERIODS = 52 weeks; //1 year in seconds // addresses address public beneficiary; // the address or contract that recieves vested tokens address public return_funds; // used to refund funds that are unclaimed address public token_address; // address of token to be vested // vesting parameters uint public delay; // delay before vesting starts, from time of vesting instance creation uint public cliff; // vesting cliff uint public period_time; // vesting period time uint public num_periods; // number of vesting periods uint public vesting_start_time; // vesting start time (not inclusive of the delay) i.e. when vesting instance was created uint public num_to_vest; // number of tokens to vest uint public time_to_claim; // max time available to claim vested tokens after all tokens have vested, max is MAX_TIME_TO_CLAIM // calculated paramteres - computed as needed and not guaranteed to be accurate at all times uint private vesting_end_time; // calcualted value for when the vesting ends uint public claimed; // number of tokens claimed uint private claimable; // number of tokens claimable - only calculated occasionally // contract state variables bool public complete; // flag to indicate whether this vesting instance is done vesting bool public paused; // flag to indicate whether this vesting instance is done vesting uint public paused_timestamp; // when was the contract paused uint private pause_delay; // vesting delay bool private initialized; // flag to indicate whether this struct has been initialized /** * @dev Constructor */ constructor( address _beneficiary, address _return_funds, address _token_address, address _controller, uint _delay, uint _cliff, uint _period_time, uint _num_periods, uint _num_to_vest, uint _time_to_claim ) { // set roles _setupRole( DEFAULT_ADMIN_ROLE, _msgSender() ); // set admin as the owner grantRole( CONTROLLER_ROLE, _controller ); // set the controller grantRole( BENEFICIARY_ROLE, _beneficiary ); // set the controller // check min/max period time require( _period_time > 0, "Period time can't be zero." ); require( _period_time < MAX_VEST_TIME, "Period time can't be greater than max vesting time." ); // ensure number of periods > 0, < max require( _num_periods > 0, "Number of vesting periods can't be zero." ); require( _num_periods <= MAX_PERIODS, "Number of vesting periods can't be more than the number of seconds in a year." ); // ensure delay is less than max delay require( _delay <= MAX_DELAY, "Delay can't be this long." ); // ensure cliff is less than period_time*num_periods and less than max delay require( _cliff <= MAX_CLIFF, "Cliff can't be this long." ) ; require( _cliff < (_delay + _period_time*_num_periods), "Cliff can't be beyond vesting time." ); // ensure num to vest is sensible require( _num_to_vest > 0, "Must vest more than zero tokens." ); // ensure time to claim is less than max require( _time_to_claim > 0, "Cannnot allow zero time to claim tokens." ); require( _time_to_claim <= MAX_TIME_TO_CLAIM, "Time to claim tokens too large." ); beneficiary = _beneficiary; return_funds = _return_funds; token_address = _token_address; delay = _delay; cliff = _cliff; period_time = _period_time; num_periods = _num_periods; vesting_start_time = block.timestamp; num_to_vest = _num_to_vest; time_to_claim = _time_to_claim; claimed = 0; claimable = 0; pause_delay = 0; complete = false; paused = false; initialized = true; vesting_end_time = calc_end_timestamp(); require( vesting_end_time > block.timestamp, "Vesting period exceeeds allowable limits." ); claimable = calc_claimable(); complete = is_complete(); } /** * @dev The beneficiary can swap another beneficary in their stead. */ function swap_beneficiary( address _new_beneficiary ) public onlyRole(DEFAULT_ADMIN_ROLE) { require( _new_beneficiary != beneficiary, "Must provide new beneficiary" ); grantRole( BENEFICIARY_ROLE, _new_beneficiary); // make the new beneficiary the beneficiary revokeRole( BENEFICIARY_ROLE, beneficiary ); // revoke beneficiary rights from the old beneficiary beneficiary = _new_beneficiary; } /** * @dev Pause the vesting of tokens. Vesting resumes only when resume function is called. * Can only be called by the controller. */ function pause_vesting() public onlyRole(CONTROLLER_ROLE) { paused_timestamp = block.timestamp; paused = true; } /** * @dev Resume vesting tokens. * Can only be called by the controller */ function resume_vesting() public onlyRole(CONTROLLER_ROLE) { require( paused, "Can only unpause if the vesting is paused" ); pause_delay += paused_delay(); paused = false; vesting_end_time = calc_end_timestamp(); } /** * @dev Claim tokens. * Can only be called by the beneficiary. */ function claim() public onlyRole(BENEFICIARY_ROLE) { // check contract state require( initialized, "This vesting contract has not been initialized. This should never happen." ); require( !complete, "This vesting contract has completed vesting." ); ERC20 token = ERC20(token_address); claimable = calc_claimable(); require( claimable > 0, "There are no tokens to claim." ); require( claimed < num_to_vest, "Cannot claim more tokens than available in the vesting contract" ); token.transfer( beneficiary, claimable ); claimed += claimable; claimable = 0; complete = is_complete(); // check if the vesting is complete } /** * @dev Calcualte how many tokens are claimable based on vesting pamareters. */ function calc_claimable() public view returns(uint) { // calculate how many tokens the user can claim uint vesting_time = calc_vesting_time(); // how much vesting time has passed uint periods_passed = vesting_time/period_time; // how many vesting periods have passed uint tokens_per_period = num_to_vest/num_periods; uint total_claimable = tokens_per_period*periods_passed; if( periods_passed >= num_periods ) { // if more periods have passed than the total vesting periods then everything is claimable total_claimable = num_to_vest; } require( total_claimable >= claimed, "Total claimable must be greater than or equal to that already claimed. This should never happen." ); return (total_claimable - claimed); } /** * @dev Calcualte how much time the tokens have been vesting, net of delays and pauses. */ function calc_vesting_time() public view returns(uint) { uint additional_delay = paused_delay(); if( block.timestamp <= (vesting_start_time + delay + pause_delay + cliff + additional_delay) ) return 0; return block.timestamp - vesting_start_time - delay - pause_delay + additional_delay; } /** * @dev Calculate when the vesting contract completes vesting. */ function calc_end_timestamp() public view returns(uint) { return (vesting_start_time + delay + pause_delay + period_time*num_periods + paused_delay()); } /** * @dev If the contract is paused calcualte how long it has been paused. */ function paused_delay() internal view returns(uint) { if( paused ) { require( block.timestamp > paused_timestamp, "Some kind of fuckery is going on." ); return (block.timestamp - paused_timestamp); } return 0; } /** * @dev Check if the contract is compelte. The contract is complete when all tokens have been claimed and when the current time is past the vesting end time. */ function is_complete() public view returns(bool) { // check if all tokens have vested and if all tokens have been claimed if( (claimed >= num_to_vest) && (block.timestamp >= calc_end_timestamp()) ) return true; return false; } /** * @dev Check whether the contract has sufficient funds remaining to satisfy the vesting contract. */ function sufficient_funds() public view returns(bool) { ERC20 token = ERC20( token_address ); uint balance = token.balanceOf( address(this) ); require( num_to_vest >= claimed, "Number of tokens claimed in this contract exceeds the number set to vest." ); if( balance >= (num_to_vest - claimed) ) return true; return false; } /** * @dev Refund tokens if the vesting period has lapsed. */ function refund() public onlyRole(DEFAULT_ADMIN_ROLE) { // check if the vesting period has lapsed require( block.timestamp > (calc_end_timestamp() + time_to_claim), "The vesting contract has not yet lapsed." ); // calcualte the number of tokens remaining to be claimed and refund those tokens ERC20 token = ERC20( token_address ); claimable = calc_claimable(); token.transfer( return_funds, claimable ); claimed += claimable; claimable = 0; complete = is_complete(); } }
set the controller
grantRole( CONTROLLER_ROLE, _controller );
5,354,851
[ 1, 542, 326, 2596, 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, 7936, 2996, 12, 8020, 25353, 67, 16256, 16, 389, 5723, 11272, 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 ]
// 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; 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 onlyOwner { bountyReduction = true; } function disableBountyReduction() external onlyOwner { 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 populate() external onlyOwner { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); TimeHelpers timeHelpers = TimeHelpers(contractManager.getTimeHelpers()); uint currentMonth = timeHelpers.getCurrentMonth(); // clean existing data for ( uint i = _effectiveDelegatedSum.firstUnprocessedMonth; i < _effectiveDelegatedSum.lastChangedMonth.add(1); ++i ) { delete _effectiveDelegatedSum.addDiff[i]; delete _effectiveDelegatedSum.subtractDiff[i]; } delete _effectiveDelegatedSum.value; delete _effectiveDelegatedSum.lastChangedMonth; _effectiveDelegatedSum.firstUnprocessedMonth = currentMonth; uint[] memory validators = validatorService.getTrustedValidators(); for (uint i = 0; i < validators.length; ++i) { uint validatorId = validators[i]; uint currentEffectiveDelegated = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, currentMonth); uint[] memory effectiveDelegated = delegationController.getEffectiveDelegatedValuesByValidator(validatorId); if (effectiveDelegated.length > 0) { assert(currentEffectiveDelegated == effectiveDelegated[0]); } uint added = 0; for (uint j = 0; j < effectiveDelegated.length; ++j) { if (effectiveDelegated[j] != added) { if (effectiveDelegated[j] > added) { _effectiveDelegatedSum.addToValue(effectiveDelegated[j].sub(added), currentMonth + j); } else { _effectiveDelegatedSum.subtractFromValue(added.sub(effectiveDelegated[j]), currentMonth + j); } added = effectiveDelegated[j]; } } delete effectiveDelegated; } } 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 /* 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; // 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; /** * @dev Allows the Owner to set new reward and delta periods * This function is only for tests. */ function setPeriods(uint32 newRewardPeriod, uint32 newDeltaPeriod) external onlyOwner { 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 onlyOwner { 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 onlyOwner { allowableLatency = newAllowableLatency; } /** * @dev Allows the Owner to set the minimum stake requirement. */ function setMSR(uint newMSR) external onlyOwner { msr = newMSR; } /** * @dev Allows the Owner to set the launch timestamp. */ function setLaunchTimestamp(uint timestamp) external onlyOwner { 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 onlyOwner { rotationDelay = newDelay; } /** * @dev Allows the Owner to set the proof-of-use lockup period. */ function setProofOfUseLockUpPeriod(uint periodDays) external onlyOwner { proofOfUseLockUpPeriodDays = periodDays; } /** * @dev Allows the Owner to set the proof-of-use delegation percentage * requirement. */ function setProofOfUseDelegationPercentage(uint percentage) external onlyOwner { 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 onlyOwner { limitValidatorsPerDelegator = newLimit; } function setSchainCreationTimeStamp(uint timestamp) external onlyOwner { schainCreationTimeStamp = timestamp; } function setMinimalSchainLifetime(uint lifetime) external onlyOwner { minimalSchainLifetime = lifetime; } function setComplaintTimelimit(uint timelimit) external onlyOwner { 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 /* 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 "./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 { 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_LAUNCH_LOCKER = "TokenLaunchLocker"; 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 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 getTokenLaunchLocker() external view returns (address) { return getContract(TOKEN_LAUNCH_LOCKER); } 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 returns (address contractAddress) { contractAddress = contracts[keccak256(abi.encodePacked(name))]; if (contractAddress == address(0)) { revert(name.strConcat(" contract has not been found")); } } } // 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 /* 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 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; } function initPublicKeyInProgress(bytes32 schainId) external allow("SkaleDKG") { _publicKeysInProgress[schainId] = G2Operations.getG2Zero(); } function adding(bytes32 schainId, G2Operations.G2Point memory value) external allow("SkaleDKG") { require(value.isG2(), "Incorrect g2 point"); _publicKeysInProgress[schainId] = value.addG2(_publicKeysInProgress[schainId]); } function finalizePublicKey(bytes32 schainId) external allow("SkaleDKG") { if (!_isSchainsPublicKeyZero(schainId)) { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); } _schainsPublicKeys[schainId] = _publicKeysInProgress[schainId]; delete _publicKeysInProgress[schainId]; } function getCommonPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { return _schainsPublicKeys[schainId]; } function getPreviousPublicKey(bytes32 schainId) external view returns (G2Operations.G2Point memory) { uint length = _previousSchainsPublicKeys[schainId].length; if (length == 0) { return G2Operations.getG2Zero(); } return _previousSchainsPublicKeys[schainId][length - 1]; } function getAllPreviousPublicKeys(bytes32 schainId) external view returns (G2Operations.G2Point[] memory) { return _previousSchainsPublicKeys[schainId]; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function _isSchainsPublicKeyZero(bytes32 schainId) private view returns (bool) { return _schainsPublicKeys[schainId].x.a == 0 && _schainsPublicKeys[schainId].x.b == 0 && _schainsPublicKeys[schainId].y.a == 0 && _schainsPublicKeys[schainId].y.b == 0; } function _getData() private view returns (BroadcastedData memory) { return _data[keccak256(abi.encodePacked("UnusedFunction"))][0]; } function _getNodesPublicKey() private view returns (G2Operations.G2Point memory) { return _schainsNodesPublicKeys[keccak256(abi.encodePacked("UnusedFunction"))][0]; } } // 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 "@openzeppelin/contracts-ethereum-package/contracts/utils/Strings.sol"; import "./Permissions.sol"; import "./ConstantsHolder.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using StringUtils for string; using StringUtils for uint; using Strings for uint; /** * 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; /** * @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) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); require(_checkRotation(schainId), "No free Nodes available for rotating"); rotateNode(nodeIndex, schainId, true); return schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false; } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schains = schainsInternal.getActiveSchains(nodeIndex); for (uint i = 0; i < schains.length; i++) { Rotation memory rotation = rotations[schains[i]]; if (rotation.nodeIndex == nodeIndex && now < rotation.freezeUntil) { continue; } string memory schainName = schainsInternal.getSchainName(schains[i]); string memory revertMessage = "Node cannot rotate on Schain "; revertMessage = revertMessage.strConcat(schainName); revertMessage = revertMessage.strConcat(", occupied by Node "); revertMessage = revertMessage.strConcat(rotation.nodeIndex.toString()); string memory dkgRevert = "DKG process did not finish on schain "; ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require( skaleDKG.isLastDKGSuccessful(keccak256(abi.encodePacked(schainName))), dkgRevert.strConcat(schainName)); require(rotation.freezeUntil < now, revertMessage); _startRotation(schains[i], nodeIndex); } } /** * @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 onlyOwner { 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 schainId, bool shouldDelay ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Schains schains = Schains(contractManager.getContract("Schains")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); newNode = selectNodeToGroup(schainId); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); schains.addSpace(nodeIndex, space); _finishRotation(schainId, 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 schainId) public allowThree("SkaleManager", "Schains", "SkaleDKG") returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(schainsInternal.isSchainActive(schainId), "Group is not active"); uint8 space = schainsInternal.getSchainsPartOfNode(schainId); uint[] memory possibleNodes = schainsInternal.isEnoughNodes(schainId); require(possibleNodes.length > 0, "No free Nodes available for rotation"); uint nodeIndex; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number - 1)), schainId))); do { uint index = random % possibleNodes.length; nodeIndex = possibleNodes[index]; random = uint(keccak256(abi.encodePacked(random, nodeIndex))); } while (schainsInternal.checkException(schainId, nodeIndex)); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); return nodeIndex; } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].newNodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); waitForNewNode[schainIndex] = true; } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); leavingHistory[nodeIndex].push( LeavingHistory(schainIndex, shouldDelay ? now.add(constants.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 schainId ) private view returns (bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist for rotation"); return schainsInternal.isAnyFreeNode(schainId); } } // 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 "./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 SafeCast for uint; // 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; string domainName; } // 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; } // 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; /** * @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) { require(nodeIndex < nodes.length, "Node with such index does not exist"); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require( isNodeExist(msg.sender, nodeIndex) || _isAdmin(msg.sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(msg.sender), "Sender is not permitted to call this function" ); _; } /** * @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) allow("Schains") { 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") // returns (uint nodeIndex) { // checks that Node has correct data require(params.ip != 0x0 && !nodesIPCheck[params.ip], "IP address is zero or is not available"); 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); // adds Node to Nodes contract uint nodeIndex = _addNode( from, params.name, params.ip, params.publicIp, params.port, params.publicKey, params.domainName, validatorId); 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); _deleteNode(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.getContract("ValidatorService")); 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.getContract("ValidatorService")); DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); require( validatorNodes.length.add(1).mul(msr) <= delegationsTotal, "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) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); 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"); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getContract("ConstantsHolder")).msr(); return position.add(1).mul(msr) <= delegationsTotal; } /** * @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 onlyNodeOrAdmin(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 onlyNodeOrAdmin(nodeIndex) { require(nodes[nodeIndex].status == NodeStatus.In_Maintenance, "Node is not In Maintenance"); _setNodeActive(nodeIndex); } function setDomainName(uint nodeIndex, string memory domainName) external onlyNodeOrAdmin(nodeIndex) { nodes[nodeIndex].domainName = domainName; } /** * @dev Returns nodes with space availability. */ function getNodesWithFreeSpace(uint8 freeSpace) external view returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint[] memory nodesWithFreeSpace = new uint[](countNodesWithFreeSpace(freeSpace)); uint cursor = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { for (uint j = 0; j < spaceToNodes[i].length; j++) { nodesWithFreeSpace[cursor] = spaceToNodes[i][j]; ++cursor; } } return nodesWithFreeSpace; } /** * @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 nodes[nodeIndex].domainName; } /** * @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 Returns IPs of active nodes. */ function getActiveNodeIPs() external view returns (bytes4[] memory activeNodeIPs) { activeNodeIPs = new bytes4[](numberOfActiveNodes); uint indexOfActiveNodeIPs = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIPs[indexOfActiveNodeIPs] = nodes[indexOfNodes].ip; indexOfActiveNodeIPs++; } } } /** * @dev Returns active nodes linked to the `msg.sender` (validator address). */ function getActiveNodesByAddress() external view returns (uint[] memory activeNodesByAddress) { activeNodesByAddress = new uint[](nodeIndexes[msg.sender].numberOfNodes); uint indexOfActiveNodesByAddress = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeExist(msg.sender, indexOfNodes) && isNodeActive(indexOfNodes)) { activeNodesByAddress[indexOfActiveNodesByAddress] = indexOfNodes; indexOfActiveNodesByAddress++; } } } /** * @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.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; } /** * @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; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) public view returns (uint count) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); count = 0; uint totalSpace = constantsHolder.TOTAL_SPACE_ON_NODE(); for (uint8 i = freeSpace; i <= totalSpace; ++i) { count = count.add(spaceToNodes[i].length); } } /** * @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 { uint8 previousSpace = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[previousSpace].length.sub(1)) { uint shiftedIndex = spaceToNodes[previousSpace][spaceToNodes[previousSpace].length.sub(1)]; spaceToNodes[previousSpace][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[previousSpace].pop(); } else { spaceToNodes[previousSpace].pop(); } spaceToNodes[newSpace].push(nodeIndex); spaceOfNodes[nodeIndex].freeSpace = newSpace; spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[newSpace].length.sub(1); } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); } /** * @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++; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; } /** * @dev Adds node to array. */ function _addNode( address from, string memory name, bytes4 ip, bytes4 publicIP, uint16 port, bytes32[2] memory publicKey, string memory domainName, uint validatorId ) private returns (uint nodeIndex) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); nodes.push(Node({ name: name, ip: ip, publicIP: publicIP, port: port, //owner: from, publicKey: publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId, domainName: domainName })); nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(name)); nodesIPCheck[ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; spaceOfNodes.push(SpaceManaging({ freeSpace: constantsHolder.TOTAL_SPACE_ON_NODE(), indexInSpaceMap: spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].length })); spaceToNodes[constantsHolder.TOTAL_SPACE_ON_NODE()].push(nodeIndex); numberOfActiveNodes++; } /** * @dev Deletes node from array. */ function _deleteNode(uint nodeIndex) private { uint8 space = spaceOfNodes[nodeIndex].freeSpace; uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; if (indexInArray < spaceToNodes[space].length.sub(1)) { uint shiftedIndex = spaceToNodes[space][spaceToNodes[space].length.sub(1)]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; spaceToNodes[space].pop(); } else { spaceToNodes[space].pop(); } delete spaceOfNodes[nodeIndex].freeSpace; delete spaceOfNodes[nodeIndex].indexInSpaceMap; } 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 _min(uint a, uint b) private pure returns (uint) { if (a < b) { return a; } else { return b; } } } // 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); } } // 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 "./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"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { using StringUtils for string; using StringUtils for uint; struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 schainId, uint time, uint gasSpend ); /** * @dev Emitted when an schain is deleted. */ event SchainDeleted( address owner, string name, bytes32 indexed schainId ); /** * @dev Emitted when a node in an schain is rotated. */ event NodeRotated( bytes32 schainId, uint oldNode, uint newNode ); /** * @dev Emitted when a node is added to an schain. */ event NodeAdded( bytes32 schainId, uint newNode ); /** * @dev Emitted when a group of nodes is created for an schain. */ event SchainNodes( string name, bytes32 schainId, uint[] nodesInGroup, uint time, uint gasSpend ); bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @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.getContract("ConstantsHolder")); 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); } function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name ) external { 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 }); _addSchain(msg.sender, 0, schainParameters); } /** * @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") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); address nodesAddress = contractManager.getContract("Nodes"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); if (!Nodes(nodesAddress).isNodeLeft(nodesInGroup[i])) { this.addSpace(nodesInGroup[i], partOfNode); } } schainsInternal.deleteGroup(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @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") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); // removes Schain from Nodes uint[] memory nodesInGroup = schainsInternal.getNodesInGroup(schainId); uint8 partOfNode = schainsInternal.getSchainsPartOfNode(schainId); for (uint i = 0; i < nodesInGroup.length; i++) { uint schainIndex = schainsInternal.findSchainAtSchainsForNode( nodesInGroup[i], schainId ); if (schainsInternal.checkHoleForSchain(schainId, i)) { continue; } require( schainIndex < schainsInternal.getLengthOfSchainsForNode(nodesInGroup[i]), "Some Node does not contain given Schain"); schainsInternal.removeNodeFromSchain(nodesInGroup[i], schainId); schainsInternal.removeNodeFromExceptions(schainId, nodesInGroup[i]); this.addSpace(nodesInGroup[i], partOfNode); } schainsInternal.deleteGroup(schainId); address from = schainsInternal.getSchainOwner(schainId); schainsInternal.removeSchain(schainId, from); schainsInternal.removeHolesForSchain(schainId); nodeRotation.removeRotation(schainId); emit SchainDeleted(from, name, schainId); } /** * @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 schainId = keccak256(abi.encodePacked(name)); ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); require(!skaleDKG.isLastDKGSuccessful(schainId), "DKG success"); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal")); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes for new group formation"); uint newNodeIndex = nodeRotation.selectNodeToGroup(schainId); skaleDKG.openChannel(schainId); emit NodeAdded(schainId, newNodeIndex); } /** * @dev addSpace - return occupied space to Node * @param nodeIndex - index of Node at common array of Nodes * @param 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 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.getContract("ConstantsHolder")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (numberOfNodes, divisor) = getNodesDataFromTypeOfSchain(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 Returns the number of Nodes and resource divisor that is needed for a * given Schain type. */ function getNodesDataFromTypeOfSchain(uint typeOfSchain) public view returns (uint numberOfNodes, uint8 partOfNode) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_SCHAIN(); if (typeOfSchain == 1) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.SMALL_DIVISOR(); } else if (typeOfSchain == 2) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_DIVISOR(); } else if (typeOfSchain == 3) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.LARGE_DIVISOR(); } else if (typeOfSchain == 4) { partOfNode = 0; numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_TEST_SCHAIN(); } else if (typeOfSchain == 5) { partOfNode = constantsHolder.SMALL_DIVISOR() / constantsHolder.MEDIUM_TEST_DIVISOR(); numberOfNodes = constantsHolder.NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN(); } else { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); (partOfNode, numberOfNodes) = schainsInternal.schainTypes(typeOfSchain); if (numberOfNodes == 0) { revert("Bad schain type"); } } } /** * @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) private { address dataAddress = contractManager.getContract("SchainsInternal"); require(SchainsInternal(dataAddress).isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain SchainsInternal(dataAddress).initializeSchain( name, from, lifetime, deposit); SchainsInternal(dataAddress).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 schainId, uint numberOfNodes, uint8 partOfNode ) private { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint[] memory nodesInGroup = schainsInternal.createGroupForSchain(schainId, numberOfNodes, partOfNode); ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainId); emit SchainNodes( schainName, schainId, 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 { uint numberOfNodes; uint8 partOfNode; SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainParameters.typeOfSchain <= schainsInternal.numberOfSchainTypes(), "Invalid type of Schain"); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime); // create a group for Schain (numberOfNodes, partOfNode) = getNodesDataFromTypeOfSchain(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } } // 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 "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./interfaces/ISkaleDKG.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { 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; /** * @dev Allows Schain contract to initialize an schain. */ function initializeSchain( string calldata name, address from, uint lifetime, uint deposit) external allow("Schains") { bytes32 schainId = keccak256(abi.encodePacked(name)); schains[schainId].name = name; schains[schainId].owner = from; schains[schainId].startDate = block.timestamp; schains[schainId].startBlock = block.number; schains[schainId].lifetime = lifetime; schains[schainId].deposit = deposit; schains[schainId].index = numberOfSchains; isSchainActive[schainId] = true; numberOfSchains++; schainsAtSystem.push(schainId); usedSchainNames[schainId] = true; } /** * @dev Allows Schain contract to create a node group for an schain. */ function createGroupForSchain( bytes32 schainId, uint numberOfNodes, uint8 partOfNode ) external allow("Schains") returns (uint[] memory) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); schains[schainId].partOfNode = partOfNode; if (partOfNode > 0) { sumOfSchainsResources = sumOfSchainsResources.add( numberOfNodes.mul(constantsHolder.TOTAL_SPACE_ON_NODE()).div(partOfNode) ); } return _generateGroup(schainId, numberOfNodes); } /** * @dev Allows Schains contract to set index in owner list. */ function setSchainIndex(bytes32 schainId, address from) external allow("Schains") { schains[schainId].indexInOwnerList = schainIndexes[from].length; schainIndexes[from].push(schainId); } /** * @dev Allows Schains contract to change the Schain lifetime through * an additional SKL token deposit. */ function changeLifetime(bytes32 schainId, uint lifetime, uint deposit) external allow("Schains") { schains[schainId].deposit = schains[schainId].deposit.add(deposit); schains[schainId].lifetime = schains[schainId].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 schainId, address from) external allow("Schains") { isSchainActive[schainId] = false; uint length = schainIndexes[from].length; uint index = schains[schainId].indexInOwnerList; if (index != length.sub(1)) { bytes32 lastSchainId = schainIndexes[from][length.sub(1)]; schains[lastSchainId].indexInOwnerList = index; schainIndexes[from][index] = lastSchainId; } schainIndexes[from].pop(); // TODO: // optimize for (uint i = 0; i + 1 < schainsAtSystem.length; i++) { if (schainsAtSystem[i] == schainId) { schainsAtSystem[i] = schainsAtSystem[schainsAtSystem.length.sub(1)]; break; } } schainsAtSystem.pop(); delete schains[schainId]; 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 remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) external allow("Schains") { _exceptionsForGroups[schainHash][nodeIndex] = false; } /** * @dev Allows Schains contract to delete a group of schains */ function deleteGroup(bytes32 schainId) external allow("Schains") { // delete channel ISkaleDKG skaleDKG = ISkaleDKG(contractManager.getContract("SkaleDKG")); delete schainsGroups[schainId]; skaleDKG.deleteChannel(schainId); } /** * @dev Allows Schain and NodeRotation contracts to set a Node like * exception for a given schain and nodeIndex. */ function setException(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { _exceptionsForGroups[schainId][nodeIndex] = true; } /** * @dev Allows Schains and NodeRotation contracts to add node to an schain * group. */ function setNodeInGroup(bytes32 schainId, uint nodeIndex) external allowTwo("Schains", "NodeRotation") { if (holesForSchains[schainId].length == 0) { schainsGroups[schainId].push(nodeIndex); } else { schainsGroups[schainId][holesForSchains[schainId][0]] = nodeIndex; uint min = uint(-1); uint index = 0; for (uint i = 1; i < holesForSchains[schainId].length; i++) { if (min > holesForSchains[schainId][i]) { min = holesForSchains[schainId][i]; index = i; } } if (min == uint(-1)) { delete holesForSchains[schainId]; } else { holesForSchains[schainId][0] = min; holesForSchains[schainId][index] = holesForSchains[schainId][holesForSchains[schainId].length - 1]; holesForSchains[schainId].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 onlyAdmin { schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external onlyAdmin { numberOfSchainTypes = newNumberOfSchainTypes; } /** * @dev Allows Admin to move schain to placeOfSchainOnNode map */ function moveToPlaceOfSchainOnNode(bytes32 schainHash) external onlyAdmin { 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; } } } } /** * @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 schainId) external view returns (uint8) { return schains[schainId].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 getSchainIdsByAddress(address from) external view returns (bytes32[] memory) { return schainIndexes[from]; } /** * @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 schainId) external view returns (address) { return schains[schainId].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 schainId = keccak256(abi.encodePacked(name)); return schains[schainId].owner == address(0) && !usedSchainNames[schainId] && keccak256(abi.encodePacked(name)) != keccak256(abi.encodePacked("Mainnet")); } /** * @dev Checks whether schain lifetime has expired. */ function isTimeExpired(bytes32 schainId) external view returns (bool) { return uint(schains[schainId].startDate).add(schains[schainId].lifetime) < block.timestamp; } /** * @dev Checks whether address is owner of schain. */ function isOwnerAddress(address from, bytes32 schainId) external view returns (bool) { return schains[schainId].owner == from; } /** * @dev Checks whether schain exists. */ function isSchainExist(bytes32 schainId) external view returns (bool) { return keccak256(abi.encodePacked(schains[schainId].name)) != keccak256(abi.encodePacked("")); } /** * @dev Returns schain name. */ function getSchainName(bytes32 schainId) external view returns (string memory) { return schains[schainId].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 schainId) external view returns (uint) { return schainsGroups[schainId].length; } /** * @dev Returns nodes in an schain group. */ function getNodesInGroup(bytes32 schainId) external view returns (uint[] memory) { return schainsGroups[schainId]; } /** * @dev Checks whether sender is a node address from a given schain group. */ function isNodeAddressesInGroup(bytes32 schainId, address sender) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < schainsGroups[schainId].length; i++) { if (nodes.getNodeAddress(schainsGroups[schainId][i]) == sender) { return true; } } return false; } /** * @dev Returns node index in schain group. */ function getNodeIndexInGroup(bytes32 schainId, uint nodeId) external view returns (uint) { for (uint index = 0; index < schainsGroups[schainId].length; index++) { if (schainsGroups[schainId][index] == nodeId) { return index; } } return schainsGroups[schainId].length; } /** * @dev Checks whether there are any nodes with free resources for given * schain. */ function isAnyFreeNode(bytes32 schainId) external view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { return true; } } return false; } /** * @dev Returns whether any exceptions exist for node in a schain group. */ function checkException(bytes32 schainId, uint nodeIndex) external view returns (bool) { return _exceptionsForGroups[schainId][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 initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 5; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 schainId) public allowTwo("Schains", "NodeRotation") { if (holesForNodes[nodeIndex].length == 0) { schainsForNodes[nodeIndex].push(schainId); placeOfSchainOnNode[schainId][nodeIndex] = schainsForNodes[nodeIndex].length; } else { uint lastHoleOfNode = holesForNodes[nodeIndex][holesForNodes[nodeIndex].length - 1]; schainsForNodes[nodeIndex][lastHoleOfNode] = schainId; placeOfSchainOnNode[schainId][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 { schainsForNodes[nodeIndex][schainIndex] = bytes32(0); 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 Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function isEnoughNodes(bytes32 schainId) public view returns (uint[] memory result) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; uint[] memory nodesWithFreeSpace = nodes.getNodesWithFreeSpace(space); uint counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (!_isCorrespond(schainId, nodesWithFreeSpace[i])) { counter++; } } if (counter < nodesWithFreeSpace.length) { result = new uint[](nodesWithFreeSpace.length.sub(counter)); counter = 0; for (uint i = 0; i < nodesWithFreeSpace.length; i++) { if (_isCorrespond(schainId, nodesWithFreeSpace[i])) { result[counter] = nodesWithFreeSpace[i]; counter++; } } } } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); uint[] memory possibleNodes = isEnoughNodes(schainId); require(possibleNodes.length >= nodesInGroup.length, "Not enough nodes to create Schain"); uint ignoringTail = 0; uint random = uint(keccak256(abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId))); for (uint i = 0; i < nodesInGroup.length; ++i) { uint index = random % (possibleNodes.length.sub(ignoringTail)); uint node = possibleNodes[index]; nodesInGroup[i] = node; _swap(possibleNodes, index, possibleNodes.length.sub(ignoringTail).sub(1)); ++ignoringTail; _exceptionsForGroups[schainId][node] = true; addSchainForNode(node, schainId); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; } function _isCorrespond(bytes32 schainId, uint nodeIndex) private view returns (bool) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); return !_exceptionsForGroups[schainId][nodeIndex] && nodes.isNodeActive(nodeIndex); } /** * @dev Swaps one index for another in an array. */ function _swap(uint[] memory array, uint index1, uint index2) private pure { uint buffer = array[index1]; array[index1] = array[index2]; array[index2] = buffer; } /** * @dev Returns local index of node in schain group. */ function _findNode(bytes32 schainId, uint nodeIndex) private view returns (uint) { uint[] memory nodesInGroup = schainsGroups[schainId]; uint index; for (index = 0; index < nodesInGroup.length; index++) { if (nodesInGroup[index] == nodeIndex) { return index; } } return index; } } // 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 /* 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 "./TokenLaunchLocker.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); _getTokenLaunchLocker().handleDelegationRemoving( delegations[delegationId].holder, delegationId, 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 _getTokenLaunchLocker() private view returns (TokenLaunchLocker) { return TokenLaunchLocker(contractManager.getTokenLaunchLocker()); } 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; _getTokenLaunchLocker().handleDelegationAdd( delegations[delegationId].holder, delegationId, amount, delegations[delegationId].started ); 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 /* 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"; /** * @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; /** * @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 onlyOwner { require(stakeMultipliers[monthsCount] == 0, "Delegation perios 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 /* 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 /* 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; /** * @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 onlyAdmin { 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 /* 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 /* TokenLaunchLocker.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 "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; import "./PartialDifferences.sol"; /** * @title TokenLaunchLocker * @dev This contract manages lockers applied to the launch process. */ contract TokenLaunchLocker is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Value; /** * @dev Emitted when an `amount` is unlocked. */ event Unlocked( address holder, uint amount ); /** * @dev Emitted when an `amount` is locked. */ event Locked( address holder, uint amount ); struct DelegatedAmountAndMonth { uint delegated; uint month; } // holder => tokens mapping (address => uint) private _locked; // holder => tokens mapping (address => PartialDifferences.Value) private _delegatedAmount; mapping (address => DelegatedAmountAndMonth) private _totalDelegatedAmount; // delegationId => tokens mapping (uint => uint) private _delegationAmount; /** * @dev Allows TokenLaunchManager contract to lock an amount of tokens in a * holder wallet. * * Emits a {Locked} event. */ function lock(address holder, uint amount) external allow("TokenLaunchManager") { _locked[holder] = _locked[holder].add(amount); emit Locked(holder, amount); } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new delegations. */ function handleDelegationAdd( address holder, uint delegationId, uint amount, uint month) external allow("DelegationController") { if (_locked[holder] > 0) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint fromLocked = amount; uint locked = _locked[holder].boundedSub(_getAndUpdateDelegatedAmount(holder, currentMonth)); if (fromLocked > locked) { fromLocked = locked; } if (fromLocked > 0) { require(_delegationAmount[delegationId] == 0, "Delegation was already added"); _addToDelegatedAmount(holder, fromLocked, month); _addToTotalDelegatedAmount(holder, fromLocked, month); _delegationAmount[delegationId] = fromLocked; } } } /** * @dev Allows DelegationController contract to notify TokenLaunchLocker * about new undelegation requests. */ function handleDelegationRemoving( address holder, uint delegationId, uint month) external allow("DelegationController") { if (_delegationAmount[delegationId] > 0) { if (_locked[holder] > 0) { _removeFromDelegatedAmount(holder, _delegationAmount[delegationId], month); } delete _delegationAmount[delegationId]; } } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { if (_locked[wallet] > 0) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); uint currentMonth = timeHelpers.getCurrentMonth(); if (_totalDelegatedSatisfiesProofOfUseCondition(wallet) && timeHelpers.calculateProofOfUseLockEndTime( _totalDelegatedAmount[wallet].month, constantsHolder.proofOfUseLockUpPeriodDays() ) <= now) { _unlock(wallet); return 0; } else { uint lockedByDelegationController = _getAndUpdateDelegatedAmount(wallet, currentMonth) .add(delegationController.getLockedInPendingDelegations(wallet)); if (_locked[wallet] > lockedByDelegationController) { return _locked[wallet].boundedSub(lockedByDelegationController); } else { return 0; } } } else { return 0; } } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 0; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } // private /** * @dev Returns and updates the current delegated amount. */ function _getAndUpdateDelegatedAmount(address holder, uint currentMonth) private returns (uint) { return _delegatedAmount[holder].getAndUpdateValue(currentMonth); } /** * @dev Adds a delegated amount to the given month. */ function _addToDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].addToValue(amount, month); } /** * @dev Removes a delegated amount from the given month. */ function _removeFromDelegatedAmount(address holder, uint amount, uint month) private { _delegatedAmount[holder].subtractFromValue(amount, month); } /** * @dev Adds the amount to the total delegated for the given month. */ function _addToTotalDelegatedAmount(address holder, uint amount, uint month) private { require( _totalDelegatedAmount[holder].month == 0 || _totalDelegatedAmount[holder].month <= month, "Cannot add to total delegated in the past"); // do not update counter if it is big enough // because it will override month value if (!_totalDelegatedSatisfiesProofOfUseCondition(holder)) { _totalDelegatedAmount[holder].delegated = _totalDelegatedAmount[holder].delegated.add(amount); _totalDelegatedAmount[holder].month = month; } } /** * @dev Unlocks tokens. * * Emits an {Unlocked} event. */ function _unlock(address holder) private { emit Unlocked(holder, _locked[holder]); delete _locked[holder]; _deleteDelegatedAmount(holder); _deleteTotalDelegatedAmount(holder); } /** * @dev Deletes the delegated amount. */ function _deleteDelegatedAmount(address holder) private { _delegatedAmount[holder].clear(); } /** * @dev Deletes the total delegated amount. */ function _deleteTotalDelegatedAmount(address holder) private { delete _totalDelegatedAmount[holder].delegated; delete _totalDelegatedAmount[holder].month; } /** * @dev Checks whether total delegated satisfies Proof-of-Use. */ function _totalDelegatedSatisfiesProofOfUseCondition(address holder) private view returns (bool) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return _totalDelegatedAmount[holder].delegated.mul(100) >= _locked[holder].mul(constantsHolder.proofOfUseDelegationPercentage()); } } // 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; /** * @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 onlyOwner { 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); addLocker("DelegationController"); addLocker("Punisher"); addLocker("TokenLaunchLocker"); } /** * @dev Allows the Owner to add a contract to the Locker. * * Emits a {LockerWasAdded} event. */ function addLocker(string memory locker) public onlyOwner { _lockers.push(locker); emit LockerWasAdded(locker); } } // 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; 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) onlyAdmin { 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) onlyAdmin { 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 onlyOwner { 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 /* 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 schainId) external; /** * @dev See {SkaleDKG-deleteChannel}. */ function deleteChannel(bytes32 schainId) external; /** * @dev See {SkaleDKG-isLastDKGSuccessful}. */ function isLastDKGSuccessful(bytes32 groupIndex) external view returns (bool); /** * @dev See {SkaleDKG-isChannelOpened}. */ function isChannelOpened(bytes32 schainId) external view returns (bool); } // 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); } 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; } } // 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 /* 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 /* 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 /* StringUtils.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 /* 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 /* 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; 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 "../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; } 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; } 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; /** * @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; /** * @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); } 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; /** * @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.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); } } pragma solidity ^0.6.0; /** * @dev String operations. */ library Strings { /** * @dev Converts a `uint256` to its ASCII `string` 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); uint256 index = digits - 1; temp = value; while (temp != 0) { buffer[index--] = byte(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } }
total resources that schains occupied
uint public sumOfSchainsResources;
401,210
[ 1, 4963, 2703, 716, 18551, 4167, 18928, 2092, 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, 2254, 1071, 2142, 951, 55, 23060, 3805, 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 ]
pragma solidity ^0.4.13; contract ERC20 { function balanceOf(address who) public constant returns (uint); function allowance(address owner, address spender) public constant returns (uint); function transfer(address to, uint value) public returns (bool ok); function transferFrom(address from, address to, uint value) public returns (bool ok); function approve(address spender, uint value) public returns (bool ok); event Transfer(address indexed from, address indexed to, uint value) ; event Approval(address indexed owner, address indexed spender, uint value); } contract SafeMath { function safeMul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert(a == 0 || c / a == b); return c; } function safeDiv(uint a, uint b) internal pure returns (uint) { assert(b > 0); uint c = a / b; assert(a == b * 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; } function max64(uint64 a, uint64 b) internal pure returns (uint64) { return a >= b ? a : b; } function min64(uint64 a, uint64 b) internal pure returns (uint64) { return a < b ? a : b; } function max256(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } function min256(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } } contract StandardToken is ERC20, SafeMath { /* Token supply got increased and a new owner received these tokens */ event Minted(address receiver, uint amount); /* Actual balances of token holders */ mapping(address => uint) balances; /* approve() allowances */ mapping (address => mapping (address => uint)) allowed; function isToken() public pure returns (bool yes) { return true; } function transfer(address _to, uint _value) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _value); balances[_to] = safeAdd(balances[_to], _value); Transfer(msg.sender, _to, _value); return true; } function transferFrom(address _from, address _to, uint _value) public returns (bool success) { uint _allowance = allowed[_from][msg.sender]; balances[_to] = safeAdd(balances[_to], _value); balances[_from] = safeSub(balances[_from], _value); allowed[_from][msg.sender] = safeSub(_allowance, _value); Transfer(_from, _to, _value); return true; } function balanceOf(address _address) constant public returns (uint balance) { return balances[_address]; } function approve(address _spender, uint _value) public returns (bool success) { // 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); return true; } function allowance(address _owner, address _spender) public constant returns (uint remaining) { return allowed[_owner][_spender]; } } contract DESToken is StandardToken { string public name = "Decentralized Escrow Service"; string public symbol = "DES"; uint public decimals = 8;//Разрядность токена uint public HardCapEthereum = 66666000000000000000000 wei;//Максимальное количество собранного Ethereum - 66 666 ETH (задано в wei) //Массив с замороженными адресами, которым запрещено осуществять переводы токенов mapping (address => bool) public noTransfer; // Время начала ICO и время окончания ICO uint constant public TimeStart = 1511956800;//Константа - время начала ICO - 29.11.2017 в 15:00 по Мск uint public TimeEnd = 1514375999;//Время окончания ICO - 27.12.2017 в 14:59:59 по мск // Время окончания бонусных этапов (недель) uint public TimeWeekOne = 1512561600;//1000 DES – начальная цена – 1-ая неделя uint public TimeWeekTwo = 1513166400;//800 DES – 2-ая неделя uint public TimeWeekThree = 1513771200;//666,666 DES – 3-ая неделя uint public TimeTransferAllowed = 1516967999;//Переводы токенов разрешены через месяц (30 суток = 2592000 секунд) после ICO //Пулы ICO (различное время выхода на биржу: запрет некоторым пулам перечисления токенов до определенного времени) uint public PoolPreICO = 0;//Человек в ЛК указывает свой адрес эфириума, на котором хранятся DEST или DESP и ему на этот адрес приходят токены DES в таком же количестве + ещё 50% uint public PoolICO = 0;//Пул ICO - выход на биржу через 1 месяц uint public PoolTeam = 0;//Пул команды - выход на биржу через 1 месяц. 15% uint public PoolAdvisors = 0;//Пул эдвайзеров - выход на биржу через 1 месяц. 7% uint public PoolBounty = 0;//Пул баунти кампании - выход на биржу через 1 месяц. 3% //Стоимость токенов на различных этапах uint public PriceWeekOne = 10000000 wei;//Стоимость токена во время недели 1 uint public PriceWeekTwo = 12500000 wei;//Стоимость токена во время недели 2 uint public PriceWeekThree = 15000000 wei;//Стоимость токена во время недели 3 uint public PriceWeekFour = 17500000 wei;//Стоимость токена во время недели 4 uint public PriceManual = 0 wei;//Стоимость токена, установленная вручную //Технические переменные состояния ICO bool public ICOPaused = false; //Основатель может активировать данный параметр (true), чтобы приостановить ICO на неопределенный срок bool public ICOFinished = false; //ICO было завершено //Технические переменные для хранения данных статистики uint public StatsEthereumRaised = 0 wei;//Переменная сохранит в себе количество собранного Ethereum uint public StatsTotalSupply = 0;//Общее количество выпущенных токенов //События event Buy(address indexed sender, uint eth, uint fbt);//Покупка токенов event TokensSent(address indexed to, uint value);//Токены отправлены на адрес event ContributionReceived(address indexed to, uint value);//Вложение получено event PriceChanged(string _text, uint _tokenPrice);//Стоимость токена установлена вручную event TimeEndChanged(string _text, uint _timeEnd);//Время окончания ICO изменено вручную event TimeTransferAllowanceChanged(string _text, uint _timeAllowance);//Время, до которого запрещены переводы токенов, изменено вручную address public owner = 0x0; //Административные действия 0xE7F7d6cBCdC1fE78F938Bfaca6eA49604cB58D33 address public wallet = 0x0; //Кошелек сбора средств 0x51559efc1acc15bcafc7e0c2fb440848c136a46b function DESToken(address _owner, address _wallet) public payable { owner = _owner; wallet = _wallet; balances[owner] = 0; balances[wallet] = 0; } modifier onlyOwner() { require(msg.sender == owner); _; } //Приостановлено ли ICO или запущено modifier isActive() { require(!ICOPaused); _; } //Транзакция получена - запустить функцию покупки function() public payable { buy(); } //Установка стоимости токена вручную. Если значение больше 0, токены продаются по установленной вручную цене function setTokenPrice(uint _tokenPrice) external onlyOwner { PriceManual = _tokenPrice; PriceChanged("New price is ", _tokenPrice); } //Установка времени окончания ICO function setTimeEnd(uint _timeEnd) external onlyOwner { TimeEnd = _timeEnd; TimeEndChanged("New ICO End Time is ", _timeEnd); } //Установка времени, до которого запрещены переводы токенов function setTimeTransferAllowance(uint _timeAllowance) external onlyOwner { TimeTransferAllowed = _timeAllowance; TimeTransferAllowanceChanged("Token transfers will be allowed at ", _timeAllowance); } // Запретить определенному покупателю осуществлять переводы его токенов // @параметр target Адрес покупателя, на который установить запрет // @параметр allow Установить запрет (true) или запрет снят (false) function disallowTransfer(address target, bool disallow) external onlyOwner { noTransfer[target] = disallow; } //Завершить ICO и создать пулы токенов (команда, баунти, эдвайзеры) function finishCrowdsale() external onlyOwner returns (bool) { if (ICOFinished == false) { PoolTeam = StatsTotalSupply*1998/10000;//Пул команды - выход на биржу через 1 месяц. 15% PoolAdvisors = StatsTotalSupply*9324/100000;//Пул эдвайзеров - выход на биржу через 1 месяц. 7% PoolBounty = StatsTotalSupply*3996/100000;//Пул баунти кампании - выход на биржу через 1 месяц. 3% uint poolTokens = 0; poolTokens = safeAdd(poolTokens,PoolTeam); poolTokens = safeAdd(poolTokens,PoolAdvisors); poolTokens = safeAdd(poolTokens,PoolBounty); //Зачислить на счет основателя токены пула команды, эдвайзеров и баунти require(poolTokens>0);//Количество токенов должно быть больше 0 balances[owner] = safeAdd(balances[owner], poolTokens); StatsTotalSupply = safeAdd(StatsTotalSupply, poolTokens);//Обновляем общее количество выпущенных токенов Transfer(0, this, poolTokens); Transfer(this, owner, poolTokens); ICOFinished = true;//ICO завершено } } //Функция возвращает текущую стоимость в wei 1 токена function price() public constant returns (uint) { if(PriceManual > 0){return PriceManual;} if(now >= TimeStart && now < TimeWeekOne){return PriceWeekOne;} if(now >= TimeWeekOne && now < TimeWeekTwo){return PriceWeekTwo;} if(now >= TimeWeekTwo && now < TimeWeekThree){return PriceWeekThree;} if(now >= TimeWeekThree){return PriceWeekFour;} } // Создать `amount` токенов и отправить их `target` // @параметр target Адрес получателя токенов // @параметр amount Количество создаваемых токенов function sendPreICOTokens(address target, uint amount) onlyOwner external { require(amount>0);//Количество токенов должно быть больше 0 balances[target] = safeAdd(balances[target], amount); StatsTotalSupply = safeAdd(StatsTotalSupply, amount);//Обновляем общее количество выпущенных токенов Transfer(0, this, amount); Transfer(this, target, amount); PoolPreICO = safeAdd(PoolPreICO,amount);//Обновляем общее количество токенов в пуле Pre-ICO } // Создать `amount` токенов и отправить их `target` // @параметр target Адрес получателя токенов // @параметр amount Количество создаваемых токенов function sendICOTokens(address target, uint amount) onlyOwner external { require(amount>0);//Количество токенов должно быть больше 0 balances[target] = safeAdd(balances[target], amount); StatsTotalSupply = safeAdd(StatsTotalSupply, amount);//Обновляем общее количество выпущенных токенов Transfer(0, this, amount); Transfer(this, target, amount); PoolICO = safeAdd(PoolICO,amount);//Обновляем общее количество токенов в пуле Pre-ICO } // Перечислить `amount` командных токенов на адрес `target` со счета основателя (администратора) после завершения ICO // @параметр target Адрес получателя токенов // @параметр amount Количество перечисляемых токенов function sendTeamTokens(address target, uint amount) onlyOwner external { require(ICOFinished);//Возможно только после завершения ICO require(amount>0);//Количество токенов должно быть больше 0 require(amount>=PoolTeam);//Количество токенов должно быть больше или равно размеру пула команды require(balances[owner]>=PoolTeam);//Количество токенов должно быть больше или равно балансу основателя balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя) balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя PoolTeam = safeSub(PoolTeam, amount);//Обновляем общее количество токенов пула команды TokensSent(target, amount);//Публикуем событие в блокчейн Transfer(owner, target, amount);//Осуществляем перевод noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов } // Перечислить `amount` токенов эдвайзеров на адрес `target` со счета основателя (администратора) после завершения ICO // @параметр target Адрес получателя токенов // @параметр amount Количество перечисляемых токенов function sendAdvisorsTokens(address target, uint amount) onlyOwner external { require(ICOFinished);//Возможно только после завершения ICO require(amount>0);//Количество токенов должно быть больше 0 require(amount>=PoolAdvisors);//Количество токенов должно быть больше или равно размеру пула эдвайзеров require(balances[owner]>=PoolAdvisors);//Количество токенов должно быть больше или равно балансу основателя balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя) balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя PoolAdvisors = safeSub(PoolAdvisors, amount);//Обновляем общее количество токенов пула эдвайзеров TokensSent(target, amount);//Публикуем событие в блокчейн Transfer(owner, target, amount);//Осуществляем перевод noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов } // Перечислить `amount` баунти токенов на адрес `target` со счета основателя (администратора) после завершения ICO // @параметр target Адрес получателя токенов // @параметр amount Количество перечисляемых токенов function sendBountyTokens(address target, uint amount) onlyOwner external { require(ICOFinished);//Возможно только после завершения ICO require(amount>0);//Количество токенов должно быть больше 0 require(amount>=PoolBounty);//Количество токенов должно быть больше или равно размеру пула баунти require(balances[owner]>=PoolBounty);//Количество токенов должно быть больше или равно балансу основателя balances[owner] = safeSub(balances[owner], amount);//Вычитаем токены у администратора (основателя) balances[target] = safeAdd(balances[target], amount);//Добавляем токены на счет получателя PoolBounty = safeSub(PoolBounty, amount);//Обновляем общее количество токенов пула баунти TokensSent(target, amount);//Публикуем событие в блокчейн Transfer(owner, target, amount);//Осуществляем перевод noTransfer[target] = true;//Вносим получателя в базу аккаунтов, которым 1 месяц после ICO запрещено осуществлять переводы токенов } //Функция покупки токенов на ICO function buy() public payable returns(bool) { require(msg.sender != owner);//Основатели не могут покупать токены require(msg.sender != wallet);//Основатели не могут покупать токены require(!ICOPaused);//Покупка разрешена, если ICO не приостановлено require(!ICOFinished);//Покупка разрешена, если ICO не завершено require(msg.value >= price());//Полученная сумма в wei должна быть больше стоимости 1 токена require(now >= TimeStart);//Условие продажи - ICO началось require(now <= TimeEnd);//Условие продажи - ICO не завершено uint tokens = msg.value/price();//Количество токенов, которое должен получить покупатель require(safeAdd(StatsEthereumRaised, msg.value) <= HardCapEthereum);//Собранный эфир не больше hard cap require(tokens>0);//Количество токенов должно быть больше 0 wallet.transfer(msg.value);//Отправить полученные ETH на кошелек сбора средств //Зачисление токенов на счет покупателя balances[msg.sender] = safeAdd(balances[msg.sender], tokens); StatsTotalSupply = safeAdd(StatsTotalSupply, tokens);//Обновляем общее количество выпущенных токенов Transfer(0, this, tokens); Transfer(this, msg.sender, tokens); StatsEthereumRaised = safeAdd(StatsEthereumRaised, msg.value);//Обновляем цифру собранных ETH PoolICO = safeAdd(PoolICO, tokens);//Обновляем размер пула ICO //Записываем события в блокчейн Buy(msg.sender, msg.value, tokens); TokensSent(msg.sender, tokens); ContributionReceived(msg.sender, msg.value); return true; } function EventEmergencyStop() public onlyOwner() {ICOPaused = true;}//Остановить ICO (в случае непредвиденных обстоятельств) function EventEmergencyContinue() public onlyOwner() {ICOPaused = false;}//Продолжить ICO //Если переводы токенов для всех участников еще не разрешены (1 месяц после ICO), проверяем, участник ли это Pre-ICO. Если нет, запрещаем перевод function transfer(address _to, uint _value) public isActive() returns (bool success) { if(now >= TimeTransferAllowed){ if(noTransfer[msg.sender]){noTransfer[msg.sender] = false;}//Если переводы разрешены по времени, разрешаем их отправителю } if(now < TimeTransferAllowed){require(!noTransfer[msg.sender]);}//Если переводы еще не разрешены по времени, переводить могут только участники Pre-ICO return super.transfer(_to, _value); } /** * ERC 20 Standard Token interface transfer function * * Prevent transfers until halt period is over. */ function transferFrom(address _from, address _to, uint _value) public isActive() returns (bool success) { if(now >= TimeTransferAllowed){ if(noTransfer[msg.sender]){noTransfer[msg.sender] = false;}//Если переводы разрешены по времени, разрешаем их отправителю } if(now < TimeTransferAllowed){require(!noTransfer[msg.sender]);}//Если переводы еще не разрешены по времени, переводить могут только участники Pre-ICO return super.transferFrom(_from, _to, _value); } //Сменить владельца function changeOwner(address _to) public onlyOwner() { balances[_to] = balances[owner]; balances[owner] = 0; owner = _to; } //Сменить адрес кошелька для сбора средств function changeWallet(address _to) public onlyOwner() { balances[_to] = balances[wallet]; balances[wallet] = 0; wallet = _to; } }
Человек в ЛК указывает свой адрес эфириума, на котором хранятся DEST или DESP и ему на этот адрес приходят токены DES в таком же количестве + ещё 50%
uint public PoolPreICO = 0;
7,219,863
[ 1, 145, 105, 145, 118, 145, 124, 145, 127, 145, 115, 145, 118, 145, 123, 225, 145, 115, 225, 145, 254, 145, 253, 225, 146, 230, 145, 123, 145, 113, 145, 120, 146, 238, 145, 115, 145, 113, 145, 118, 146, 229, 225, 146, 228, 145, 115, 145, 127, 145, 122, 225, 145, 113, 145, 117, 146, 227, 145, 118, 146, 228, 225, 146, 240, 146, 231, 145, 121, 146, 227, 145, 121, 146, 230, 145, 125, 145, 113, 16, 225, 145, 126, 145, 113, 225, 145, 123, 145, 127, 146, 229, 145, 127, 146, 227, 145, 127, 145, 125, 225, 146, 232, 146, 227, 145, 113, 145, 126, 146, 242, 146, 229, 146, 228, 146, 242, 2030, 882, 225, 145, 121, 145, 124, 145, 121, 2030, 3118, 225, 145, 121, 225, 145, 118, 145, 125, 146, 230, 225, 145, 126, 145, 113, 225, 146, 240, 146, 229, 145, 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, 202, 11890, 1071, 8828, 1386, 2871, 51, 273, 374, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.4; /** * @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; } } /** * @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) { 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 Contracts guidelines: functions revert * instead 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 `amount` of tokens from `sender` to `recipient`. * * This 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); _afterTokenTransfer(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); _afterTokenTransfer(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); _afterTokenTransfer(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 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 Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been 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 _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } /** * @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.3.0, sets of type `bytes32` (`Bytes32Set`), `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]; } // Bytes32Set struct Bytes32Set { 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(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _add(set._inner, 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(Bytes32Set storage set, bytes32 value) internal returns (bool) { return _remove(set._inner, value); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(Bytes32Set storage set, bytes32 value) internal view returns (bool) { return _contains(set._inner, value); } /** * @dev Returns the number of values in the set. O(1). */ function length(Bytes32Set 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(Bytes32Set storage set, uint256 index) internal view returns (bytes32) { return _at(set._inner, 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(uint160(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(uint160(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(uint160(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(uint160(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)); } } // helper methods for interacting with ERC20 tokens and sending ETH that do not consistently return true/false library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } function safeTransferNative(address to, uint value) internal { (bool success,) = to.call{value:value}(new bytes(0)); require(success, 'TransferHelper: Native_TRANSFER_FAILED'); } } /** * @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); } } /** * @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); } } } } /** * @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"); } } } /** * @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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. 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. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @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) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // 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 (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): 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), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * 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)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } /** * @dev LaunchPad Pool. */ contract LaunchPadPool is Ownable, EIP712{ using SafeMath for uint256; using SafeERC20 for IERC20; using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private _governors; // Info of each LaunchPad Project. struct LaunchPadInfo { uint8 launchStatus; // launchPad Project status, 0 pending, 1 paying, 2 claiming IERC20 launchToken; //launchpad token IERC20 payToken; // pay token uint256 timeStart; // launchpad start. uint256 timeEnd ; // launchpad end. uint256 tokenAmount; //token amount. uint256 priceBasedPayToken; //pay, decimals is 8 uint256 maxPerAddress; //cap limit uint256 launchMaxPay; //pay cap limit uint256 releaseStart; // claim time start uint256 lockPeriod; //lock time uint256 totalAmount; // Total amount of current pool deposit. } LaunchPadInfo[] public launchPadInfo; //all launchPadInfo // Info of each user. struct UserInfo { uint256 paidAmount; // How many pay tokens the user has provided. uint256 lockedAmount;// user locked token Amount uint256 pickedAmount; //user picked amount. } // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; event Claimed(address indexed owner, uint8 lauchID, address rewardToken, uint256 rewardAmount, uint256 refundAmount); event Deposited(address indexed sender, uint8 lauchID, address paidToken, uint256 paidAmount ); event GovernorAdded( address _user); event GovernorDeleted( address _user); bytes32 constant public LAUNCHPAD_CALL_HASH_TYPE = keccak256("getLaunchPad(address receiver,uint8 lanchID,uint256 rewardAmount,uint256 refundAmount)"); address public immutable cSigner; /** * @dev Constructor. */ constructor(address _signer) EIP712("LaunchPadPool", "1"){ cSigner = _signer; } // Add a new launchpad project to the pool. Can only be called by the owner. function add( IERC20 _launchToken,IERC20 _payToken, uint256 _timeStart, uint256 _timeEnd , uint256 _tokenAmount,uint256 _priceBasedPayToken,uint256 _maxPerAddress, uint256 _launchMaxPay, uint256 _releaseStart, uint256 _lockPeriod) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); launchPadInfo.push(LaunchPadInfo({ launchStatus : 0, launchToken : _launchToken, payToken : _payToken, timeStart : _timeStart, timeEnd : _timeEnd, tokenAmount : _tokenAmount, priceBasedPayToken : _priceBasedPayToken, maxPerAddress : _maxPerAddress, launchMaxPay : _launchMaxPay, releaseStart : _releaseStart, lockPeriod : _lockPeriod, totalAmount : 0 })); } function setLaunchPadInfo(uint8 _pid, IERC20 _launchToken,IERC20 _payToken, uint256 _timeStart, uint256 _timeEnd , uint256 _tokenAmount,uint256 _priceBasedPayToken,uint256 _maxPerAddress, uint256 _launchMaxPay, uint256 _releaseStart, uint256 _lockPeriod) public onlyGovernor { require( _timeStart > block.timestamp && _timeEnd > _timeStart, "invalid time limit"); require( _pid < launchPadInfo.length, "invalid pid"); LaunchPadInfo storage pool = launchPadInfo[_pid]; if( pool.launchStatus == 0 ){ pool.launchToken = _launchToken; pool.payToken = _payToken; pool.timeStart = _timeStart; pool.timeEnd = _timeEnd; pool.tokenAmount = _tokenAmount; pool.priceBasedPayToken = _priceBasedPayToken; pool.maxPerAddress = _maxPerAddress; pool.launchMaxPay = _launchMaxPay; pool.releaseStart = _releaseStart; pool.lockPeriod = _lockPeriod; } } function setLaunchPadInfo(uint8 _pid, uint8 _launchStatus ) public onlyGovernor { LaunchPadInfo storage pool = launchPadInfo[_pid]; require( _launchStatus > pool.launchStatus, "invalid status"); pool.launchStatus = _launchStatus; } //user deposit to enter launchpad function deposit(uint8 _pid, uint256 _amount) public { LaunchPadInfo storage pool = launchPadInfo[_pid]; UserInfo storage user = userInfo[_pid][ msg.sender ]; require( pool.launchStatus == 1 , "invalid status"); require( pool.timeEnd > block.timestamp, "invalid time"); //deposit TransferHelper.safeTransferFrom( address(pool.payToken), msg.sender, address(this), _amount); user.paidAmount = user.paidAmount.add(_amount); pool.totalAmount = pool.totalAmount.add(_amount); emit Deposited( msg.sender, _pid, address(pool.payToken), _amount); } //claim reward token quota function claim(uint8 _pid, uint256 _rewardAmount, uint256 _refundAmount, uint8 v, bytes32 r, bytes32 s) external { LaunchPadInfo storage pool = launchPadInfo[_pid]; UserInfo storage user = userInfo[_pid][ msg.sender ]; require( pool.timeEnd <= block.timestamp, "waiting for end"); require( user.paidAmount > 0 ,"invalid user"); require( pool.maxPerAddress >= _rewardAmount ,"limit max quota"); //check rewardamount &refundamount uint256 tokenNeedPaid = _rewardAmount.mul( pool.priceBasedPayToken).div(1e8); require( user.paidAmount.sub(_refundAmount) >= tokenNeedPaid, "check refund quota"); //only once time claim if( user.lockedAmount > 0 ){ return; } user.lockedAmount = _rewardAmount; bytes32 digest = keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", ECDSA.toTypedDataHash(_domainSeparatorV4(), keccak256(abi.encode(LAUNCHPAD_CALL_HASH_TYPE, msg.sender, _pid, _rewardAmount, _refundAmount)) ))); require(ecrecover(digest, v, r, s) == cSigner, "LaunchPadPool: Invalid signer"); uint256 _pickedAmount = _rewardAmount; if( pool.lockPeriod > 0 ){ _pickedAmount = 0; if( block.timestamp > pool.releaseStart ){ _pickedAmount = _rewardAmount.mul(block.timestamp.sub(pool.releaseStart)).div(pool.lockPeriod); if( _pickedAmount > _rewardAmount ){ _pickedAmount = _rewardAmount; } } } user.pickedAmount = _pickedAmount; if( _pickedAmount > 0 ){ TransferHelper.safeTransfer( address(pool.launchToken), msg.sender , _pickedAmount ); } if( _refundAmount > 0 ){ TransferHelper.safeTransfer( address(pool.payToken), msg.sender , _refundAmount ); } emit Claimed( msg.sender , _pid, address(pool.launchToken), _rewardAmount, _refundAmount ); } //claim release reward token function claimReward(uint8 _pid) public { LaunchPadInfo storage pool = launchPadInfo[_pid]; UserInfo storage user = userInfo[_pid][ msg.sender ]; if( user.lockedAmount > user.pickedAmount ){ uint256 _pickedAmount = 0; if( block.timestamp > pool.releaseStart ){ _pickedAmount = user.lockedAmount.mul(block.timestamp.sub(pool.releaseStart)).div(pool.lockPeriod); if( _pickedAmount > user.lockedAmount ){ _pickedAmount = user.lockedAmount; } _pickedAmount = _pickedAmount.sub( user.pickedAmount ); user.pickedAmount = user.pickedAmount.add(_pickedAmount); TransferHelper.safeTransfer( address(pool.launchToken), msg.sender , _pickedAmount ); } } } //emergency token function withdrawEmergency(address tokenaddress,address to) public onlyOwner{ TransferHelper.safeTransfer( tokenaddress, to , IERC20(tokenaddress).balanceOf(address(this))); } function withdrawEmergencyNative(address to , uint256 amount) public onlyOwner{ TransferHelper.safeTransferNative(to, amount); } //governor function addGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorAdded( _governor ); return EnumerableSet.add(_governors, _governor); } function delGovernor(address _governor) public onlyOwner returns (bool) { require(_governor != address(0), "_governor is the zero address"); emit GovernorDeleted( _governor ); return EnumerableSet.remove(_governors, _governor); } function getGovernorLength() public view returns (uint256) { return EnumerableSet.length(_governors); } function isGovernor(address account) public view returns (bool) { return EnumerableSet.contains(_governors, account); } function getGovernor(uint256 _index) public view returns (address){ require(_index <= getGovernorLength() - 1, "index out of bounds"); return EnumerableSet.at(_governors, _index); } // modifier for governor function modifier onlyGovernor() { require(isGovernor(msg.sender) || owner() == msg.sender , "caller is not the governor"); _; } }
* @dev Library for managing 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 { using EnumerableSet for EnumerableSet.AddressSet; EnumerableSet.AddressSet private mySet; } ``` As of v3.3.0, sets of type `bytes32` (`Bytes32Set`), `address` (`AddressSet`) and `uint256` (`UintSet`) are supported./ 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.
library EnumerableSet { function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } struct Set { bytes32[] _values; mapping (bytes32 => uint256) _indexes; } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); set._indexes[value] = set._values.length; return true; return false; } } } else { function _remove(Set storage set, bytes32 value) private returns (bool) { uint256 valueIndex = set._indexes[value]; uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; bytes32 lastvalue = set._values[lastIndex]; set._values[toDeleteIndex] = lastvalue; set._values.pop(); delete set._indexes[value]; return true; return false; } } else { }
489,432
[ 1, 9313, 364, 30632, 1953, 18, 11511, 1240, 326, 3751, 1790, 30, 300, 17219, 854, 3096, 16, 3723, 16, 471, 5950, 364, 15782, 316, 5381, 813, 261, 51, 12, 21, 13, 2934, 300, 17219, 854, 3557, 690, 316, 531, 12, 82, 2934, 2631, 28790, 854, 7165, 603, 326, 9543, 18, 31621, 6835, 5090, 288, 377, 1450, 6057, 25121, 694, 364, 6057, 25121, 694, 18, 1887, 694, 31, 377, 6057, 25121, 694, 18, 1887, 694, 3238, 3399, 694, 31, 289, 31621, 2970, 434, 331, 23, 18, 23, 18, 20, 16, 1678, 434, 618, 1375, 3890, 1578, 68, 21863, 2160, 1578, 694, 68, 3631, 1375, 2867, 68, 21863, 1887, 694, 24065, 471, 1375, 11890, 5034, 68, 21863, 5487, 694, 24065, 854, 3260, 18, 19, 2974, 2348, 333, 5313, 364, 3229, 1953, 598, 487, 12720, 981, 31239, 487, 3323, 16, 732, 1045, 518, 316, 6548, 434, 279, 5210, 1000, 618, 598, 1731, 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, 12083, 6057, 25121, 694, 288, 203, 203, 565, 445, 389, 5771, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 203, 565, 445, 389, 5205, 1345, 5912, 12, 203, 3639, 1758, 628, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 3844, 203, 97, 203, 203, 565, 1958, 1000, 288, 203, 3639, 1731, 1578, 8526, 389, 2372, 31, 203, 203, 3639, 2874, 261, 3890, 1578, 516, 2254, 5034, 13, 389, 11265, 31, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 565, 445, 389, 1289, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 3238, 1135, 261, 6430, 13, 288, 203, 3639, 309, 16051, 67, 12298, 12, 542, 16, 460, 3719, 288, 203, 5411, 444, 6315, 2372, 18, 6206, 12, 1132, 1769, 203, 5411, 444, 6315, 11265, 63, 1132, 65, 273, 444, 6315, 2372, 18, 2469, 31, 203, 5411, 327, 638, 31, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 565, 289, 203, 203, 3639, 289, 469, 288, 203, 565, 445, 389, 4479, 12, 694, 2502, 444, 16, 1731, 1578, 460, 13, 2 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.18; pragma experimental ABIEncoderV2; /// @title Utility functions /// @author Giovanni Rescinito /// @notice math utilities and sorting functions library Utils { //Constants uint constant public C = 10**6; // constant used to scale value //Data Structures /// @notice container used to maintain agent id and score together struct Element { uint id; // agent id uint value; // score } //Events event ClustersAssignmentsGenerated(uint[][] assignments); event AssignmentGenerated(uint[] assignments); event PartitionsGenerated(uint[][] partition); event AlgorithmInfo(uint nWinners, uint matrixSizes, uint nPartitions); event ScoreMatrixConstructed(uint[][] scoreMatrix); event QuotasCalculated(uint[] quotas); event Winners(Element[] winners); //Math functions /// @notice returns the smallest integer value that is bigger than or equal to a number, using scaling by C /// @param x the value to be rounded /// @return the rounded value function ceil(uint x) view public returns (uint){ return ((x + C - 1) / C) * C; } /// @notice returns the largest integer value that is less than or equal to a number, using scaling by C /// @param x the value to be rounded /// @return the rounded value function floor(uint x) view public returns (uint){ return (x/C)*C; } /// @notice returns the nearest integer to a number, using scaling by C /// @param x the value to be rounded /// @return the rounded value function round(uint x) view public returns (uint){ if (x-floor(x) < C/2){ return floor(x); }else{ return ceil(x); } } /// @notice produces a range of n values, from 0 to n-1 /// @param upper the number values to produce /// @return a list of integer values, from 0 to upper-1 function range(uint upper) public returns (uint[] memory) { uint[] memory a = new uint[](upper); for (uint i=0;i<upper;i++){ a[i] = i; } return a; } //Sorting functions /// @notice sorts a list of values in ascending order /// @param data the list of values to order /// @return the ordered values with the corresponding ordered indices /// base implementation provided by https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f function sort(uint[] memory data) public returns(Element[] memory) { Element[] memory dataElements = new Element[](data.length); for (uint i=0; i<data.length; i++){ dataElements[i] = Element(i, data[i]); } quickSort(dataElements, int(0), int(dataElements.length - 1)); return dataElements; } /// @notice implements sorting using quicksort algorithm /// @param arr the list of elements to order /// @param left the starting index of the subset of values ordered /// @param right the final index of the subset of values ordered /// base implementation provided by https://gist.github.com/subhodi/b3b86cc13ad2636420963e692a4d896f function quickSort(Element[] memory arr, int left, int right) internal{ int i = left; int j = right; if(i==j) return; uint pivot = arr[uint(left + (right - left) / 2)].value; while (i <= j) { while (arr[uint(i)].value < pivot) i++; while (pivot < arr[uint(j)].value) j--; if (i <= j) { (arr[uint(i)], arr[uint(j)]) = (arr[uint(j)], arr[uint(i)]); i++; j--; } } if (left < j) quickSort(arr, left, j); if (i < right) quickSort(arr, i, right); } } /// @title Set containing proposals /// @author Giovanni Rescinito /// @notice proposals submitted by agents, along with the corresponding assignment and commitment library Proposals{ //Data Structures /// @notice Data structure related to a single proposal struct Proposal { bytes work; // work submitted uint[] assignment; // assignment associated to the proposal bytes32 commitment; // commitment associated to the proposal uint[] evaluations; // evaluations associated to the proposal } /// @notice Set data structure containing proposals struct Set { Proposal[] elements; // list of the proposals submitted mapping (bytes32 => uint) idx; // maps the proposal to the index in the list } //Events event ProposalSubmitted(bytes32 hashed); event ProposalsUpdate(Proposal[] e); event Committed(uint tokenId, bytes32 commitment); event Revealed(bytes32 commitment,uint randomness, uint[] assignments, uint[] evaluations, uint tokenId); /// @notice checks that the index corresponds to an existing value in the set /// @param s the set to check /// @param index the index to check modifier checkIndex(Set storage s, uint index) { require(index >= 0 && index < s.elements.length, "Set out of bounds"); _; } //Utility /// @notice returns the number of proposals submitted /// @param s set containing proposals /// @return the length of the list contained in the set function length(Set storage s) public returns (uint) { return s.elements.length; } /// @notice hashes the work submitted to obtain the index of the set /// @param work the work to be hashed /// @return the keccak256 hash of the work function encodeWork(bytes memory work) public returns (bytes32){ return keccak256(abi.encodePacked(work)); } //Setters /// @notice stores a proposal in the set /// @param s set containing proposals /// @param work the work submitted /// @return the proposal created from the work function propose(Set storage s, bytes memory work) public returns (Proposal memory){ bytes32 h = encodeWork(work); uint index = s.idx[h]; require(index == 0, "Work already proposed"); Proposal memory p = Proposal(work,new uint[](0), 0x0,new uint[](0)); s.elements.push(p); s.idx[h] = s.elements.length; emit ProposalSubmitted(h); return p; } /// @notice updates the assignment in the set given a specific index /// @param s set containing proposals /// @param index index in the list of elements of the set to update /// @param assignment the assignment to be stored function updateAssignment(Set storage s, uint index, uint[] memory assignment) public checkIndex(s, index) { s.elements[index].assignment = assignment; } /// @notice stores the commitment in the proposal considered /// @param s set containing proposals /// @param tokenId token associated to the proposal for which the evaluations' commitment should be stored /// @param com the commitment to save function setCommitment(Set storage s, uint tokenId, bytes32 com) public checkIndex(s, tokenId - 1){ s.elements[tokenId - 1].commitment = com; emit Committed(tokenId, com); } /// @notice stores the evaluations related to the proposal considered /// @param s set containing proposals /// @param tokenId token associated to the proposal for which the evaluations should be stored /// @param assignments the assignment considered /// @param evaluations the evaluations proposed function setEvaluations(Set storage s, uint tokenId, uint[] memory assignments, uint[] memory evaluations) public checkIndex(s, tokenId - 1){ require(assignments.length == evaluations.length, "Incoherent dimensions between assignments and evaluations"); Proposal storage p = s.elements[tokenId - 1]; p.assignment = assignments; p.evaluations = new uint[](assignments.length); for (uint i=0; i<assignments.length;i++){ p.evaluations[i] = evaluations[i]; } emit ProposalsUpdate(s.elements); } //Getters /// @param s set containing proposals /// @return the list of proposals stored in the set function getProposals(Set storage s) public returns (Proposal[]memory) { return s.elements; } /// @param p proposal considered /// @return the assignment associated to the proposal function getAssignment(Proposal memory p) public returns (uint[] memory) { return p.assignment; } /// @param p proposal considered /// @return the work associated to the proposal function getWork(Proposal memory p) public returns (bytes memory) { return p.work; } /// @param p proposal considered /// @return the commitment associated to the proposal function getCommitment(Proposal memory p) public returns (bytes32){ return p.commitment; } /// @param p proposal considered /// @return the evaluations associated to the proposal function getEvaluations(Proposal memory p) public returns (uint[] memory){ return p.evaluations; } /// @param s set containing proposals /// @param p proposal considered /// @return the index associated to the proposal function getId(Set storage s, Proposal memory p) public returns (uint){ return s.idx[encodeWork(p.work)]; } /// @param s set containing proposals /// @param index the index in the list of proposals /// @return the proposal associated to the index in the list function getProposalAt(Set storage s, uint index) public checkIndex(s, index) returns (Proposal memory) { return s.elements[index]; } /// @param s set containing proposals /// @param tokenId the token associated to the proposal /// @return the proposal associated to the token provided function getProposalByToken(Set storage s, uint tokenId) public returns (Proposal memory){ return getProposalAt(s, tokenId - 1); } } /// @title Dictionary storing allocations /// @author Giovanni Rescinito /// @notice Data structure implemented as an iterable map, produced during the apportionment algorithm to store allocations library Allocations { //Data Structures /// @notice Data structure related to a single allocation struct Allocation { uint[] shares; // winners per cluster uint p; // probability of the allocation } /// @notice Dictionary containing allocations struct Map { Allocation[] elements; // list of allocations mapping (bytes32 => uint) idx; // maps key to index in the list } //Events event AllocationsGenerated (Allocation[] allocations); event AllocationSelected(uint[] allocation); //Setters /// @notice creates a new allocation or updates the probability of an existing one /// @param map dictionary containing allocations /// @param a winners per cluster to insert/modify /// @param p probability of the specific allocation function setAllocation(Map storage map, uint[] memory a, uint p) public { bytes32 h = keccak256(abi.encodePacked(a)); uint index = map.idx[h]; if (index == 0) { map.elements.push(Allocation(a, p)); map.idx[h] = map.elements.length; }else { map.elements[index - 1].p = p; } } /// @notice updates the winners per cluster of an allocation specified by its index /// @param map dictionary containing allocations /// @param index index of the allocation to modify /// @param shares winners per cluster to update function updateShares(Map storage map, Allocation memory a, uint[] memory shares) public { bytes32 h = keccak256(abi.encodePacked(a.shares)); uint index = map.idx[h]; require(index != 0, "Allocation not present"); map.elements[index - 1].shares = shares; } //Getters /// @param map dictionary containing allocations /// @return the list of allocations stored function getAllocations(Map storage map) public returns (Allocation[]memory) { return map.elements; } /// @param a allocation for which the probability is required /// @return the probability associated to the allocation function getP(Allocation memory a) public returns (uint) { return a.p; } /// @param a allocation for which the winners per cluster are required /// @return the winners per cluster associated to the allocation function getShares(Allocation memory a) public returns (uint[] memory) { return a.shares; } /// @param map dictionary containing allocations /// @param index allocation for which the probability is required /// @return the allocation stored at a specified index function getAllocationAt(Map storage map, uint index) public returns (Allocation memory) { require(index >= 0 && index < map.elements.length, "Map out of bounds"); return map.elements[index]; } /// @param a allocation from which the winners per cluster are needed /// @param index cluster to select /// @return the number of winners in a specified allocation for a fixed cluster function getValueInAllocation(Allocation memory a, uint index) public returns (uint) { require(index >= 0 && index < a.shares.length, "Allocation out of bounds"); return a.shares[index]; } }
@notice returns the largest integer value that is less than or equal to a number, using scaling by C @param x the value to be rounded @return the rounded value
function floor(uint x) view public returns (uint){ return (x/C)*C; }
5,422,477
[ 1, 6154, 326, 12756, 3571, 460, 716, 353, 5242, 2353, 578, 3959, 358, 279, 1300, 16, 1450, 10612, 635, 385, 225, 619, 326, 460, 358, 506, 16729, 327, 326, 16729, 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, 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, 6346, 12, 11890, 619, 13, 1476, 1071, 1135, 261, 11890, 15329, 203, 3639, 327, 261, 92, 19, 39, 17653, 39, 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 ]